Mechanize 版はてダラ v 0.1

編集ページの日付を変更して投稿した場合、変更した日付の日記に追記されるのか(上書きではなく)。なので修正。

require 'rubygems'
require 'mechanize'
require 'optparse'

VER = 0.1

@agent = WWW::Mechanize.new

PConfig = Hash.new
opts = OptionParser.new
opts.on("-t"){|v| PConfig[:t] = true ; puts "trivial update on"} 
opts.on("-v"){|v| PConfig[:v] = true } 
opts.parse!(ARGV)  

if PConfig[:v]
  puts "version #{VER}"
  exit
end

def eval_config
  eval open("config.txt"){|file| file.read}
  if @proxy_addr 
    puts "set proxy -> " + @proxy_addr + ":" + @proxy_port.to_s
    @agent.set_proxy(@proxy_addr , @proxy_port) 
  end
end
def login
  page  = @agent.get('https://www.hatena.ne.jp/login')
  form  = page.forms.first
  form["name"]       = @id
  form["password"]   = @password
  form["persistent"] = "true"
  res = form.submit
  if res.body =~ /.*error-message"\>.*\<p\>(.*?)\<\/p\>.*\<\/div\>/m
    puts "login error to " + @id
    exit
  else
    puts "login to " + @id
  end
end
def post
  time = touch_time
  Dir.foreach("."){|file|
    next if file !~ /\d\d\d\d-\d\d-\d\d\.txt/
    if File.stat(file).mtime.strftime("%Y%m%d%H%M%S") > time
      print "post " + file + " ... "
      date = file.split("-")
      date[2].sub!(".txt","")
      page = @agent.get('http://d.hatena.ne.jp/' + @id  + '/edit?date=' + date.join)
      form = page.forms.first
      form["year"]  = date[0]
      form["month"] = date[1]
      form["day"]   = date[2]
      body = open(file){|file| file.read.split("\n",2)}
      form["title"] = body[0]
      form["body"]  = body[1]
      form["trivial"] = "true" if PConfig[:t]
      form.submit
      puts "end"
    end
  }
end
def touch_time
  if File.exist?("touch.txt")
    open("touch.txt"){|file| file.read}
  else
    Time.now.strftime("%Y%m%d%000000")
  end
end
def edit_touch_time
  open("touch.txt","w") {|file| file.puts Time.now.strftime("%Y%m%d%H%M%S")}
end
# main
eval_config
login
post
edit_touch_time
  • 実行
ruby hatedara.rb
ちょっとだけ更新する場合
ruby hatedara.rb -t

テスト環境 : ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-cygwin]