hatena/diary/client.rb

待望の投稿API!
これはありダラ(仮)をいじくるしかない!!

とりあえずRuby用のサンプルもあったので、見よう見まねでやってみる。
投稿成功。
この例では日本語書いてないんですけど、はてなダイアリーAtomPub
文字コードUTF-8だそうです。

#!ruby -Ku
require 'rubygems'
require 'hatena/diary/client'

client = Hatena::Diary::Client.new do |c|
  c.username = 'arikui1911'
  c.password = 'xxxx'
end

body = <<EOS
Entry Body.
use
- atomutil
EOS

member_uri = client.post do |e|
  e.title   = 'Hatena Diary Atompub Test'
  e.updated = Time.local(1998)
  e.content = body
end
hatena/diary/client.rb
require 'atomutil'

module Hatena
  module Diary
    class Client
      def initialize
        yield self if block_given?
      end
      
      attr_accessor :username
      attr_accessor :password
      
      def entry(*args, &block)
        ::Atom::Entry.new(*args, &block)
      end
      
      def post(ent = nil, &block)
        ent ||= entry(&block)
        create_entry(post_uri, ent)
      end
      
      private
      
      def service
        @service ||= core.get_service("http://d.hatena.ne.jp/#{username}/atom")
      end
      
      def ask_uri_to_service(n)
        service.workspace.collections[n].href
      end
      
      def draft_uri
        ask_uri_to_service 0
      end
      
      def post_uri
        ask_uri_to_service 1
      end
      
      def auth
        @auth ||= ::Atompub::Auth::Wsse.new(
          :username => username,
          :password => password
        )
      end
      
      def core
        @core ||= Core.new(:auth => auth)
      end
      
      def create_entry(uri, ent)
        core.create_entry(uri, ent)
      end
      
      class Core < ::Atompub::Client  #:nodoc:
        def publish_entry(uri)
          @hatena_publish_p = true
          update_resource(uri, ' ', ::Atompub::Atom::MediaType::ENTRY.to_s)
        ensure
          @hatena_publish_p = false
        end
        
        private
        
        def set_common_info(req)
          req['X-Hatena-Publish'] = 1 if @hatena_publish_p
          super
        end
      end
    end
  end #module Diary
end #module Hatena