#!/usr/bin/ruby require 'sinatra/base' require 'haml' require 'RMagick' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'httpthumbnailer/thumbnailer' require 'httpthumbnailer/thumbnail_specs' sinatra = Sinatra.new sinatra.set :port, 3100 sinatra.set :bind, 'localhost' sinatra.set :environment, 'production' sinatra.set :server, ['mongrel'] sinatra.set :lock, true sinatra.set :boundary, "thumnail image data" sinatra.set :logging, true sinatra.before do unless @thumbnailer @thumbnailer = Thumbnailer.new(:logger => logger) @thumbnailer.method('crop') do |image, spec| image.resize_to_fill(spec.width, spec.height) end end end sinatra.helpers do def plain_exception(exception) headers "Content-Type" => "text/plain" body "Error: #{exception.class.name}: #{exception}\n" end end sinatra.get '/' do logger.info 'hello' end sinatra.put %r{/thumbnail/(.*)} do |specs| image = begin @thumbnailer.load('current', request.body) rescue => e plain_exception(e) halt 415 end thumbnail_specs = ThumbnailSpecs.from_uri(specs) status 200 headers "Content-Type" => "multipart/mixed; boundary=\"#{settings.boundary}\"" stream do |out| thumbnail_specs.each do |ts| logger.info "Thumbnailing: #{ts}" out << "--#{settings.boundary}\r\n" begin thumbnail = @thumbnailer.thumbnail('current', ts) thumbnail_data = thumbnail.to_blob do |inf| inf.format = ts.format end out << "Content-Type: #{ts.mime}\r\n\r\n" out << thumbnail_data thumbnail_data = nil thumbnail.destroy! rescue => e out << "Content-Type: text/plain\r\n\r\n" out << "Error: #{e.class.name}: #{e}\r\n" ensure out << "\r\n" end end out << "--#{settings.boundary}--" end end sinatra.error do plain_exception(env['sinatra.error']) end begin sinatra.run! rescue Errno::EACCES, Errno::EADDRNOTAVAIL, SocketError => e puts "Error: failed to bind HTTP server socket (#{options[:bind]}): #{e}" exit 5 end