コード
image-viewer.rb
USE_THUMB_CACHE = !ARGV.delete('--cache').nil?
require 'sinatra'
require 'puma'
require 'uri'
require 'erb'
require 'json'
require 'vips'
require 'digest'
require 'fileutils'
THUMB_CACHE_DIR = File.expand_path('.thumb_cache', __dir__)
MAX_CACHE_BYTES = 1 * 1024 * 1024 * 1024
if USE_THUMB_CACHE
puts "📦 サムネイルキャッシュ: 有効"
if Dir.exist?(THUMB_CACHE_DIR)
total_size = Dir.glob(File.join(THUMB_CACHE_DIR, '*')).sum { |f| File.file?(f) ? File.size(f) : 0 }
if total_size > MAX_CACHE_BYTES
FileUtils.rm_rf(THUMB_CACHE_DIR)
end
end
FileUtils.mkdir_p(THUMB_CACHE_DIR)
else
puts "⚡ サムネイルキャッシュ: 無効(オンメモリ生成)"
end
set :bind, '0.0.0.0'
set :port, 4567
ROOTS = {
'Pictures' => '/home/username',
'External' => '/media/username'
}.transform_values { |path| File.expand_path(path) }.freeze
IMAGE_EXTS = %w[.jpg .jpeg .png .gif .webp .bmp].freeze
BOOKMARK_FILE = File.expand_path('bookmarks.json', __dir__)
VISIT_GEN_FILE = File.expand_path('visit_gen.txt', __dir__)
helpers do
def natural_sort_key(str)
str.downcase.gsub(/\d+/) { |num| num.rjust(20, '0') }
end
def sort_entries(dir_path, names, sort_mode)
if sort_mode == 'mtime'
names.sort_by do |name|
mtime = File.mtime(File.join(dir_path, name)).to_f rescue 0.0
[-mtime, natural_sort_key(name)]
end
else
names.sort_by { |name| natural_sort_key(name) }
end
end
def resolve_path(virtual_path)
decoded = virtual_path.to_s.sub(%r{^/}, '')
return nil if decoded.empty?
root_name, sub_path = decoded.split('/', 2)
base_dir = ROOTS[root_name]
return nil unless base_dir && File.exist?(base_dir)
target = sub_path ? File.expand_path(File.join(base_dir, sub_path)) : base_dir
return nil unless target == base_dir || target.start_with?(base_dir + '/')
target
end
def encode_path(path)
path.split('/').map { |part| URI.encode_uri_component(part) }.join('/')
end
def load_bookmarks
return Array.new unless File.exist?(BOOKMARK_FILE)
JSON.parse(File.read(BOOKMARK_FILE))
rescue JSON::ParserError
Array.new
end
def save_bookmarks(list)
File.write(BOOKMARK_FILE, JSON.pretty_generate(list.uniq.sort))
end
def current_visit_gen
File.exist?(VISIT_GEN_FILE) ? File.read(VISIT_GEN_FILE).to_i : 1
end
end
post '/reset_visited/*' do
new_gen = current_visit_gen + 1
File.write(VISIT_GEN_FILE, new_gen.to_s)
v_path = params['splat'].first.to_s.sub(%r{/$}, '')
sort_q = params['sort'] == 'mtime' ? "sort=mtime&v=#{new_gen}" : "v=#{new_gen}"
redirect "/browse/#{encode_path(v_path)}?#{sort_q}"
end
post '/trash/*' do
v_path = params['splat'].first.to_s.sub(%r{/$}, '')
halt 400, 'Cannot trash root directory' unless v_path.include?('/')
target_dir = resolve_path(v_path)
halt 404, 'Not Found' unless target_dir && File.directory?(target_dir)
require 'open3'
_out, err, status = Open3.capture3('gio', 'trash', target_dir)
halt 500, "Trash failed: #{err}" unless status.success?
bookmarks = load_bookmarks
if bookmarks.delete(v_path)
save_bookmarks(bookmarks)
end
parent_v_path = File.dirname(v_path)
gen = current_visit_gen
sort_q = params['sort'] == 'mtime' ? "sort=mtime&v=#{gen}" : "v=#{gen}"
redirect "/browse/#{encode_path(parent_v_path)}?#{sort_q}"
end
get '/' do
available_roots = ROOTS.select { |_, path| File.directory?(path) }.keys
bookmarks = load_bookmarks.select do |v_path|
real = resolve_path(v_path)
real && File.directory?(real)
end
erb :roots, locals: { roots: available_roots, bookmarks: bookmarks }
end
post '/bookmark/toggle' do
v_path = params['path'].to_s.sub(%r{^/}, '').sub(%r{/$}, '')
sort_mode = params['sort'] == 'mtime' ? 'mtime' : 'name'
target_dir = resolve_path(v_path)
halt 400, 'Invalid Path' unless target_dir && File.directory?(target_dir)
bookmarks = load_bookmarks
if bookmarks.include?(v_path)
bookmarks.delete(v_path)
else
bookmarks << v_path
end
save_bookmarks(bookmarks)
if params['return_to'] == 'top'
redirect '/'
else
query = sort_mode == 'mtime' ? '?sort=mtime' : ''
redirect "/browse/#{encode_path(v_path)}#{query}"
end
end
get '/browse/*' do
v_path = params['splat'].first.sub(%r{/$}, '')
sort_mode = params['sort'] == 'mtime' ? 'mtime' : 'name'
target_dir = resolve_path(v_path)
halt 403, 'Access Denied or Not Found' unless target_dir && File.directory?(target_dir)
raw_entries = Dir.children(target_dir).reject { |f| f.start_with?('.') }
entries = sort_entries(target_dir, raw_entries, sort_mode)
dirs = Array.new
images = Array.new
entries.each do |name|
full_path = File.join(target_dir, name)
next unless File.readable?(full_path)
rel_v_path = "#{v_path}/#{name}"
if File.directory?(full_path)
dirs << { name: name, path: rel_v_path }
elsif IMAGE_EXTS.include?(File.extname(name).downcase)
images << { name: name, path: rel_v_path }
end
end
parent_v_path = v_path.include?('/') ? File.dirname(v_path) : ''
is_bookmarked = load_bookmarks.include?(v_path)
erb :browse, locals: {
current_path: v_path,
parent_path: parent_v_path,
dirs: dirs,
images: images,
is_bookmarked: is_bookmarked,
sort_mode: sort_mode
}
end
get '/view/*' do
v_path = params['splat'].first
sort_mode = params['sort'] == 'mtime' ? 'mtime' : 'name'
target_file = resolve_path(v_path)
halt 404, 'Not Found' unless target_file && File.file?(target_file)
dir_v_path = File.dirname(v_path)
dir_full = File.dirname(target_file)
raw_images = Dir.children(dir_full)
.reject { |f| f.start_with?('.') }
.select { |f| File.file?(File.join(dir_full, f)) && IMAGE_EXTS.include?(File.extname(f).downcase) }
all_images = sort_entries(dir_full, raw_images, sort_mode)
current_name = File.basename(target_file)
idx = all_images.index(current_name)
halt 404, 'Image not in list' unless idx
prev_img = idx > 0 ? all_images[idx - 1] : nil
next_img = idx < all_images.size - 1 ? all_images[idx + 1] : nil
erb :view, locals: {
current_path: v_path,
current_name: current_name,
dir_path: dir_v_path,
prev_path: prev_img ? "#{dir_v_path}/#{prev_img}" : nil,
next_path: next_img ? "#{dir_v_path}/#{next_img}" : nil,
index: idx + 1,
total: all_images.size,
sort_mode: sort_mode
}
end
get '/raw/*' do
v_path = params['splat'].first
target_file = resolve_path(v_path)
halt 404, 'Not Found' unless target_file && File.file?(target_file)
send_file target_file
end
get '/thumb/*' do
v_path = params['splat'].first
target_file = resolve_path(v_path)
halt 404, 'Not Found' unless target_file && File.file?(target_file)
if USE_THUMB_CACHE
mtime = File.mtime(target_file).to_i
cache_key = Digest::SHA256.hexdigest("#{target_file}:#{mtime}")
cache_path = File.join(THUMB_CACHE_DIR, "#{cache_key}.jpg")
unless File.exist?(cache_path)
begin
thumb = Vips::Image.thumbnail(target_file, 300, auto_rotate: true)
thumb.jpegsave(cache_path, Q: 75, strip: true)
rescue
return send_file(target_file)
end
end
send_file cache_path
else
begin
thumb = Vips::Image.thumbnail(target_file, 300, auto_rotate: true)
content_type 'image/jpeg'
thumb.jpegsave_buffer(Q: 75, strip: true)
rescue
send_file(target_file)
end
end
end
__END__
2026.11.20 version 1.7