#!/usr/bin/python # # UDP 2 Twitter Application server # v0.1, by Stelios M. # # Receives UDP packets from the Simplelan devices and pushes them out # through HTTP to Twitter web site. # # TwitterAPI provided by: # http://avinashv.net/2008/04/python-and-twitter/ # import SocketServer, httplib, sys, os, base64, urllib # Define the listening port. SimpleLan can use only this port CLIENT_PORT = 22002 class ClientHandler(SocketServer.DatagramRequestHandler): def handle(self): # Handle the packet's data self.message = self.rfile.readline() # Split the values self.data = self.message.split(':') # Crate a TwitterAPI object and prepare to update the status self.myTwitter = TwitterAPI(self.data[0], self.data[1]) # Make the update self.myTwitter.update_status(self.data[2]) class TwitterAPI: def __init__(self, username, password): # generate authentication header string self.authentication = { "Authorization": "Basic %s" % base64.encodestring("%s:%s" % (username, password)).strip() } # create connection self.connection = httplib.HTTPConnection("twitter.com", 80) def update_status(self, status): # send post response with authenticated status self.connection.request("POST", "/statuses/update.xml", urllib.urlencode({ "status": status }), self.authentication) response = self.connection.getresponse() return response.status def main (): # Start the UDP server MainServer = SocketServer.ThreadingUDPServer(('',CLIENT_PORT), ClientHandler) # Display status print "UDP Twitter server starting" print "Awaiting for clients on port %d" % CLIENT_PORT # Serve forever! MainServer.serve_forever() # # Main part # if __name__ == "__main__": # Do the first fork try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # Do the second fork try: pid = os.fork() if pid > 0: # exit from second parent, print eventual PID before print "Daemon PID %d" % pid sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # start the daemon main loop main()