2008年 01月 01日

atomutil で fotolife API をたたいてみる

fotolife API は Atom 0.3 なのでちょっとだけ工夫がいるのですが

require "rubygems"
require "atomutil"
require "yaml"
require "pathname"

file = Pathname.new("2150944907_5be2ee34ac.jpg")

entry = Atom::Entry.new({
	:title => file.basename.to_s,
	:updated => Time.now,
	:content => Atom::Content.new { |c|
		c.body = [file.read].pack('m')
		c.type = "image/jpeg"
		c.set_attr(:mode, "base64")
	},
})
puts entry.to_s

config = YAML.load(Pathname.new("~/.hatena.ne.jp.yaml").expand_path.read)
client = Atompub::Client.new({
	:auth => Atompub::Auth::Wsse.new(:username => config["user"], :password => config["pass"])
})

post_uri = "http://f.hatena.ne.jp/atom/post"
p post_uri
p client.create_entry(post_uri, entry, file.basename.to_s)

とやるとできるみたいです。Atom::Entry とかがブロックをとれるので綺麗にかけていいですね! (mode="base64" は Atom 1.0 だとなくて、バイナリをそのまま Content-Type 指定して送信するみたい (まだちゃんと読んでないけど……)。base64 でいけると XHR でも画像が POST できるからいいんだけどなぁ)

ちなみに拡張子から mime-type への変換は WEBrick 使うと簡単です (mechanize でもこうやってる)

require "webrick/httputils"
mime_type = WEBrick::HTTPUtils.mime_type("foo.jpg", WEBrick::HTTPUtils::DefaultMimeTypes)
p mime_type #=> "image/jpeg"