読者です 読者をやめる 読者になる 読者になる

クッキー処理のところを変更

Ruby

この前のやつをちょっと変更。

#! /usr/bin/ruby
# -*- coding: utf-8 -*-
require 'rubygems'
require 'mechanize'
require 'logger'

class HatenaGroupKeyword
  attr_accessor :agent
  attr_accessor :log
  attr_accessor :name
  attr_accessor :password
  attr_accessor :group
  attr_accessor :cookies
  def initialize
    @agent = WWW::Mechanize.new
    @log = Logger.new(STDOUT)
    @log.level = Logger::DEBUG
  end
  def login(cookie)
    @log.debug("started login.")
    if (!File.exist?(cookie)) || (Time.now - Time::local(*ParseDate::parsedate(@agent.cookie_jar.load(cookie)['hatena.ne.jp']['b'].expires.to_s))  > 0)
      login_page  = @agent.get('https://www.hatena.ne.jp/login')
      login_form  = login_page.forms.first
      login_form["name"] = @name
      login_form["password"] = @password
      @agent.submit(login_form)
      @agent.cookie_jar.save_as(cookie)
      @log.debug("finished login.")
    elsif
      @agent.cookie_jar.load(cookie)
      @log.debug("skipped login.")
    end
  end
  def edit(file)
    f = open(file,"r")
    text = f.read
    f.close
    file = File::split(file)[-1].split(".")
    #Tsukuba.R.txtみたいなやつの対処
    file.pop
    keyword = file.join(".")
    url = 'http://' + self.group + '.g.hatena.ne.jp/keyword/' + URI.encode(keyword) + '?mode=edit'
    puts url
    edit = @agent.get(url)
    edit_form  = edit.forms[0]
    edit_form["body"] = text
    @agent.submit(edit_form)
  end
  def create
    #need not to implement
  end
  def delete
    #menndoi
  end
end

config = YAML.load_file("/Users/yasuhisa/ruby/hatena.yaml")

hg = HatenaGroupKeyword.new
hg.name = config['name']
hg.password = config['password']
hg.group = config['group']
hg.cookies = config['cookies']

hg.login(cookie="cookie.yaml")
hg.edit(ARGV[0])