# today_keyword.rb $Revision: 1.9 $
# Copyright (C) 2004  Michitaka Ohno <elpeo@mars.dti.ne.jp>
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

require 'net/http'
require 'timeout'

def get_keywordlist
	file = "#{@cache_path}/keywordlist"
	r = ""
	begin
		raise unless File.exist?( file )
		r = File::readlines( file )[0]
		raise if Time.now - File.mtime( file ) > 86400
	rescue
		host = 'd.hatena.ne.jp'
		port = 80
		path = "/images/keyword/keywordlist"
		limittime = 10
		timeout( limittime ) do
			begin
				Net::HTTP.version_1_1
				Net::HTTP.start( host.untaint, port.untaint ) do |http|
					response, = http.get( path )
					r = response.body
				end
				open( file, "w" ) do |f|
					f.print r
				end
			rescue Exception
			end
		end
	end
	r.scan( /(?:[^\|]|\\\|)*[^\\](?=\||$)/ )
end

def today_keyword( date )
	keywordlist = get_keywordlist
	url_regexp = %r<(((https?:|ftp:|/)[\(\)%#!/0-9a-zA-Z_$@.&+-,'"*=;?:~-]+)|([0-9a-zA-Z_.-]+@[\(\)%!0-9a-zA-Z_$.&+-,'"*-]+\.[\(\)%!0-9a-zA-Z_$.&+-,'"*-]+))>
	src = @diaries[date.strftime('%Y%m%d')].to_src.gsub( url_regexp, ';' )
	words = Array.new
	keywordlist.each do |word|
		begin
			re = Regexp.new( word, true )
			if src.gsub!( re, ';' ) then
				words << $&
			end
		rescue
		end
	end
	r = words.map do |item|
		key = CGI::escape( item ).gsub( /\+/, '%20' )
		%Q[<a class="keyword" href="http://d.hatena.ne.jp/keyword/#{key}">#{item}</a>]
	end.join( " / " )
	<<-HTML
	<div class="keywordlist">
	<div class="caption">本日のキーワード</div>
	<span class="keywordlist">#{r}</span>
	</div>
	HTML
end

if @mode == 'day' && !@cgi.mobile_agent? && !bot? then
	add_body_leave_proc do |date|
		today_keyword( date )
	end
end
