#!/usr/bin/env ruby
# mobile_twitter.rb $Revision: 4 $
# Copyright (C) 2007 Michitaka Ohno <elpeo@mars.dti.ne.jp>
# You can redistribute it and/or modify it under GPL2.
BEGIN{ $stdout.binmode }

require 'cgi'
require 'kconv'
require 'rexml/document'
require 'net/http'
require 'open-uri'

user = '' # <= Your Username.
pass = '' # <= Your Password.
ua = nil # <= Your User-Agent.

cgi = CGI.new
status = cgi.params['status'][0] if cgi.include?( 'status' )
status = nil if status.to_s.empty?

if (ua.to_s.empty? || ua == cgi.user_agent) && status then
	#status << ' .' if /[\x80-\xff]/ =~ status
	Net::HTTP.version_1_2
	req = Net::HTTP::Post.new( '/statuses/update.xml' )
	req.basic_auth( user, pass )
	Net::HTTP.start( 'twitter.com' ) do |http|
		response = http.request( req, "status=#{CGI::escape( status.toutf8 )}" )
	end
end

r = ""
begin
	require 'json'
	$KCODE = 'u'
	json = open( "http://twitter.com/statuses/friends_timeline.json", :http_basic_authentication => [user, pass] ) do |f|
		begin
			JSON.parse( f.read )
		rescue
		end
	end
	if json then
		json.each do |item|
			r << "<br>\n<b>" << CGI::escapeHTML( item['user']['screen_name'] )
			r << ":</b> " << CGI::escapeHTML( item['text'] )
		end
	end
rescue LoadError
	doc = open( "http://twitter.com/statuses/friends_timeline.xml", :http_basic_authentication => [user, pass] ) do |f|
		REXML::Document.new( f.read ).root
	end
	if doc then
		doc.elements.each( 'status' ) do |e|
			r << "<br>\n<b>" << CGI::escapeHTML( e.elements['user/screen_name'].text )
			r << ":</b> " << CGI::escapeHTML( e.elements['text'].text )
		end
	end
end

print cgi.header( 'type' => 'text/html', 'charset' => 'Shift_JIS', 'expires' => Time.at(0) )
print <<-HTML.tosjis
<html>
<head>
<title>Twitter</title>
</head>
<body>
<h1>Twitter</h1>
<form method="POST" action="#{cgi.script_name}" #{'utn' if ua}>
<input type="text" name="status">
<input type="submit" value="Update">
</form>
#{r}
</body>
</html>
HTML

exit
