#!/usr/bin/env python
#Copyright (C) 2008 Pruet Boon,a <pruetboonma@gmail.com>
#Licensed under WTFPL (http://en.wikipedia.org/wiki/WTFPL)

import xchat, urllib2, urllib, base64, simplejson, os
from ConfigParser import ConfigParser

__module_name__ = 'Twitter Plug-in'
__module_version__ = '1.0'
__module_description__ = 'Send/Receive Twitter Status Updates from XChat'

username = ''
password = ''
interval = 300
since = 0
conf = ConfigParser()
user_agent = 'xchat-twitter'

def confopt(conf, section, option, default=None):
	try:
		return conf.get(section, option)
	except:
		return default

def user_timeline(since_id=0):
	global username
	global password
	auth = base64.encodestring('%s:%s' % (username, password)).strip()
	url = 'http://twitter.com/statuses/friends_timeline/%s.json' % username
	data = {}
	if since_id > 0:
		data['since_id'] = since_id
	req = urllib2.Request(url, urllib.urlencode(data), {'Authorization': 'Basic %s' % auth, 'User-Agent': user_agent})
	fd = urllib2.urlopen(req)
	results = simplejson.loads(fd.read())
	return filter(lambda x: x['id'] > since_id, results)

def timeline_cb(userdata):
	global since
	global conf
	try:
		results = user_timeline(since)
	except Exception, why:
		xchat.emit_print('Channel Message', 'Twitter Error', str(why), '@' )
		results = []
		return xchat.EAT_ALL
	results.reverse()
	for item in results:
		xchat.emit_print('Channel Message', 'Twitter', item['user']['name'].encode('utf-8') + ': ' + item['text'].encode('utf-8'), '@' )
		since = item['id']
	conf.set('twitter', 'since_id', str(since))	
	conf.write(open(os.path.expanduser('~/.xchattwitt.cfg'), 'w'))
	return xchat.EAT_ALL

def tweet_cb(words, word_eol, userdata):
	global username
	global password
	if len(words) < 2:
		xchat.emit_print('Channel Message', 'Twitter Error', '/tweet <message>\nNo message send out.', '@' )
		return xchat.EAT_ALL
	auth = base64.encodestring('%s:%s' % (username, password)).strip()
	#Remove comment from the following line if you want to see sent response.
	#xchat.emit_print('Channel Message', 'My Tweet', ' '.join(words[1:]), '@' )
	urllib2.urlopen(urllib2.Request('http://twitter.com/statuses/update.json', urllib.urlencode({'status':' '.join(words[1:])}), {'Authorization': 'Basic %s' % auth, 'User-Agent': user_agent}))
	return xchat.EAT_ALL

	
conf.read([os.path.expanduser('~/.xchattwitt.cfg')])
username_conf = confopt(conf, 'twitter', 'username')

if username_conf is None:
	xchat.emit_print('Channel Message', 'Twitter Error', 'Please set your username/password in the configuration file then reload this module.', '@' )
else:
	username = username_conf
password_conf = confopt(conf, 'twitter', 'password')
if password_conf is None:
	xchat.emit_print('Channel Message', 'Twitter Error', 'Please set your username/password in the configuration file then reload this module.', '@' )
else:
	password = password_conf
interval_conf = confopt(conf, 'twitter', 'interval')
if interval_conf is not None:
	interval = int(interval_conf)
since_conf = confopt(conf, 'twitter', 'since_id')
if since_conf is  None:
	since = since_conf
xchat.hook_command('tweet', tweet_cb, help='/tweet <message>')
xchat.hook_timer(interval * 1000, timeline_cb)
