Atompubを使った投稿

はてなダイアリーAtomPubってものがあるらしくて、とりあえずサンプル見ながら書いてみた。

require 'rubygems'
require 'atomutil'
require 'kconv'

module Atompub
  class HatenaClient < Client
    def publish_entry(uri)
      @hatena_publish = true
      update_resource(uri,' ',Atom::MediaType::ENTRY.to_s)
    ensure
      @hatena_publish = false
    end

    private
    def set_common_info(req)
      req['X-Hatena-Publish'] = 1 if @hatena_publish
      super(req)
    end
  end
end

auth = Atompub::Auth::Wsse.new :username => 'your_username',:password => 'your_password'
client = Atompub::HatenaClient.new :auth => auth
service = client.get_service 'http://d.hatena.ne.jp/' + auth.instance_variable_get('@username') + '/atom'

## collections[0] => draft
## collections[1] => blog
collection_uri = service.workspace.collections[1].href

## 第一引数に指定されたファイルすべてを読み込む
entry_data = IO.readlines(ARGV[0])
## 2行以下なら終了
if entry_data.size < 2 then
    puts "file error"
    exit
end

entry = Atom::Entry.new

## 1行目はタイトルに
entry.title = entry_data.shift.toutf8
entry.updated = Time.now
## 2行目以降はエントリ記事
entry.content = entry_data[0..-1].join.toutf8

puts client.create_entry collection_uri, entry

サンプルと違うのは、serviceって変数に対してclient.get_serviceを使ってURIを与えているところ。サンプルでは%sとconfig[@username]って書いていたけど、うちのRubyでは「そんなメソッドねぇよ」って言われたので、違う手段をとることに。

とりあえず、うまく動いてくれている。いい感じだ。