#!/usr/bin/env python
#Copyright (C) 2008,2009 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.1'
__module_description__ = 'Send/Receive Twitter Status Updates from XChat'

username = ''
password = ''
channel = ''
interval = 300
since = 0
since_replies = 0
conf = ConfigParser()
cnc = None
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 replies_timeline(since_replies_id=0):
	global username
	global password
	auth = base64.encodestring('%s:%s' % (username, password)).strip()
	url = 'http://twitter.com/statuses/replies.json'
	data = {}
	if since_replies_id > 0:
		data['since_id'] = since_replies_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_replies_id, results)

def print_msg(arg1, arg2, arg3, arg4):
	global cnc
	if cnc is not None:
		cnc.emit_print(arg1, arg2, arg3, arg4)
	else:
		xchat.emit_print(arg1, arg2, arg3, arg4)
	
def timeline_cb(userdata):
	global since
	global conf
	try:
		results = user_timeline(since)
	except Exception, why:
		print_msg('Channel Message', 'Twitter Error', str(why), '@' )
		results = []
		return xchat.EAT_ALL
	results.reverse()
	for item in results:
		print_msg('Channel Message', 'Tweet', 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 replies_cb(words, word_eol, userdata):
	global since_replies
	global conf
	try:
		results = replies_timeline(since_replies)
	except Exception, why:
		print_msg('Channel Message', 'Twitter Error', str(why), '@' )
		results = []
		return xchat.EAT_ALL
	results.reverse()
	for item in results:
		print_msg('Channel Message', 'Replies', item['user']['name'].encode('utf-8') + ': ' + item['text'].encode('utf-8'), '@' )
		since_replies = item['id']
	conf.set('twitter', 'since_replies_id', str(since_replies))	
	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:
		print_msg('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:
	print_msg('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:
	print_msg('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

channel_conf = confopt(conf, 'twitter', 'channel')
if channel_conf is not None:
	cnc = xchat.find_context(channel='#%s'%channel_conf)

xchat.hook_command('TWEET', tweet_cb, help='/tweet <message>')
xchat.hook_command('REPLIES', replies_cb, help='/replies')
xchat.hook_timer(interval * 1000, timeline_cb)
