require 'digest/md5'
class FileNotFoundController < ApplicationController
def index
@path = params[:path].join('/')
# Nail and serve images on request if they aren't nailed yet
if @path =~ /^(.*)\/.nails\/([a-z]+)\/(.+)$/
@folder = $1
@size = $2
@name = $3
@path = @folder + @name
fs_folder = RAILS_ROOT + "/public/#{@folder}"
fs_path = fs_folder + "/#{@name}"
@sizes ||= ['thumb', 'small', 'medium', 'large']
if @sizes.include? @size
@size_sym = @size.to_sym
else
render :action => 'filenotfound', :status => 404
return
end
fs_target = _resize_image fs_path, @size_sym
send_file(fs_target, :type => 'image/' + File.extname(@name).delete('.').downcase, :disposition => 'inline')
return
end
@fs_path = RAILS_ROOT + '/public/' + @path
if File.exists?(@fs_path) && !(params[:path].include?('.nail'))
files = Dir.entries(@fs_path).sort!
@dirs = []
@imgs = []
@files = []
@sizes = []
@img_exts = ['.gif', '.jpg', '.jpeg', '.png', '.svg', '.bmp'] # ', '. , '.'
@fs_nail = @fs_path + '/.nail/'
files.each do |file|
next if file[0,1] == '.' && file != '..'
file_path = @fs_path + '/' + file
ftype = File.ftype(file_path)
if ftype == 'file'
file_ext = File.extname(file).downcase
file_array = {:name => file, :size => File.size(file_path)}
if @img_exts.include? file_ext
_resize_image file_path, :thumb
@imgs << file_array
else
@files << file_array
end
elsif ftype == 'directory'
@dirs << file
end
end
@thumbnail = @imgs.size > @files.size
unless @thumbnail
@files += @imgs
@files.sort! { |a,b| a[:name] <=> b[:name] }
end
render :action => 'dirlist'
else
render :action => 'filenotfound', :status => 404
end
end
def _resize_image(fs_image, type)
fs_target = File.dirname(fs_image) + "/.nails/#{type}/"
FileUtils.mkdir_p fs_target
fs_target += File.basename(fs_image)
@nail_types ||= {
:thumb => '150x113',
:small => '320x240',
:medium => '640x480',
:large => '1280x960'
}
unless File.exists?(fs_target) && (File.stat(fs_target).mtime.to_i > File.stat(fs_image).mtime.to_i)
system("convert -resize #{@nail_types[type] || type} '#{fs_image}' '#{fs_target}'")
end
fs_target
end
end