
# Get scrennshot of we page.
#  2010-05-15 katoy
#
# How to run:
# ----------------
#  $ ruby scrennshot.rb   // using ruby 1.8.7,  1.9.1, jruby 1.5.0
#  Then access to 
#    http://localhost:4567/
#    http://localhost:4567/screenshot/c/url/http://www.google.co.jp
#    http://localhost:4567/screenshot/f/url/http://www.google.co.jp
#    http://localhost:4567/screenshot/t/url/http://www.google.co.jp
#
#    http://localhost:4567/screenshot/f/url/http://www.google.co.jp/search?q=あい
#
# webkit2png:  download from http://www.paulhammond.org/webkit2png/
# Imagemagick: port install ImageMagick

require 'rubygems'
require 'sinatra'       # gem install sinatra
# reloader
require "sinatra/base"
require "sinatra/reloader" if development?  # rem install sinatra-reloader 

gem RUBY_PLATFORM == 'java' ? 'rmagick4j' : 'rmagick' # gem install rmagick rmagick4j
require 'RMagick'

require 'pp'

get '/' do
  usage()
end

get '/screenshot/*/url/*' do
  begin
    args = request.fullpath.scan(/^\/screenshot\/([ctf])\/url\/(.*)/)[0]
    system(getCommand(args))    

    content_type 'image/png'
    Magick::ImageList.new(getFilename(args)).to_blob
  rescue => exe
    content_type 'text/html'
    exe.to_s
  end
end

helpers do
  @@type2shotType = { 'c' => '-C', 't' => '-T', 'f' => '-F'}
  @@type2shotName = { 'c' => 'clipped', 't' => 'thumb', 'f' => 'full'}

  def getCommand(args) 
    "./webkit2png -o tmp #{@@type2shotType[args[0]]} #{args[1]}"
  end    
  def getFilename(args) 
    "tmp-#{@@type2shotName[args[0]]}.png"
  end

  def usage
    "\
<pre>\
usage:\n\
  http://{hostname}:9393/screenshot/{type}/url/{url}\n\
      type = c:clipped t:tumb, f:full\n\
\n\
 example:\n\
  http://{hostname}:4567/screenshot/c/url/http://www.google.com  // get clipped \n\
  http://{hostname}:4567/screenshot/t/url/http://www.google.com  // get thumb \n\
  http://{hostname}:4567/screenshot/f/url/http://www.google.com  // get full \n\
    (#{RUBY_PLATFORM} #{RUBY_VERSION})\n\
</pre>"
  end

end
