はてなダイアリーとEvernote2

既存の記事の取得

引き続きやる。
あまり賢いやり方ではなさそうだけど、XML解析してlinkを取り出してみる。
とりあえず

  • タイトル
  • 投稿日
  • URI

の組をリストとして出力するようにやってみる。

require 'rubygems'
require 'atomutil'
require 'jcode'
require 'debug_func'
require 'rexml/document'
require 'kconv'
include REXML


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

class Entry
  attr_accessor :title, :date, :uri
  def initialize title,date,uri
    @title = title
    @date = date
    @uri = uri
  end
end


username='kayn_koen'
publish_time = Time.now

auth    = Atompub::Auth::Wsse.new :username => username, :password => 'password'
client  = Atompub::HatenaClient.new :auth => auth
service = client.get_service "http://d.hatena.ne.jp/#{username}/atom"
collection_uri = service.workspace.collections[1].href

#20件の記事データの取得 => XML形式、詳しくははてな
xml_text =  (client.get_media(collection_uri))[0]
#puts xml_text

# XMLから記事タイトルとURIの取り出し
# タイトル -> 日付(YYYYMMDD) -> URI
doc = Document.new(xml_text)
root_elem = doc.root #<feed>ノード

entry_list = []

#各記事についての処理
root_elem.elements.each {|child|
  #それぞれの記事は  
  #updated, id, title,author,link,link,"entry"と続くノードからなる
  if child.name != "entry" then
    next
  end
  #puts child.to_s.tosjis # これできちんと表示されるよ、やったねたえちゃん!
  
  #child == <entry>....</entry>
  
  #ほしい情報
  entry_title = nil  #タイトル
  entry_date= nil #登校日
  entry_uri = nil   #uri
 
  
  
  child.elements.each {|grandchild|
    #URIの取り出し
    if grandchild.name == "link" then
      if grandchild.attributes['rel'] == "edit" then
        entry_uri = grandchild.attributes['href']
        p entry_uri
        uri_separated = entry_uri.split("/")
        entry_id = uri_separated[uri_separated.length-1]
        entry_date = uri_separated[uri_separated.length-2]
        p entry_id
        p entry_date
      end
      
    end
    
    #タイトルの取り出し
    if grandchild.name == "title" then
      entry_title = grandchild.get_text.to_s
      p entry_title.tosjis
    end
    
   
    
  }
  
   #Entryの作成とリストへの追加
    entry_list << Entry.new(entry_title.tosjis, entry_date, entry_uri)
}


#これで20件分の記事のタイトル、日付、URIが取得可能
p entry_list

最初これで全記事が取得できると思っていたらどうやらそうではないようで、公式のはてなAtompub APIのページをみるとこれでは最新20件分しかもってこれないらしい。問題なのはこの部分

xml_text =  (client.get_media(collection_uri))[0]

ここでは
collection_uri = "http://d.hatena.jp/kayn_koen/atom/blog"
このときは最新の20件分
この20件以前の記事を取得したい場合は
collection_uri = "http://d.hatena.jp/kayn_koen/atom/blog?page=n"
このnは[1,m]の整数。ここで記事の存在するページ番号を指定するとそのページに属する
20件分の記事のEntryオブジェクトが取得できる。
1のときはpageを指定しない場合とおなじ。
もし記事がない場合は最後のentry_list = []となる

やらなきゃいけなさそうなこと

  • 投稿時にはHTML用に特殊な記号を変換

"<" を "<"に、とか

  • 20件ごとしか取ってこれないので、これを全記事について適用する