"""
Copyright (C) 2007 Butterfat, LLC (http://butterfat.net)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Created by bmuller <bmuller@butterfat.net>
""" 

import urllib, urllib2, base64, xml.sax, dbhash, time

USERNAME = "whatever"
PASSWORD = "password"

class XMLHandler(xml.sax.ContentHandler):
    def __init__(self):
        self.msgs = []
        self.cdata = ""
        self.msg = {}
    def startElement(self, name, attrs):
        if name == "item":
            self.msg = {}
        self.nowin = name
    def endElement(self, name):
        self.msg[name.strip()] = self.cdata.strip()
        self.cdata = ""
        if name == "item":
            self.msgs.append(self.msg)
    def characters(self, chars):
        self.cdata += chars

def twit(msg):
    request = urllib2.Request("http://twitter.com/statuses/update.xml")
    base64string = base64.encodestring('%s:%s' % (USERNAME, PASSWORD))[:-1]
    request.add_header("Authorization", "Basic %s" % base64string)
    params = urllib.urlencode({'status': msg})
    htmlFile = urllib2.urlopen(request, params)
    htmlData = htmlFile.read()
    htmlFile.close()

def get():
    request = urllib2.Request("http://twitter.com/statuses/friends_timeline.rss")
    base64string = base64.encodestring('%s:%s' % (USERNAME, PASSWORD))[:-1]
    request.add_header("Authorization", "Basic %s" % base64string)    
    request.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071128 Iceweasel/2.0.0.11 (Debian-2.0.0.11-1)")
    f = urllib2.urlopen(request)
    data = f.read()
    f.close()
    handler = XMLHandler()
    xml.sax.parseString(data, handler)
    return cleanup(handler.msgs)

def cleanup(msgs):
    results = {}
    for msg in msgs:
        d = msg['description']
        username = str(d[:d.index(':')])
        if username != USERNAME:
            if not results.has_key(username):
                results[username] = []
            results[username].append(msg)
    return results

def run():
    db = dbhash.open('history.db', 'c')
    mghash = {}
    try:
        msghash = get()
    except:
        return
    for user, msgs in msghash.items():
        found = False
        for msg in msgs:
            if db.has_key(user) and msg['guid'] == db[user]:
                found = True
            if not found:
                twit('@' + msg['description'])
        db[user] = msgs[0]['guid']

while True:
    run()
    time.sleep(60)

