Ruby

ライブドア・ブログ投稿

More than 5 years have passed since last update.

AtomPubという埃のついた技術の煤払いをしました。

livedoor_blog_atompub.rb
#!/usr/bin/env ruby -Ku
#coding: utf-8
require 'rubygems'
require 'net/http'
require 'wsse'
require 'base64'
require 'stringio'
require 'pp'
class LivedoorBlogAtomPub
    # livedoor のブログの細かい仕様は http://help.blogpark.jp/archives/52288925.html
    def initialize(login_id, atompub_key, blogid )
        @username, @password, @blogid = [login_id, atompub_key, blogid]
        @server_host_name = "livedoor.blogcms.jp"
    end

    def service()
        #サービスの全般:WSSE認証のチェックに使う。
        response = self.http.get('/atom/service',{'X-WSSE' => WSSE::header(@username, @password )})
        response.body
    end

    def atom()
        #エントリ取得    
        http = Net::HTTP.start(@server_host_name)
        response = http.get("/atom/blog/#{@blogid}/article",{'X-WSSE' => WSSE::header(@username, @password )})
        response.body
    end

    def post_entry(title,content,categories=[],draft_flag=false)
        #エントリをAtomのXMLで作成 
        xml = entry(title, content,draft_flag,categories) #委譲
        #エントリポストする。
        #puts xml;exit
        http = Net::HTTP.start(@server_host_name)
        response = http.post("/atom/blog/#{@blogid}/article", xml, {'X-WSSE' => WSSE::header(@username, @password )})
        puts response.body
    end
    def entry(title, body,draft_flag=false,categories=[],body_more=nil,private_more=nil,tags=nil)
        #todo 引数を キーワード引数にする。
        cat_name = nil
        draft = draft_flag ? "yes": "no" #下書き
        out = StringIO.new
         out.puts "<entry xmlns='http://www.w3.org/2005/Atom'"
         out.puts "    xmlns:app='http://www.w3.org/2007/app'"
         out.puts "    xmlns:blogcms='http://blogcms.jp/-/spec/atompub/1.0/'>"
         out.puts "    <title>#{title}</title>"
         out.puts "    <id>tag:example.org,2003:3.2397</id>"  if tags
         out.puts "    <updated>#{Time.now.iso8601}</updated>"
         out.puts "    <published>#{Time.now.iso8601}</published>"
         out.puts "    <author><name>purururuh</name></author>"
         out.puts "    <category scheme='http://livedoor.blogcms.jp/blog/#{@blogid}/category' term='#{cat_name}' />" while cat_name = categories.pop
         out.puts "    <blogcms:source>"
         out.puts "        <blogcms:body><![CDATA[<p>#{body}</p>]]></blogcms:body>"
         out.puts "        <blogcms:more><![CDATA[<p></p>]]></blogcms:more>"        if body_more
         out.puts "        <blogcms:private><![CDATA[<p></p>]]></blogcms:private>"  if private_more
         out.puts "    </blogcms:source>"
         out.puts "    <app:control>"
         out.puts "        <app:draft>#{draft}</app:draft>"
         out.puts "    </app:control>"
         out.puts "</entry>"
         out.string
    end
end


# cli = LivedoorBlogAtomPub.new("blog_id","wsse_token", "blog_id")
# #puts cli.service
# #puts cli.atom
# puts cli.post_entry("test from ruby", "hello ruby atom pp world",["test_category"])