# tw_today.rb $Revision: 1.1 $
# (C) 2010 pyon
# You can redistribute it and/or modify it under GPL2.

require 'fileutils'
require 'open-uri'
require 'pstore'
require 'rexml/document'
require 'time'
require 'timeout'
require 'uri'

def tw_today_cache_dir(date)
	File::join(@cache_path, 'tw_today', date.strftime('%Y'))
end

def tw_today_cache_file(date)
	File::join(tw_today_cache_dir(date), date.strftime('%Y%m%d.db'))
end

def tw_today_read_cache(date)

	return if !FileTest.exist?(tw_today_cache_file(date))

	begin
		tweets = {}
		db = PStore.new(tw_today_cache_file(date))
		db.transaction(:read_only) do
			tweets = db.fetch(date.strftime('%Y%m%d'), {})
			db.abort
		end
		return tweets
	rescue PStore::Error
	end
end

def tw_today_write_cache(date, tweet)

	FileUtils.mkdir_p(tw_today_cache_dir(date))

	datestr = date.strftime('%Y%m%d')

	begin
		db = PStore.new(tw_today_cache_file(date))
		db.transaction do
			db[datestr] = {} if !db.root?(datestr)
			db[datestr][tweet['id']] = tweet if !tweet.empty?
			db.commit
		end
	rescue PStore::Error
	end
end

def tw_today_get_xml(date)
	uri = URI::HTTP.build(
		:host  => 'twitter.com',
		:path  => "/statuses/user_timeline/#{@conf['twitter.user']}.xml",
		:query => 'count=200'
	)
	begin
		timeout(15){uri.read}
	rescue Timeout::Error
	rescue OpenURI::HTTPError
	end
end

def tw_today_html(date, tweets)

	screen_name = @conf['twitter.user']

	r = %Q[<div class="section">\n]
	r << %Q[<h3>]
	r << %Q[<a href="http://twitter.com/#{h screen_name}">]
	r << %Q[#{@conf.section_anchor}</a> ]
	r << %Q[<a href="http://twitter.com/#{h screen_name}">]
	r << %Q[けふのツイート</a></h3>\n]
	tweets.sort{|a,b| a[0] <=> b[0]}.each do |t|
		r << %Q[<p><a href="http://twitter.com/#{h screen_name}/status/#{h t[1]['id']}/">#{h t[1]['tweet']}</a> (#{h t[1]['time'].strftime('%m/%d %H:%M')})</p>]
	end
	r << %Q[</div>]
end

add_body_leave_proc do |date|
	next '' if /^(latest|day)$/ !~ @mode

	tweets = tw_today_read_cache(date)
	if !tweets.nil?
		next tweets.empty? ? '' : tw_today_html(date, tweets)
	end

	xml = tw_today_get_xml(date)
	next '' if !xml

	doc = REXML::Document.new(xml).root
	next '' if !doc

	doc.elements.each('status') do |e|
		time = Time.parse(e.elements['created_at'].text).localtime
		tw_today_write_cache(time - 5 * 60 * 60, {
			'id'    => e.elements['id'].text,
			'tweet' => @conf.to_native(e.elements['text'].text),
			'time'  => time
		})
	end

	tweets = tw_today_read_cache(date)
	if tweets.nil?
		tw_today_write_cache(date, {})
		next ''
	else
		next tweets.empty? ? '' : tw_today_html(date, tweets)
	end
end

