Skip to content

Instantly share code, notes, and snippets.

@tsunekawa
Created June 21, 2014 14:14
Show Gist options
  • Save tsunekawa/74b6b981f6a9b7951a7a to your computer and use it in GitHub Desktop.
Save tsunekawa/74b6b981f6a9b7951a7a to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
require 'uri'
require 'csv'
require 'mechanize'
require 'hashie'
class Booklog
def initialize
@agent = Mechanize.new
@agent.user_agent_alias = 'Windows IE 7'
@logined = false
end
def login(id, password)
@agent = Mechanize.new
@agent.user_agent_alias = 'Windows IE 7'
@agent.post('https://booklog.jp/login', {:account=>id, :password=>password})
@user_id = id
@logined = true
end
def logout
@agent.post('https://booklog.jp/logout')
@logined = false
end
def logined?
@logined
end
def record_cached?
File.exists? cache_file_name
end
def cache_file_name
raise "login required" unless self.logined?
"booklog_#{user_id}.csv"
end
def export(options={})
raise "login required" unless self.logined?
caching = options[:cached] || true
if record_cached?
exported = File.open(cache_file_name, "r").read
else
exported = @agent.get("https://booklog.jp/export/csv").body
File.open(EXPORT_CACHE, "w"){|f| f.write exported } if caching
end
CSV.parse(exported.encode('UTF-8', 'Shift_JIS')).map do |row|
Booklog::Record.import(row)
end
end
end
# エクスポートした読書記録をパース
class Booklog::Record < Hashie::Dash
property :service_id #サービスID
property :item_id #アイテムID
property :isbn13 #13桁ISBN
property :category #カテゴリ
property :score #評価
property :status #読書状況
property :review #レビュー
property :tags #タグ
property :private_memo #読書メモ(非公開)
property :registerd_at #登録日時
property :read_at #読了日
property :title #タイトル
property :author #作者名
property :publisher #出版社名
property :issued_at #発行年
property :genre #ジャンル
property :pages #ページ数
property :price #価格
# ISBN13をISBN10に変換して表示
def isbn10
isbn10 = self.isbn13[3..11].to_s
check_digit = 0
isbn10.split(//).each_with_index do |chr, idx|
check_digit += chr.to_i * (10 - idx)
end
check_digit = 11 - (check_digit % 11)
case check_digit
when 10
check_digit = "X"
when 11
check_digit = 0
end
return "#{isbn10}#{check_digit}"
end
def self.import(list)
record = self.new
record.import(list)
end
def import(list)
attrs = [:service_id, :item_id, :isbn13, :category, :score, :status, :review, :tags, :private_memo, :registerd_at, :read_at, :title, :author, :publisher, :issued_at, :genre, :pages, :price]
attrs.zip(list).each do |k,v|
self[k] = v
end
self
end
end
if $0 == __FILE__ then
require 'io/console'
print "アカウント名:"
id = gets.chomp
print "パスワード:"
password = STDIN.noecho(&:gets)
password.chomp!
booklog = Booklog.new
booklog.login(id, password)
p booklog.export
booklog.logout
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment