termtter用のGyazoプラグインを書いてみた

termtterというコマンドラインで使えるTwitterクライアントはRubyで書かれていて、簡単にプラグインやフック(フィルタ)が書けるというので、Gyazoプラグインを書いてみた。

といっても、YAAさんのところにあるGNU/Linux用のGyazoアップローダをテンプレートにはめ込んだだけで、作業時間は10分足らず。本当はコマンドラインから指定した画像をアップロードする部分とか、関係ないから削除するか変更するといいんだろうけど。

~/.termtter/plugins/に、gyazo.rbとして以下のファイルを放り込んで、~/.termtter/configに、

Termtter::Client.init do |t|
  t.plug 'gyazo'
end

と書けば、後はtermtter上で「gyazo なんだこの画面は!」とかやって、切り抜く範囲の画面を指定すれば「画像キャプチャ→アップロード→Twitterポスト」まで自動でいけるはず。

そもそもGyazoというサービス自体よく分かってないのだけど、IDを付けると何かいいことがあるのだろうか。

require 'net/http'

def post_gyazo
  browser_cmd = 'firefox'
  clipboard_cmd = 'xclipboard'
  gyazo_url = ""
  
  idfile = ENV['HOME'] + "/.gyazo.id"
  
  id = ''
  if File.exist?(idfile) then
    id = File.read(idfile).chomp
  else
    id = Time.new.strftime("%Y%m%d%H%M%S")
    File.open(idfile,"w").print(id+"\n")
  end
  
  tmpfile = "/tmp/image_upload#{$$}.png"
  imagefile = ARGV[0]
  
  if imagefile && File.exist?(imagefile) then
    system "convert #{imagefile} #{tmpfile}"
  else
    system "import #{tmpfile}"
  end
  
  imagedata = File.read(tmpfile)
  File.delete(tmpfile)
  
  boundary = '----BOUNDARYBOUNDARY----'
  
  data = <<EOF
--#{boundary}\r
content-disposition: form-data; name="id"\r
\r
#{id}\r
--#{boundary}\r
content-disposition: form-data; name="imagedata"\r
\r
#{imagedata}\r
\r
--#{boundary}--\r
EOF

  header ={
    'Content-Length' => data.length.to_s,
    'Content-type' => "multipart/form-data; boundary=#{boundary}"
  }

  Net::HTTP.start("gyazo.com",80){|http|
    res = http.post("/upload.cgi",data,header)
    url = res.response.to_ary[1]
    puts url
    if system "which #{clipboard_cmd} >/dev/null 2>&1" then
      system "echo #{url} | #{clipboard_cmd}"
    end
    system "#{browser_cmd} #{url}"
    gyazo_url = url
  }
  return gyazo_url
end

Termtter::Client.register_command(
  :name => :gyazo,
  :exec => lambda {|arg|
    text = arg
    url = post_gyazo
    Termtter::API.twitter.update(text + " " + url)
    puts "=> " << text + " " + url
  }
)