jabber.py-0.5.0.orig/0000755000175000017500000000000010007747447014517 5ustar kalfakalfa00000000000000jabber.py-0.5.0.orig/CREDITS0000644000175000017500000000043707753207720015542 0ustar kalfakalfa00000000000000 DJ Adams Lots of help with protocol implentation / Bug fixes Brian Lalor Bug fixes / IMAP Component John 'zariok' Draughn - SSL support Aaron Wald pyqt client Erik Westra Lots of bug fixes, and documentation improvements Lalo Martins Picogui clientjabber.py-0.5.0.orig/MANIFEST0000644000175000017500000000040707753207721015651 0ustar kalfakalfa00000000000000README CREDITS jabber.py xmlstream.py setup.py examples/README examples/jrpc.py examples/test_client.py examples/pygtkjab.py examples/pyqtjab.py examples/mailchecker.py examples/offline.xpm examples/online.xpm examples/pending.xpm util/sleepy.py docs/index.html jabber.py-0.5.0.orig/README0000644000175000017500000000507607753207721015407 0ustar kalfakalfa00000000000000jabberpy 0.3 README Matthew Allum Introduction ------------- jabber.py is a Python module for the jabber instant messaging protocol. jabber.py deals with the xml parsing and socket code, leaving the programmer to concentrate on developing quality jabber based applications with Python. jabber.py requires at least python 2.0 and the XML expat parser module ( included in the standard Python distrubution ). It is developed on Linux but should run happily on other Unix's and win32. The library currently supports enough of the protocol to write simple jabber clients. jabber.py is released under the GPL license. For more infomation see http://jabberpy.sourceforge.net Whats Needed ------------- You need python >=2.0 with the expat modules installed. You can check for the expat modules by opening up a Python shell ( make sure it reports at least version 2 ) and enter 'import xml.parsers.expat' . If you get an error you need to install the python expat libs... To do this; For Debian users; You need the python2-base package installed, then as root; apt-get install python2-xml From Python source (Un*x); Before compiling Python, have a look at the file Modules/Setup in the distrubution directory. At the bottom of the file you'll find some instructions for installing the expat modules, follow them ! For Windows Users; AFAIK the windows Python Binary ( from python.org ) comes with expat support included. If you are using windows see the 'notes' section at the bottom of this readme. Installation ------------- From the untared distrubution directory; As root run; python setup.py install Alternatively just copy xmlstream.py and jabber.py to somewhere in your PYTHONPATH. The examples directory contains some simple jabber based programs which use the library. See examples/README Documentaion ------------- The modules contain embedded docmentation, use pydoc to present this is a nice readable format. Also see the protocol documentation on jabber.org and the source code for the scripts in examples/* . Bugs ---- Probably lots :p. If you find any subscribe to the dev list ( see below ) or drop me a mail - breakfast@10.am Notes ----- <> The library should run fine on windows. Unfortunatly the test client will not as it 'selects' on a file handle and windows does not support this. If anyone knows a workaround for this please then inform me. <> A Mailing list for the development of the jabberpy project is available at; http://lists.sourceforge.net/lists/listinfo/jabberpy-devel Please subscribe and help the project. jabber.py-0.5.0.orig/setup.py0000644000175000017500000000150007753207721016225 0ustar kalfakalfa00000000000000#!/usr/bin/env python2 import sys try: from distutils.core import setup except: if sys.version[0] < 2: print "jabber.py requires at least python 2.0" print "Setup cannot continue." sys.exit(1) print "You appear not to have the Python distutils modules" print "installed. Setup cannot continue." print "You can manually install jabberpy by coping the jabber" print "directory to your /python-libdir/site-packages" print "directory." sys.exit(1) setup(name="jabber.py", version="0.3-1", #py_modules=["xmlstream","jabber"], packages=["jabber"], description="Python xmlstream and jabber IM protocol libs", author="Matthew Allum", author_email="breakfast@10.am", url="http://jabberpy.sf.net/", license="LGPL" ) jabber.py-0.5.0.orig/examples/0000755000175000017500000000000010007747457016336 5ustar kalfakalfa00000000000000jabber.py-0.5.0.orig/examples/pypguijab.py0000644000175000017500000002655707472403120020705 0ustar kalfakalfa00000000000000#!/usr/bin/env python2.2 # we require Python 2.2 because PyPicoGUI does import PicoGUI import socket from select import select from string import split,strip,join import sys,os import jabber True = 1 False = 0 pg_roster = {} log_chat_format = '<%(from)s> %(body)s' log_st_format = '*%(from)s %(type)s: %(body)s' def getBuddy(jid): jid = str(jid) if not pg_roster.has_key(jid): buddy = Buddy(jid) pg_roster[jid] = buddy return pg_roster[jid] class Buddy(object): def __init__(self, jid): self.jid = jid self.item = status_item.addWidget('ListItem') self.item.text = jid self.listed = False self._log = [] global app app.link(self.select, self.item, 'activate') def select(self, *a): global Who Who = self.jid self.update_log_box() def update_log_box(self): log_box.text = '\n'.join(self._log) app.server.update() def log(self, msgdata): if msgdata.get('type', 'chat') == 'chat': self._log.append(log_chat_format % msgdata) else: self._log.append(log_st_format % msgdata) if Who == self.jid: self.update_log_box() pg_log_data = [] def pg_log(text): global log_to_stdout, log_box if log_to_stdout: print text pg_log_data.append(text) if not Who: log_box.text = '\n'.join(pg_log_data) # PicoGUI initialization app = PicoGUI.Application('Jabber client') roster_box = app.addWidget('Box') roster_box.side = 'left' roster_box.transparent = 1 roster_box.sizemode = 'percent' roster_box.size = '20' panelbar = roster_box.addWidget('PanelBar') panelbar.side = 'left' panelbar.bind = roster_box status_item = roster_box.addWidget('ListItem', 'inside') status_item.text = '(status)' status_item.hilighted = 1 roster_box.addWidget('Scroll', 'inside').bind = roster_box log_box = panelbar.addWidget('TextBox') log_box.side = 'right' log_box.sizemode = 'percent' log_box.size = 100 log_box.autoscroll = 1 panelbar.addWidget('Scroll').bind = log_box entry = panelbar.addWidget('Field') entry.side = 'bottom' def select_status(*a): global Who, log_box Who = '' log_box.text = '\n'.join(pg_log_data) app.server.update() select_status() app.link(select_status, status_item, 'activate') def pg_input(message, initial='', password=0): global app s = app.server s.mkcontext() dlg = PicoGUI.Widget(s, s.mkpopup(-1, -1, 0, 0)) msg = dlg.addWidget('Label', 'inside') msg.text = message field = msg.addWidget('Field') field.text = initial if password == 1: password = '*' if type(password) == type(''): password = ord(password) field.password = password s.focus(dlg) s.focus(field) def finish(*a): app.send(app, 'stop') app.link(finish, field, 'activate') app.run() txt = s.getstring(field.text)[:-1] s.rmcontext() return txt # Console and jabber initialization # Change this to 0 if you dont want a color xterm USE_COLOR = 0 Who = '' MyStatus = '' MyShow = '' def usage(): pg_log("%s: a simple python jabber client " % sys.argv[0]) pg_log("usage:") pg_log("%s - connect to and register" % sys.argv[0]) pg_log("%s []" % sys.argv[0]) pg_log("%s @ []" % sys.argv[0]) pg_log(" - connect to server and login ") sys.exit(0) def doCmd(con,txt): global Who cmd = split(txt) if cmd[0] == 'presence': to = cmd[1] type = cmd[2] con.send(jabber.Presence(to, type)) elif cmd[0] == 'status': p = jabber.Presence() MyStatus = ' '.join(cmd[1:]) p.setStatus(MyStatus) con.send(p) elif cmd[0] == 'show': p = jabber.Presence() MyShow = ' '.join(cmd[1:]) p.setShow(MyShow) con.send(p) elif cmd[0] == 'subscribe': to = cmd[1] con.send(jabber.Presence(to, 'subscribe')) elif cmd[0] == 'unsubscribe': to = cmd[1] con.send(jabber.Presence(to, 'unsubscribe')) elif cmd[0] == 'roster': con.requestRoster() _roster = con.getRoster() for jid in _roster.getJIDs(): pg_log(colorize("%s :: %s (%s/%s)" % ( jid, _roster.getOnline(jid), _roster.getStatus(jid), _roster.getShow(jid), ) , 'blue' )) elif cmd[0] == 'agents': pg_log(`con.requestAgents()`) elif cmd[0] == 'register': agent = '' if len(cmd) > 1: agent = cmd[1] con.requestRegInfo(agent) pg_log(`con.getRegInfo()`) elif cmd[0] == 'exit': con.disconnect() pg_log(colorize("Bye!",'red')) sys.exit(0) elif cmd[0] == 'help': pg_log("commands are:") pg_log(" subscribe ") pg_log(" - subscribe to jid's presence") pg_log(" unsubscribe ") pg_log(" - unsubscribe to jid's presence") pg_log(" agents") pg_log(" - list agents") pg_log(" register ") pg_log(" - register with an agent") pg_log(" presence ") pg_log(" - sends a presence of type to the jabber id") pg_log(" status ") pg_log(" - set your presence status message") pg_log(" show ") pg_log(" - set your presence show message") pg_log(" roster") pg_log(" - requests roster from the server and ") pg_log(" display a basic dump of it.") pg_log(" exit") pg_log(" - exit cleanly") else: pg_log(colorize("uh?", 'red')) def doSend(con,txt): global Who if Who != '': msg = jabber.Message(Who, txt.strip()) msg.setType('chat') #pg_log("<%s> %s" % (JID, msg.getBody())) con.send(msg) buddy = getBuddy(Who) buddy.log({'from':JID, 'to':Who, 'body':txt.strip()}) else: pg_log(colorize('Nobody selected','red')) def messageCB(con, msg): """Called when a message is recieved""" mfrom = msg.getFrom() mbody = msg.getBody() buddy = getBuddy(mfrom) buddy.log({'from':mfrom, 'to':JID, 'body':mbody}) def presenceCB(con, prs): """Called when a presence is recieved""" who = prs.getFrom() type = prs.getType() if type == None: type = 'available' # subscription request: # - accept their subscription # - send request for subscription to their presence if type == 'subscribe': pg_log(colorize("subscribe request from %s" % (who), 'blue')) con.send(jabber.Presence(to=str(who), type='subscribed')) con.send(jabber.Presence(to=str(who), type='subscribe')) # unsubscription request: # - accept their unsubscription # - send request for unsubscription to their presence elif type == 'unsubscribe': pg_log(colorize("unsubscribe request from %s" % (who), 'blue')) con.send(jabber.Presence(to=str(who), type='unsubscribed')) con.send(jabber.Presence(to=str(who), type='unsubscribe')) elif type == 'subscribed': pg_log(colorize("we are now subscribed to %s" % (who), 'blue')) elif type == 'unsubscribed': pg_log(colorize("we are now unsubscribed to %s" % (who), 'blue')) elif type == 'available': sta = '%s / %s' % (prs.getShow(), prs.getStatus()) pg_log(colorize("%s is available (%s)" % (who, sta),'blue')) buddy = getBuddy(who) buddy.listed = True buddy.item.text = '%s (%s)' % (who, sta) buddy.log({'type':'available', 'from':who, 'body':sta}) app.server.update() elif type == 'unavailable': sta = '%s / %s' % (prs.getShow(), prs.getStatus()) pg_log(colorize("%s is unavailable (%s)" % (who, sta),'blue')) buddy = getBuddy(who) app.server.attachwidget(0, buddy.item, 0) buddy.listed = False buddy.log({'type':'unavailable', 'from':who, 'body':sta}) app.server.update() def iqCB(con,iq): """Called when an iq is recieved, we just let the library handle it at the moment""" pass def disconnectedCB(con): pg_log(colorize("Ouch, network error", 'red')) sys.exit(1) def colorize(txt, col): """Return colorized text""" if not USE_COLOR: return txt ## DJ - just incase it breaks your terms ;) ## cols = { 'red':1, 'green':2, 'yellow':3, 'blue':4} initcode = '\033[;3' endcode = '\033[0m' if type(col) == type(1): return initcode + str(col) + 'm' + txt + endcode try: return initcode + str(cols[col]) + 'm' + txt + endcode except: return txt if len(sys.argv) == 1: usage() argv = sys.argv if '-d' in argv: log_to_stdout = True argv.remove('-d') else: log_to_stdout = False if argv[1].find('@') != -1: arg_tmp = sys.argv[1].split('@') arg_tmp.reverse() argv[1:2] = arg_tmp del arg_tmp Server = argv[1] Username = '' Password = '' Resource = 'default' con = jabber.Client(host=Server,debug=False,log=None) # Experimental SSL support # # con = jabber.Client(host=Server,debug=True ,log=sys.stderr, # port=5223, connection=xmlstream.TCP_SSL) try: con.connect() except IOError, e: pg_log("Couldn't connect: %s" % e) sys.exit(0) else: pg_log(colorize("Connected",'red')) con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB) con.setIqHandler(iqCB) con.setDisconnectHandler(disconnectedCB) if len(argv) == 2: # Set up a jabber account con.requestRegInfo() req = con.getRegInfo() pg_log(req[u'instructions']) for info in req.keys(): if info != u'instructions' and \ info != u'key': pg_log("enter %s;" % info) con.setRegInfo( info,strip(sys.stdin.readline()) ) con.sendRegInfo() req = con.getRegInfo() Username = req['username'] Password = req['password'] else: Username = argv[2] Password = pg_input('Password for %s:' % Username, password='*') if len(argv) > 3: Resource = argv[3] else: Resource = 'PyPguiJab' pg_log(colorize("Attempting to log in...", 'red')) if con.auth(Username,Password,Resource): pg_log(colorize("Logged in as %s to server %s" % ( Username, Server), 'red')) else: pg_log("eek -> ", con.lastErr, con.lastErrCode) sys.exit(1) pg_log(colorize("Requesting Roster Info" , 'red')) con.requestRoster() con.sendInitPresence() pg_log(colorize("Ok, ready" , 'red')) pg_log(colorize("Type /help for help", 'red')) JID = Username + '@' + Server + '/' + Resource # jabber -> pgui setup def idle(ev, win): inputs, outputs, errors = select([sys.stdin], [], [],1) if sys.stdin in inputs: doCmd(con,sys.stdin.readline()) else: con.process(1) app.link(idle, None, "idle") def pg_send(ev, wid): txt = app.server.getstring(wid.text)[:-1] wid.text = '' if Who: doSend(con, txt) else: doCmd(con, txt) app.link(pg_send, entry, 'activate') apptitle = app.panelbar_label if type(apptitle) is type(1L): # temporary workaround till library can know about property types apptitle = PicoGUI.Widget(app.server, apptitle, app) apptitle.text = 'Jabber client: %s' % JID # now run the app def closeapp(ev, win): con.disconnect() pg_log(colorize("Bye!",'red')) sys.exit(0) app.link(closeapp, app, "close") app.server.focus(entry) app.run() jabber.py-0.5.0.orig/examples/jrpc.py0000755000175000017500000000531607757050453017657 0ustar kalfakalfa00000000000000#!/usr/bin/python """ jrpc demonstrates extending an iq with the QueryPayload methods. This example, using xmlrpclib, simply wraps an XML-RPC request a an ip with the namespace 'jabber:iq:rpc' For more info on this technique see http://www.pipetree.com/jabber/jrpc.html mallum """ # $Id: jrpc.py,v 1.6 2003/11/08 19:00:07 snakeru Exp $ import sys ## Import jabber module import jabber ## Import xmlrpclib - http://www.pythonware.com/products/xmlrpc/index.htm import xmlrpclib ## Setup server and auth varibles ## You'll need to edit these. Server = 'jabber.com' Username = 'xxxx' Password = 'xxxx' Resource = 'xmlrpc' IqID = '999999' def iq_CB(con,iq): print "got an iq" def iq_error_CB(con,iq): print "got an error -> ", iq.getError() ## This is called when an Iq is recieved def iq_xmlrpc_response_CB(con,iq): ## Get the query part of the Iq and check its namespace and id if iq.getID() == IqID: ## Get the querys 'payload' , will return an XMLStreanNode structure xmlrpc_node = iq.getQueryPayload() ## Let xmlrpclib parse the method call. The node becomes a string ## automatically when called in a str context. result,func = xmlrpclib.loads("%s" % xmlrpc_node) ## Print the function name and params xmllibrpc returns print "Recieved -> ",result ## Exit sys.exit() ## Get a jabber connection object, with logging to stderr con = jabber.Client(host=Server,log=sys.stderr) ## Try and connect try: con.connect() except: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected" ## Attatch the above iq callback con.registerHandler('iq',iq_CB) con.registerHandler('iq',iq_error_CB, type='error') con.registerHandler('iq',iq_xmlrpc_response_CB, type='get', ns='jabber:iq:rpc') ## Authenticate if con.auth(Username,Password,Resource): print "Authenticated" else: print "Auth failed", con.lastErr, con.lastErrCode sys.exit(1) ## Get the roster and send presence. Maybe not needed but ## good practise. ## con.requestRoster() ## con.sendInitPresence() ## Build an XML-RPC request - note xmlrpc_req is a string params = ( (16,2,7,4), ) method = 'examples.getStateList' print "sending ", method, params xmlrpc_req = xmlrpclib.dumps( params , methodname=method) ## Birth an iq ojbject to send to self iqTo = "jrpchttp.gnu.mine.nu/http://validator.userland.com:80/RPC2" iq = jabber.Iq(to=iqTo, type="set") ## Set the i'qs query namespace iq.setQuery('jabber:iq:rpc') ## Set the ID iq.setID(IqID) ## Set the query payload - can be an XML document or ## a Node structure iq.setQueryPayload(xmlrpc_req) ## Send it con.send(iq) ## wait .... while 1: con.process(1) jabber.py-0.5.0.orig/examples/online.xpm0000644000175000017500000000363007372240020020333 0ustar kalfakalfa00000000000000/* XPM */ static char * unknown[] = { "17 16 80 2", " s None c None", ".. c #6a5f53", "#. c #000000", "a. c #6f6f6f", "b. c #494977", "c. c #b3916e", "d. c #e5b684", "e. c #030303", "f. c #cdcdcd", "g. c #bcbcbc", "h. c #383859", "i. c #e1e1e1", "j. c #373748", "k. c #9c9cff", "l. c #161514", "m. c #aeaeae", "n. c #535353", "o. c #af8a65", "p. c #b89978", "q. c #4f4e4d", "r. c #302d2a", "s. c #313131", "t. c #c9a682", "u. c #7474bd", "v. c #565656", "w. c #202020", "x. c #fccb98", "y. c #35281a", "z. c #a3a3a3", "A. c #484848", "B. c #121212", "C. c #5b5b89", "D. c #a18262", "E. c #959595", "F. c #bababa", "G. c #4e4e4e", "H. c #3a3633", "I. c #2a2a2d", "J. c #19191c", "K. c #e2e2e2", "L. c #5f4225", "M. c #8a8a8a", "N. c #ffce9c", "O. c #4e4b47", "P. c #3f3f60", "Q. c #e8e8e8", "R. c #d7d7d7", "S. c #212121", "T. c #909090", "U. c #735332", "V. c #bc9975", "W. c #3f3020", "X. c #cba883", "Y. c #828282", "Z. c #a7a7a7", "0. c #c7a481", "1. c #3b3630", "2. c #a58057", "3. c #302a25", "4. c #d0ab86", "5. c #fdcc9a", "6. c #bf9a75", "7. c #1c1c1c", "8. c #c6a27e", "9. c #3e352c", ".# c #c7a581", "## c #454555", "a# c #8484cd", "b# c #161413", "c# c #514940", "d# c #56493b", "e# c #3d3c3b", "f# c #65594d", "g# c #e9e9e9", "h# c #bb9b7a", "i# c #725130", "j# c #e1b381", "k# c #4e3f2f", "l# c #4a4a60", "m# c #a37e59", " ", " Q.z.v.v.v.z.Q. ", " g#q.L.D.D.D.L.e#K. ", " i.O.2.5.N.N.N.5.2.r.R. ", " M.i#x.X.f#N...8.x.U.Y. ", " s.6.N.0.9.N.c#c.N.4.S. ", " s.6.N.N.N.N.N.N.N.4.S. ", " n.m#N.#..#.#.##.N.o.A. ", " g.W.j#t.1.3.3.V.d.k#m. ", " T.y.p.N.N.N.h#d#E. ", " F.B.b#H.H.H.l.e.Z. ", " f.I.b.u.u.u.u.u.C.J.g. ", " a.P.k.k.k.k.k.k.k.h.G. ", " s.u.k.k.k.k.k.k.k.a#w. ", " s.j.l#l#l#l#l#l#l###7. ", " "};jabber.py-0.5.0.orig/examples/README0000644000175000017500000000044607421537024017213 0ustar kalfakalfa00000000000000This directory contains some simple example of using jabber.py test_client.py - A simple command line based client. jrpc.py - Combining jabber and XML-RPC. pygtkjab.py - An 'in-progress' pygtk based client. pyqtjab.py - A simple pyQt client. mailchecker.py - A component examplejabber.py-0.5.0.orig/examples/mailchecker.py0000644000175000017500000002307407757050453021166 0ustar kalfakalfa00000000000000## Stick this in the element of your jabber.xml ## ## jabber:iq:register ## jabber:iq:gateway ## ## ## Stick this in with the other elements ## ## ## ## secret ## 6969 ## ## import jabber import sys import sha import imaplib import pickle import string # mailchecker client class MCClient: jid = None username = None password = None hostname = None directory = None folders = [] online = 0 status = None imap = None def __init__(self, jid, username, password, hostname, directory, folders): self.jid = jid self.username = username self.password = password self.hostname = hostname self.directory = directory self.folders = string.split(folders, ':') def doit(self, con): """query the mail server for new messages""" pass def cleanup(self): """Close down IMAP connection and perform any other necessary cleanup""" pass def setStatus(self, status): """Set the client's "verbose" status""" self.status = status def setShow(self, show): """Set the client's show mode; one of away, chat, xa, dnd, or 'None'""" # http://docs.jabber.org/jpg/html/main.html#REFSHOW # One of away, chat, xa, or dnd. self.show = show self.setOnline(1) def setOnline(self, online): """Set whether the user is online or not""" self.online = online def isOnline(self): """Return the state of the user's online'ness""" return(self.online) def isAvailable(self): """Return a boolean based on the user's show status""" # return false if xa, dnd or away (?) if (self.show == None) or (self.show == 'chat'): return(1) else: return(0) # dict of keys keys = {} def iqCB(con, iq): print "Iq:", str(iq) resultIq = jabber.Iq(to=iq.getFrom()) resultIq.setID(iq.getID()) resultIq.setFrom(iq.getTo()) query_result = resultIq.setQuery(iq.getQuery()) type = iq.getType() query_ns = iq.getQuery() # switch on type: get, set, result error # switch on namespaces if query_ns == jabber.NS_REGISTER: if type == 'get': resultIq.setType('result') # generate a key to be passed to the user; it will be checked # later. yes, we're storing a sha object iq_from = str(iq.getFrom()) keys[iq_from] = sha.new(iq_from) # tell the client the fields we want fields = { 'username': None, 'password': None, 'instructions': 'Enter your username, password, IMAP hostname, directory, and :-separated list of folders to check', 'key': keys[iq_from].hexdigest(), 'hostname': None, 'directory': None, 'folders': 'INBOX' } for field in fields.keys(): field_node = query_result.insertTag(field) if fields[field]: field_node.putData(fields[field]) con.send(resultIq) elif type == 'set': # before anything else, verify the key client_key_node = iq.getQueryNode().getTag('key') if not client_key_node: resultIq.setType('error') resultIq.setError('no key given!') con.send(resultIq) else: # verify key if keys[str(iq.getFrom())].hexdigest() == client_key_node.getData(): # key is good if iq.getQueryNode().getTag('remove'): # user is trying to unregister # TODO. :-) del clients[iq.getFrom().getStripped()] else: # someone is trying to register jid = iq.getFrom().getStripped() username = iq.getQueryNode().getTag('username') if username: username = str(username.getData()) password = iq.getQueryNode().getTag('password') if password: password = str(password.getData()) hostname = iq.getQueryNode().getTag('hostname') if hostname: hostname = str(hostname.getData()) directory = iq.getQueryNode().getTag('directory') if directory: directory = str(directory.getData()) folders = iq.getQueryNode().getTag('folders') if folders: folders = str(folders.getData()) client = MCClient(jid, username, password, hostname, directory, folders) clients[client.jid] = client # subscribe to the client's presence sub_req = jabber.Presence(iq.getFrom(), type='subscribe') sub_req.setFrom(str(iq.getTo()) + "/registered") con.send(sub_req) resultIq.setType('result') con.send(resultIq) else: resultIq.setType('error') resultIq.setError('invalid key', 400) con.send(resultIq) # done with key; delete it del keys[str(iq.getFrom())] else: print "don't know how to handle type", type, "for query", query_ns elif (query_ns == jabber.NS_AGENT) and (type == 'get'): # someone wants information about us resultIq.setType('result') responses = { 'name': "Mailchecker", # 'url': None, 'description': "This is the mailchecker component", 'transport': "don't know what should go here...", 'register': None, # we can be registered with 'service': 'test' # nothing really standardized here... } for response in responses.keys(): resp_node = query_result.insertTag(response) if responses[response]: resp_node.putData(responses[response]) con.send(resultIq) else: print "don't know how to handle type", type, "for query", query_ns def presenceCB(con, pres): print "Presence:", str(pres) # presence reply to use later on p = jabber.Presence(to=pres.getFrom()) p.setFrom(pres.getTo()) type = pres.getType() # find the client object if str(pres.getFrom().getStripped()) in clients.keys(): client = clients[pres.getFrom().getStripped()] else: print("not able to find client for " + pres.getFrom().getStripped()) client = None if type != 'unsubscribed': type = 'unsubscribe' if not type: type = 'available' print(pres.getFrom().getStripped() + " is " + type) if type == 'unavailable': # user went offline client.setOnline(0) p.setType('unavailable') con.send(p) elif type == 'subscribe': # user wants to subscribe to our presence; oblige, and ask for his p.setType('subscribed') con.send(p) p.setType('subscribe') con.send(p) elif type == 'unsubscribe': p.setType('unsubscribed') con.send(p) p.setType('unsubscribe') con.send(p) elif type == 'unsubscribed': # now unsubscribe from the user's presence pass elif type == 'probe': # send our presence p.setType('available') con.send(p) elif type == 'available': # user is online client.setStatus(pres.getStatus()) client.setShow(pres.getShow()) p.setType('available') con.send(p) con = jabber.Component(host='webtechtunes.hq.insight.com', debug=0, port=6969, log='log') try: clients = pickle.load(open('clients.p')) except IOError, e: print(e) clients = {} try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected" con.process(1) if con.auth('secret'): print "connected" else: print "problems with handshake: ", con.lastErr, con.lastErrCode sys.exit(1) # con.registerHandler('message',messageCB) con.registerHandler('presence',presenceCB) con.registerHandler('iq',iqCB) p = jabber.Presence(type='available') p.setFrom('mailcheck/registered') for c in clients.keys(): p.setTo(clients[c].jid) con.send(p) try: while(1): con.process(10) # whoo baby, is this a kludge. Should really have a bona-fide event # loop or thread that processes the user's email checking, or at least # build up a timer type element that only runs this once every five # minutes or so... for c in clients.keys(): clients[c].doit() except KeyboardInterrupt: p = jabber.Presence(type='unavailable') p.setFrom('mailcheck/registered') for c in clients.keys(): p.setTo(clients[c].jid) con.send(p) pickle.dump(clients, open('clients.p', 'w')) con.disconnect() jabber.py-0.5.0.orig/examples/offline.xpm0000644000175000017500000000363007372240020020471 0ustar kalfakalfa00000000000000/* XPM */ static char * unknown[] = { "17 16 69 2", " s None c None", ".. c #6f6f6f", "#. c #e5b684", "a. c #030303", "b. c #ff0000", "c. c #bcbcbc", "d. c #e1e1e1", "e. c #161514", "f. c #535353", "g. c #aeaeae", "h. c #af8a65", "i. c #4f4e4d", "j. c #302d2a", "k. c #313131", "l. c #c9a682", "m. c #b89978", "n. c #565656", "o. c #202020", "p. c #fccb98", "q. c #a0a0a0", "r. c #35281a", "s. c #a3a3a3", "t. c #484848", "u. c #121212", "v. c #a18262", "w. c #959595", "x. c #bababa", "y. c #4e4e4e", "z. c #3a3633", "A. c #2a2a2d", "B. c #19191c", "C. c #e2e2e2", "D. c #5f4225", "E. c #8a8a8a", "F. c #7d6a57", "G. c #ffce9c", "H. c #4e4b47", "I. c #e8e8e8", "J. c #d7d7d7", "K. c #212121", "L. c #735332", "M. c #909090", "N. c #bc9975", "O. c #3f3020", "P. c #aa0000", "Q. c #828282", "R. c #a7a7a7", "S. c #880000", "T. c #3b3630", "U. c #a58057", "V. c #302a25", "W. c #d0ab86", "X. c #fdcc9a", "Y. c #bf9a75", "Z. c #1c1c1c", "0. c #3e352c", "1. c #c7a581", "2. c #161413", "3. c #514940", "4. c #56493b", "5. c #efc293", "6. c #3d3c3b", "7. c #7b6955", "8. c #e9e9e9", "9. c #bb9b7a", ".# c #725130", "## c #e1b381", "a# c #4e3f2f", "b# c #a37e59", " ", " I.s.n.n.n.s.I. ", " 8.i.D.v.v.v.D.6.C. ", " d.H.U.X.G.G.G.X.U.j.J. ", " E..#p.G.G.G.G.G.p.L.Q. ", " k.Y.G.7.0.G.3.F.G.W.K. ", " k.Y.G.5.G.G.G.5.G.W.K. ", " f.b#G.G.1.1.1.G.G.h.t. ", " c.O.##l.T.V.V.N.#.a#g. ", " M.r.m.G.G.G.9.4.w. ", " x.u.2.z.z.z.e.a.R. ", " q.A.S.P.P.P.P.P.S.B.c. ", " ..S.b.b.b.b.b.b.b.S.y. ", " k.P.b.b.b.b.b.b.b.P.o. ", " k.S.S.S.S.S.S.S.S.S.Z. ", " "};.u.u.u.u.C.J.g. ", " a.P.k.k.k.k.k.k.k.h.G. ", " s.u.k.k.k.k.k.k.k.a#w. ", " s.j.l#l#l#l#l#l#l###7. ", " "};jabber.py-0.5.0.orig/examples/pyqtjab.py0000755000175000017500000002727307757050453020401 0ustar kalfakalfa00000000000000#!/usr/bin/python2 import sys import string from qt import * import StringIO import jabber import time from threading import * from xml.sax import saxutils from xml.sax import make_parser def sendMessage (con, to, msg): msg = jabber.Message(to, msg) msg.setType('chat') print 'send ->', msg con.send(msg) class DocumentList( QWidget ): def __init__( self, *args ): apply( QWidget.__init__, (self, ) + args ) # 1 x 1 self.mainGrid = QGridLayout( self, 1, 1, 5, 5 ) self.listView = QListView( self ) self.listView.addColumn('Document') self.listView.setSelectionMode( QListView.Extended ) self.connect( self.listView, SIGNAL( 'clicked( QListViewItem* )' ), self.itemSelected ) self.mainGrid.addWidget(self.listView, 1, 0) self.listView.setAllColumnsShowFocus( 1 ) def itemSelected( self, item ): if item: item.setSelected( 1 ) item.repaint() print item.text(0) def addDocument (self, docName): item = QListViewItem(self.listView) item.setText(0, docName) class RosterList( QWidget ): def __init__( self, *args ): apply(QWidget.__init__, (self, ) + args ) self.users = {} self.chatWindows = {} # 1 x 1 self.mainGrid = QGridLayout( self, 1, 1, 5, 5 ) self.listView = QListView( self ) self.listView.addColumn('Handle') self.listView.addColumn('Status') self.listView.addColumn('Unread') self.listView.setSelectionMode( QListView.Extended ) self.connect(self.listView, SIGNAL('clicked( QListViewItem* )' ), self.itemSelected ) self.connect(self.listView, SIGNAL('rightButtonClicked (QListViewItem *, const QPoint &, int)'), self.rightClick) self.mainGrid.addWidget( self.listView, 1, 0 ) self.listView.setAllColumnsShowFocus( 1 ) self.rosterMenu = QPopupMenu(self) self.rosterMenu.insertItem('Add', self.queryAddUser) self.rosterMenu.insertItem('Remove', self.queryRemoveUser) def rightClick (self, item, point, i): self.rosterMenu.exec_loop(point, 0) def queryAddUser(self, userName): newUser = QInputDialog.getText('Add to roster', 'Please enter handle of user to add', 'new user') if newUser and newUser[1]: if con: con.send(jabber.Presence(str(newUser[0]), 'subscribe')) def addUser (self, userName, status): if not self.users.has_key(userName): item = QListViewItem(self.listView) item.setText(0, userName) item.setText(1, status) item.setText(2, '0') self.users[userName] = item def queryRemoveUser (self, userName): pass def itemSelected( self, item ): if item: item.setSelected(1) item.repaint() to = str(item.text(0)) cw = 0 if self.chatWindows.has_key(to): cw = self.chatWindows[to] else: cw = ChatWindow() cw.peer = to cw.con = self.con self.tabWidget.addTab(cw, to) self.chatWindows[to] = cw self.users[to].setText(2, '0') if cw: self.tabWidget.showPage(cw) class ChatWindow (QWidget): def __init__ (self, *args): apply(QWidget.__init__, (self, ) + args ) self.widget = QWidget(self) self.mainGrid = QGridLayout(self.widget, 4, 2, 5, 5 ) self.msgField = QLineEdit('', self.widget, 'MsgField') self.sendButton = QPushButton('&Send', self.widget, 'SendButton') self.clearButton = QPushButton('&Clear', self.widget, 'ClearButton') self.listView = QListView( self.widget ) self.listView.setSelectionMode( QListView.Extended ) self.listView.addColumn('Time') self.listView.addColumn('From') self.listView.addColumn('Message') self.label = QLabel('List of Messages', self.widget) self.mainGrid.addWidget(self.label, 0, 0) self.mainGrid.addMultiCellWidget(self.listView, 1, 1, 0, 1) self.mainGrid.addMultiCellWidget(self.msgField, 2, 2, 0, 1) self.mainGrid.addWidget(self.sendButton, 3, 0) self.mainGrid.addWidget(self.clearButton, 3, 1) self.listView.setAllColumnsShowFocus( 1 ) self.connect(self.sendButton, SIGNAL('clicked( )' ), self.sendNewMessage ) self.connect(self.clearButton, SIGNAL('clicked( )' ), self.clear ) self.connect(self.msgField, SIGNAL('returnPressed( )' ), self.sendNewMessage ) self.grid = QGridLayout(self, 1, 1, 5, 5) self.grid.addWidget(self.widget, 0, 0) def clear (self): if self.listView: self.listView.clear() if self.msgField: self.msgField.setText('') def addMsg (self, source, msg): item = QListViewItem(self.listView) item.setText(0, time.strftime('%X', time.localtime(time.time()))) item.setText(1, source) item.setText(2, msg) def sendNewMessage (self): if self.con and self.msgField.text() and self.peer: self.sendMessage(self.con, self.peer, str(self.msgField.text())); self.addMsg('me', self.msgField.text()) self.msgField.setText('') def sendMessage (self, con, to, msg): msg = jabber.Message(to, msg) msg.setType('chat') print 'send ->', msg con.send(msg) class AgentEditDialog (QTabWidget): def __init__ (self, parent, name, con, agentData): QTabWidget.__init__(self, parent, name) self.con = con self.agentData = agentData self.listView = QListView( self ) self.listView.addColumn('Name') self.listView.addColumn('Value') print self.agentData for key in self.agentData.keys(): item = QListViewItem(self.listView) item.setText(0, key) item.setText(1, self.agentData[key]) name = 'noname' if self.agentData.has_key('name'): name = self.agentData['name'] self.addTab(self.listView, name) class AgentDialog (QTabDialog): def __init__ (self, parent, con): QTabDialog.__init__(self, parent, 'agents' ) self.con = con self.listView = QListView( self ) self.listView.addColumn('Agent') self.regInfo = con.requestRegInfo() #print con.getRegInfo() self.agents = con.requestAgents() for key in self.agents.keys(): item = QListViewItem(self.listView) item.setText(0, key) self.addTab(self.listView, '&Agents') self.connect(self.listView, SIGNAL( 'clicked( QListViewItem* )' ), self.itemSelected ) self.editWindows = {} def itemSelected( self, item ): key = str(item.text(0)); if not self.editWindows.has_key(key): aed = AgentEditDialog(self, None, self.con, self.agents[str(item.text(0))]) self.editWindows[key] = aed self.addTab(aed, key) self.showPage(self.editWindows[key]) class DocumentWindow (QMainWindow): def __init__ (self, con): QMainWindow.__init__( self, None, 'jyqt' ) self.con = con self.initMenuBar() self.initWidgets() if self.con: self.con.registerHandler('presence',self.presenceCB) self.con.registerHandler('message',self.messageCB) self.statusBar().message('Connected') self.timer = QTimer(self) self.connect(self.timer, SIGNAL('timeout()'), self.timeout) self.timer.start(1000) def presenceCB(self, con, prs): who = str(prs.getFrom()) i = string.find(who, '/') status = str(prs.getStatus()) if i > 0: self.rosterList.addUser(who[:i], status) else: self.rosterList.addUser(who, status) who = str(prs.getFrom()) type = prs.getType() if type == None: type = 'available' if type == 'subscribe': con.send(jabber.Presence(to=who, type='subscribed')) con.send(jabber.Presence(to=who, type='subscribe')) elif type == 'unsubscribe': con.send(jabber.Presence(to=who, type='unsubscribed')) con.send(jabber.Presence(to=who, type='unsubscribe')) def messageCB(self, con, msg): sender = str(msg.getFrom()) i = string.find(sender, '/') if i > 0: sender = sender[:i] cw = 0 if self.rosterList.chatWindows.has_key(sender): cw = self.rosterList.chatWindows[sender] else: cw = ChatWindow() cw.peer = sender cw.con = self.con self.tabWidget.addTab(cw, sender) self.rosterList.chatWindows[sender] = cw if cw: source = str(msg.getFrom()) i = string.find(source, '/') if i: source = source[i+1:] cw.addMsg(source, str(msg.getBody())) #self.tabWidget.showPage(cw) tabBar = self.tabWidget.tabBar() tab = tabBar.tab(2) if self.rosterList.users and self.rosterList.users.has_key(sender): item = self.rosterList.users[sender] last = 0 if item.text(2): s = str(item.text(2)) if s: last = int(s) item.setText(2, str(last + 1)) def timeout(self): if self.con: self.con.process(0) def initMenuBar (self): self.fileMenu = QPopupMenu(self) self.menuBar().insertItem('&File', self.fileMenu) self.fileMenu.insertItem( '&About', self.about, Qt.Key_F1) self.fileMenu.insertItem( 'Quit', qApp, SLOT( 'quit()' ), Qt.CTRL + Qt.Key_Q ) self.agentMenu = QPopupMenu(self) self.menuBar().insertItem('&Agents', self.agentMenu) self.agentMenu.insertItem( '&Edit', self.editAgents) def editAgents (self): if self.con: ad = AgentDialog(self, self.con) ad.show() def about(self): QMessageBox.about(self,'JYQT', 'JYQT 0.01 by www.elevenprospect.com') def initWidgets (self): self.tabWidget = QTabWidget(self) self.documentList = DocumentList(self) self.rosterList= RosterList(self) self.rosterList.con = con self.rosterList.tabWidget = self.tabWidget self.tabWidget.addTab(self.rosterList, '&Roster') self.tabWidget.addTab(self.documentList, '&Documents') self.setCentralWidget(self.tabWidget) def addDocument (self, docName): self.documentList.addDocument(docName) userName = '' password = '' hostname = 'jabber.org' for x in xrange(1, len(sys.argv)): if sys.argv[x] == '-u': userName = sys.argv[x + 1] if sys.argv[x] == '-p': password = sys.argv[x + 1] if sys.argv[x] == '-h': hostname = sys.argv[x + 1] # jabber con = None if hostname: con = jabber.Client(host=hostname) if con: try: con.connect() except IOError, e: print e if con and userName and password and con.auth(userName, password, 'default'): print 'connected' else: con = None print 'not connected' if con: con.requestRoster() con.sendInitPresence() else: print 'not connected' # setup QT a = QApplication(sys.argv) dw = DocumentWindow(con) a.setMainWidget(dw) # Start QT Window dw.resize(500, 300) dw.show() a.exec_loop() # disconnect if con: con.disconnect() jabber.py-0.5.0.orig/examples/pygtkjab.py0000755000175000017500000012024307472403120020514 0ustar kalfakalfa00000000000000#!/usr/bin/env python # # TODO: # -- fix mass transport subscribe crash ?? # -- implement group chat # -- catch errors better with dialog to show em. # import sys,string,os,re,time import gtk, _gtk, GDK # Change path so we find jabber libs strait from tarball sys.path.insert(1, os.path.join(sys.path[0], '..')) sys.path.insert(1, os.path.join(sys.path[0], '../util')) import jabber import sleepy TRUE = 1 FALSE = 0 OK = 1 CANCEL = 2 ## add a server name entry to the below ## Known = { 'yahoo': { 'xpm' : 'an xpm path' }, 'msn': { 'xpm' : 'info....'}, 'icq': { 'xpm' : 'info....'}, } def makeKnownNice(jid): for known in Known.keys(): if re.match("^"+known+".*", jid.getDomain()): if jid.getNode(): return jid.getNode() else: return known + " transport" return str(jid) def sort_jids(a,b): if string.lower(str(a)) < string.lower(str(b)): return -1 if string.lower(str(a)) > string.lower(str(b)): return 1 return 0 class Tab: def __init__(self, gui, title): self._type = type self._notebook = gui.notebook self._title = title self._id = None self._box = gtk.GtkVBox() self._main_callback = None self._cb = None self.cmap = gui.get_colormap() self.cols={} self.cols['blue'] = self.cmap.alloc('blue') self.cols['red'] = self.cmap.alloc('red') self.cols['black'] = self.cmap.alloc('black') self.cols['green'] = self.cmap.alloc('green') self.gui = gui def getID(self): return self._id; def setID(self,val): self._id = val; def recieve(self,obj): pass def setCallBack(self,cb): self._cb = cb def getCallBack(self): return self._cb def getData(self): pass def setData(self,val): pass def _addToNoteBook(self): self._tab_label = gtk.GtkLabel(self._title) self._tab_label.show() self._notebook.append_page(self._box,self._tab_label) def tabClicked(self, *args): return gtk.FALSE def highlight(self): #style = _gtk.gtk_rc_get_style() # self._tab_label) style = self._tab_label.get_style() new_style = style.copy() new_style.fg[0] = self.cols['blue'] self._tab_label.set_style(new_style) def lowlight(self): style = self._tab_label.get_style() new_style = style.copy() new_style.fg[0] = self.cols['black'] self._tab_label.set_style(new_style) def getJID(self): return None def destroy(self,*args): i = 0 for tab in self.gui._tabs: if tab == self: self._notebook.remove_page(i) del(self.gui._tabs[i]) ## self.__destroy__ ? i=i+1 class Chat_Tab(Tab): ### Make bigger and Better !!! def __init__(self, gui, jid, title='a tab'): Tab.__init__(self, gui, title) self._id = str(jid.getStripped()) self._scroll = gtk.GtkScrolledWindow() self._txt = gtk.GtkText() self._txt.set_word_wrap( gtk.TRUE ) self._scroll.add(self._txt) self._scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._box.pack_start(self._scroll, fill=gtk.TRUE, expand=gtk.TRUE) self._hbox = gtk.GtkHBox() self._entry = gtk.GtkEntry() self._hbox.pack_start(self._entry, fill=gtk.TRUE, expand=gtk.TRUE) self._send_button = gtk.GtkButton('send') #self._send_button.connect('clicked', self._cb, self) #self._entry.connect('activate', self._cb, self ) self._hbox.pack_end(self._send_button, fill=gtk.FALSE, expand=gtk.FALSE) self._box.pack_end(self._hbox, fill=gtk.TRUE, expand=gtk.FALSE) self._box.show_all() self._addToNoteBook() self._entry.grab_focus() ## this_tab.event_connected = 0 ?? def getJID(self): return self._id def recieve(self,obj): if obj.getFrom().getStripped() == self._id: if str(obj.__class__) == 'jabber.Message': if obj.getError(): err_code = '' if obj.getErrorCode(): err_code = obj.getErrorCode() self._txt.insert(None,self.cols['red'], None, "%s ( %s )" % (obj.getError(), err_code) ) else: self._txt.insert(None,self.cols['red'], None, "<%s> " % obj.getFrom().getStripped()) self._txt.insert(None,None, None, "%s\n" % obj.getBody()) return TRUE if str(obj.__class__) == 'jabber.Presence': if obj.getType() != 'unavailable': self._txt.insert(None,self.cols['green'], None, "<%s> ( %s / %s )\n" % ( obj.getFrom().getStripped(), obj.getStatus(), obj.getShow() ) ) else: self._txt.insert(None,self.cols['green'], None, "<%s> went offline\n" % obj.getFrom().getStripped() ) return TRUE return FALSE def getData(self): txt = self._entry.get_text() self._entry.set_text('') self._txt.insert(None,None,None, "<%s> %s\n" % ( self.gui.jabberObj.loggedin_jid.getStripped(), txt) ) return txt class Debug_Tab(Tab): ### Make bigger and Better !!! def __init__(self, gui, title='DEBUG'): Tab.__init__(self, gui, title) self._id = "DEBUG" self._scroll = gtk.GtkScrolledWindow() self._txt = gtk.GtkText() self._txt.set_word_wrap( gtk.TRUE ) self._scroll.add(self._txt) self._scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._box.pack_start(self._scroll, fill=gtk.TRUE, expand=gtk.TRUE) self._hbox = gtk.GtkHBox() self._box.show_all() self._addToNoteBook() ## this_tab.event_connected = 0 ?? def getJID(self): return self._id def recieve(self,obj): return TRUE class Url_Tab(Tab): ### Make bigger and Better !!! def __init__(self, gui): Tab.__init__(self, gui, 'URLs') self._id = 'URLs' self._regexp = re.compile('(http://[^\s]+)', re.IGNORECASE) self._scrolled_win = gtk.GtkScrolledWindow() self._scrolled_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._box.pack_start(self._scrolled_win) self._list = gtk.GtkList() self._list.set_selection_mode(gtk.SELECTION_BROWSE) self._scrolled_win.add_with_viewport(self._list) self._list.connect("select-child" , self.selectCB) self._hbox = gtk.GtkHBox() self._open_button = gtk.GtkButton('open') self._hbox.pack_end(self._open_button, fill=gtk.FALSE, expand=gtk.FALSE) self._box.pack_end(self._hbox, fill=gtk.TRUE, expand=gtk.FALSE) self._box.show_all() self._addToNoteBook() ## this_tab.event_connected = 0 ?? def getJID(self): return self._id def recieve(self,obj): if str(obj.__class__) == 'jabber.Message': m = self._regexp.match(obj.getBody()) if m: list_item = gtk.GtkListItem(m.group()) self._list.add(list_item) list_item.show() return TRUE return FALSE def selectCB(self, *args): pass class Roster_Tab(Tab): ### Make bigger and Better !!! def __init__(self, gui, title): Tab.__init__(self, gui, title) self._roster_selected = None self._online_icon, self._online_mask = \ gtk.create_pixmap_from_xpm( gui.get_window(), None,"online.xpm" ); self._offline_icon, self._offline_mask = \ gtk.create_pixmap_from_xpm( gui.get_window(), None,"offline.xpm" ); self._pending_icon, self._pending_mask = \ gtk.create_pixmap_from_xpm( gui.get_window(), None,"pending.xpm" ); self._rows = [] self._scroll = gtk.GtkScrolledWindow() self._ctree = gtk.GtkCTree(1,0) self._ctree.set_column_width(0,200); self._ctree.set_line_style(gtk.CTREE_LINES_NONE) self._ctree.set_expander_style(gtk.CTREE_EXPANDER_CIRCULAR) self._ctree.connect("select_row" , self.rosterSelectCB) self.paint_tree() self._scroll.add(self._ctree) self._scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.FALSE) self._box.pack_start(self._scroll, fill=gtk.TRUE, expand=gtk.TRUE) self._hbox = gtk.GtkHBox() self._box.pack_end(self._hbox, fill=gtk.TRUE, expand=gtk.FALSE) self._box.show_all() self._addToNoteBook() def rosterSelectCB(self, *args): self._roster_selected = self._ctree.get_row_data(int(args[1])) if args[3].type == GDK._2BUTTON_PRESS: self._cb() def get_roster_selection(self): return self._roster_selected def recieve(self,obj): if str(obj.__class__) != 'jabber.Message': if str(obj.__class__) == 'jabber.Iq': if obj.getQuery() == jabber.NS_ROSTER: self.paint_tree() ## only paint if roster iq else: self.paint_tree() ## a presence def paint_tree(self): self._ctree.freeze() self._ctree.clear() self._online_node = self._ctree.insert_node( None, None, ( 'online', ), 2, None, None, None, None, gtk.FALSE, gtk.TRUE ) self._offline_node = self._ctree.insert_node( None, None, ( 'offline', ), 2, None, None, None, None, gtk.FALSE, gtk.TRUE ) self._pending_node = self._ctree.insert_node( None, None, ( 'pending', ), 2, None, None, None, None, gtk.FALSE, gtk.TRUE ) _roster = self.gui.jabberObj.getRoster() self._nodes = [] jids = _roster.getJIDs() jids.sort(sort_jids) for jid in jids: attach_node = None nice_name = makeKnownNice(jid) show = '' if _roster.getShow(jid): show = _roster.getShow(jid) if _roster.getStatus(jid): if show: show = " ( %s / %s )" % ( show, _roster.getStatus(jid) ) else: show = " ( %s )" % _roster.getStatus(jid) nice_name = str("%s %s" % ( nice_name, show )) if _roster.getOnline(jid) == 'online': node =self._ctree.insert_node( self._online_node, None, ( nice_name, ) , 2, pixmap_closed = self._online_icon, mask_closed = self._online_mask, is_leaf=gtk.TRUE, expanded=gtk.TRUE ) elif _roster.getOnline(jid) == 'offline': node =self._ctree.insert_node( self._offline_node, None, ( nice_name, ) , 2, pixmap_closed = self._offline_icon, mask_closed = self._offline_mask, is_leaf=gtk.TRUE, expanded=gtk.TRUE ) elif _roster.getOnline(jid) == 'pending': node =self._ctree.insert_node( self._pending_node, None, ( nice_name, ) , 2, pixmap_closed = self._pending_icon, mask_closed = self._pending_mask, is_leaf=gtk.TRUE, expanded=gtk.TRUE ) else: pass self._nodes.append(node) self._ctree.node_set_row_data(node, str(jid)) self._ctree.thaw() if self.gui._tabs and self != self.gui.getSelectedTab(): self.highlight() class Logon_dialog(gtk.GtkWindow): def __init__(self, master): gtk.GtkWindow.__init__(self) self.password = '' self.username = '' self.server = 'jabber.org' self.done = None self.connect("delete_event", self.delete_event) self.master = master self.vbox = gtk.GtkVBox(gtk.FALSE,5) self.add(self.vbox) self.frame_s = gtk.GtkFrame("Server to use") self.table_s = gtk.GtkTable(1,6,gtk.FALSE) self.server_lbl = gtk.GtkLabel('Server') self.server_lbl.set_alignment(1,0.5) self.server_entry = gtk.GtkEntry() self.table_s.attach( self.server_lbl, 0,2,0,1,xpadding=3,ypadding=2) self.table_s.attach( self.server_entry, 2,6,0,1,xpadding=3,ypadding=2) self.frame_s.add(self.table_s) self.vbox.pack_start(self.frame_s) self.frame = gtk.GtkFrame("Have Account?") self.table = gtk.GtkTable(6,6,gtk.FALSE) self.username_lbl = gtk.GtkLabel('Username') self.username_lbl.set_alignment(1,0.5) self.password_lbl = gtk.GtkLabel('Password') self.password_lbl.set_alignment(1,0.5) self.username_entry = gtk.GtkEntry() self.password_entry = gtk.GtkEntry() self.password_entry.set_visibility(gtk.FALSE) self.table.attach( self.username_lbl, 0,2,1,2,xpadding=3,ypadding=2) self.table.attach( self.password_lbl, 0,2,2,3,xpadding=3,ypadding=2) self.table.attach( self.username_entry, 2,6,1,2,xpadding=3,ypadding=2) self.table.attach( self.password_entry, 2,6,2,3,xpadding=3,ypadding=2) self.save_check = gtk.GtkCheckButton('Save Details') self.table.attach( self.save_check, 3,6,4,5,xpadding=3,ypadding=2) self.login_button = gtk.GtkButton('Login') self.login_button.connect('clicked', self.login) self.table.attach( self.login_button, 3,6,5,6,xpadding=5) self.frame.add(self.table) self.vbox.pack_start(self.frame) self.frame_acc = gtk.GtkFrame("New User?") self.table_acc = gtk.GtkTable(1,1,gtk.FALSE) self.button_acc = gtk.GtkButton("Get an Account") self.button_acc.connect('clicked', self.new_account) self.table_acc.attach( self.button_acc, 0,1,0,1,xpadding=5,ypadding=5) self.frame_acc.add(self.table_acc) self.vbox.pack_end(self.frame_acc) self.readRC() self.username_entry.set_text(self.username) self.password_entry.set_text(self.password) self.server_entry.set_text(self.server) self.vbox.show_all() self.show() self.set_modal(gtk.TRUE) def login(self,*args): self.password = self.password_entry.get_text() self.username = self.username_entry.get_text() self.server = self.server_entry.get_text() self.done = gtk.TRUE if self.save_check.get_active(): try: rcfile = open(os.environ['HOME'] + "/.pyjab",'w') except: return rcfile.write("%s\0%s\0%s\n" % (self.server, self.username, self.password)) rcfile.close() else: try: os.remove(os.environ['HOME'] + "/.pyjab") except: pass # file dont exist, or I cant delete def readRC(self): try: rcfile = open(os.environ['HOME'] + "/.pyjab",'r') except: return self.save_check.set_active(gtk.TRUE) data = (rcfile.readline().splitlines())[0] self.server, self.username, self.password = data.split("\0") rcfile.close() return def new_account(self,*args): self.done = 2 def delete_event(self, *args): gtk.mainquit() sys.exit(0) def close(self,*args): self.hide() del self class New_ac_dialog(gtk.GtkWindow): def __init__(self, master, jabber, agent=None): gtk.GtkWindow.__init__(self) self.connect("delete_event", self.delete_event) self.master = master self.jabber = jabber self.done = None self.agent = agent self.vbox = gtk.GtkVBox(gtk.FALSE,5) self.add(self.vbox) self.frame = gtk.GtkFrame("New Account") self.jabber.requestRegInfo(self.agent) req = self.jabber.getRegInfo() self.table = gtk.GtkTable(6,6,gtk.FALSE) self.instr_lbl = gtk.GtkLabel(req[u'instructions']) self.entrys = {} i = 0 for info in req.keys(): if info != u'instructions' and \ info != u'key': self.entrys[info] = {} self.entrys[info]['lbl'] = gtk.GtkLabel(info) self.entrys[info]['lbl'].set_alignment(1,0.5) self.entrys[info]['entry'] = gtk.GtkEntry() self.table.attach( self.entrys[info]['lbl'], 0,2,1+i,2+i, xpadding=3,ypadding=2) self.table.attach( self.entrys[info]['entry'], 2,6,1+i,2+i, xpadding=3,ypadding=2) i=i+1 self.reg_button = gtk.GtkButton('Register') self.table.attach( self.reg_button, 2,6,0,1,xpadding=3,ypadding=2) self.reg_button.connect('clicked', self.register) self.frame.add(self.table) self.vbox.pack_start(self.frame) self.vbox.show_all() self.show() self.set_modal(gtk.TRUE) def register(self,*args): for info in self.entrys.keys(): self.jabber.setRegInfo( info, self.entrys[info]['entry'].get_text() ) self.username = self.entrys['username']['entry'].get_text() self.password = self.entrys['password']['entry'].get_text() self.jabber.sendRegInfo(self.agent) self.done = OK def delete_event(win, event=None): self.hide() return gtk.TRUE def close(self,*args): self.hide() del self class Add_dialog(gtk.GtkDialog): def __init__(self, master, jabberObj): gtk.GtkDialog.__init__(self) self.jid_str = None self.done = None self.connect("delete_event", self.delete_event) self.master = master self.jabber = jabberObj if self.master: self.set_transient_for(self.master) self.set_usize(200,150) self.table = gtk.GtkTable(5,2,gtk.FALSE) self.jid_lbl = gtk.GtkLabel('JID') self.jid_entry = gtk.GtkEntry() self.table.attach( self.jid_lbl, 0,1,0,1) self.table.attach( self.jid_entry, 1,2,0,1) self.add_button = gtk.GtkButton('Add') self.add_button.connect('clicked', self.add) self.action_area.pack_start(self.add_button,expand=gtk.FALSE) self.vbox.pack_start(self.table) self.vbox.show_all() self.action_area.show_all() self.show() self.set_modal(gtk.TRUE) def add(self,*args): self.done = self.jid_entry.get_text() def delete_event(win, event=None): self.hide() self.done = 1 return gtk.FALSE def close(self,*args): self.hide() del self class Status_dialog(gtk.GtkDialog): def __init__(self): gtk.GtkDialog.__init__(self) self.jid_str = None self.done = None self.type = 'available' self.connect("delete_event", self.delete_event) #self.master = master #self.jabber = jabberObj self.set_usize(200,150) self.table = gtk.GtkTable(5,2,gtk.FALSE) self.jid_lbl = gtk.GtkLabel('Status') self.jid_entry = gtk.GtkEntry() self.table.attach( self.jid_lbl, 0,1,0,1) self.table.attach( self.jid_entry, 1,2,0,1) self.add_button = gtk.GtkButton('Set') self.add_button.connect('clicked', self.set) self.action_area.pack_start(self.add_button,expand=gtk.FALSE) self.avail_radio = gtk.GtkRadioButton(None, 'available') self.unavail_radio = gtk.GtkRadioButton(self.avail_radio, 'unavailable') self.avail_radio.connect('clicked', self.avail) self.unavail_radio.connect('clicked', self.unavail) self.avail_radio.set_active(gtk.TRUE) self.table.attach( self.avail_radio, 0,2,1,2) self.table.attach( self.unavail_radio, 0,2,2,3) self.vbox.pack_start(self.table) self.vbox.show_all() self.action_area.show_all() self.show() self.set_modal(gtk.TRUE) def avail(self, *args): self.type = None def unavail(self, *args): self.type = 'unavailable' def set(self,*args): self.done = ( self.type , self.jid_entry.get_text() ) def delete_event(win, event=None): self.hide() self.done = 1 return gtk.FALSE def close(self,*args): self.hide() del self MSG_DIA_TYPE_OK = 0 MSG_DIA_TYPE_YESNO = 1 MSG_DIA_RET_OK = 1 MSG_DIA_RET_CANCEL = 2 class Msg_dialog(gtk.GtkDialog): def __init__(self, master, msg, type = MSG_DIA_TYPE_OK ): gtk.GtkDialog.__init__(self) self.done = None self.connect("delete_event", self.delete_event) self.master = master self.set_usize(200,150) if self.master: self.set_transient_for(self.master) self.msg_lbl = gtk.GtkLabel(msg) self.ok_button = gtk.GtkButton('Ok') self.ok_button.connect('clicked', self.okay) self.action_area.pack_start(self.ok_button,expand=gtk.FALSE) if type == MSG_DIA_TYPE_YESNO: self.cancel_button = gtk.GtkButton('Cancel') self.cancel_button.connect('clicked', self.cancel) self.action_area.pack_start(self.cancel_button,expand=gtk.FALSE) self.vbox.pack_start(self.msg_lbl) self.vbox.show_all() self.action_area.show_all() self.show() self.set_modal(gtk.TRUE) def okay(self,*args): self.done = MSG_DIA_RET_OK def cancel(self,*args): self.done = MSG_DIA_RET_CANCEL def delete_event(win, event=None): self.hide() self.done = MSG_DIA_RET_CANCEL def close(self,*args): self.hide() del self class Trans_dialog(gtk.GtkDialog): def __init__(self, master, jabberObj ): gtk.GtkDialog.__init__(self) self.agents = jabberObj.requestAgents() self.done = None self.connect("delete_event", self.delete_event) self.master = master self.set_usize(200,150) if self.master: self.set_transient_for(self.master) self.ok_button = gtk.GtkButton('Ok') self.ok_button.connect('clicked', self.okay) self.action_area.pack_start(self.ok_button,expand=gtk.FALSE) self.cancel_button = gtk.GtkButton('Cancel') self.cancel_button.connect('clicked', self.cancel) self.action_area.pack_start(self.cancel_button,expand=gtk.FALSE) self.scrolled_win = gtk.GtkScrolledWindow() self.scrolled_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.vbox.pack_start(self.scrolled_win) self.list = gtk.GtkList() self.list.set_selection_mode(gtk.SELECTION_BROWSE) self.scrolled_win.add_with_viewport(self.list) for i in self.agents.keys(): if self.agents[i].has_key('transport'): list_item = gtk.GtkListItem(self.agents[i]['name']) list_item.set_data('jid', i) self.list.add(list_item) list_item.show() self.list.connect("select-child" , self.selectCB) self.vbox.pack_start(self.scrolled_win) self.vbox.show_all() self.action_area.show_all() self.show() self.selected = None self.set_modal(gtk.TRUE) def selectCB(self, *args): self.selected = args[1].get_data('jid') def okay(self,*args): self.done = OK def cancel(self,*args): self.done = CANCEL def delete_event(win, event=None): self.hide() self.done = MSG_DIA_RET_CANCEL def close(self,*args): self.hide() del self class mainWindow(gtk.GtkWindow): # Usual Base def __init__(self, title='pygtk app', jabberObj=None, width=None, height=None): gtk.GtkWindow.__init__(self) self.set_title(title) if width is None: if gtk.screen_width() > 300: ## Fit the display width = 320 height = 200 else: width = 240 height = 300 self._tabs = [] self.cols = {}; self.jabberObj = jabberObj self.roster_selected = None self.set_usize(width,height) self.connect("delete_event", self.quit) self.box = gtk.GtkVBox() self.add(self.box) self.box.show() self.tbox = gtk.GtkHBox() self.checkItemCalled = 0 self.init_menu() self.init_status_select() self.close_but = gtk.GtkButton('X') self.close_but.connect("clicked", self.closeTabCB); self.close_but.show() self.tbox.pack_end(self.close_but, fill=gtk.FALSE, expand=gtk.FALSE) self.tbox.show() self.box.pack_start(self.tbox, fill=gtk.FALSE, expand=gtk.FALSE) self.notebook = gtk.GtkNotebook() self.notebook.set_tab_pos (gtk.POS_BOTTOM); self.notebook.set_scrollable( gtk.TRUE ) self.notebook.connect('switch_page', self.notebook_switched) self.box.pack_end(self.notebook, fill=gtk.TRUE, expand=gtk.TRUE) self._tabs.append( Roster_Tab(self, 'roster') ) self.notebook.show() self.show() def init_status_select(self): ag = gtk.GtkAccelGroup() self.itemsel = gtk.GtkItemFactory(gtk.GtkOptionMenu, "') self.tbox.pack_start(self.status_select, fill=gtk.TRUE, expand=gtk.TRUE) self.status_select.show() def init_menu(self): ag = gtk.GtkAccelGroup() self.itemf = gtk.GtkItemFactory(gtk.GtkMenuBar, "
", ag) self.add_accel_group(ag) self.itemf.create_items([ ('/File', None, None, 0, ''), ('/File/Exit', None, self.quit, 0, ''), ('/Tools', None, None, 0, ''), ('/Tools/Chat', None, self.jabberObj.addChatTabViaRoster, 1, ''), ('/Tools/sep1', None, None, 0, ''), ('/Tools/Add', None, self.addCB, 1, ''), ('/Tools/Remove', None, self.removeCB, 0, ''), ('/Tools/Status/Available', None, self.statusCB, 1, ''), ('/Tools/Status/Unavailable', None, self.statusCB, 0, ''), ('/Tools/Status/Custom', None, self.custstatusCB, 0, ''), ('/Tools/sep2', None, None, 0, ''), ('/Tools/Transports', None, self.transCB, 0, ''), ('/Tools/Tabs/Rotate', None, self.rotateTabCB, 0, ''), ('/Tools/Tabs/Url Grabber', None, self.urlTabCB, 0, ''), ('/Tools/Tabs/Debug', None, self.debugTabCB, 0, ''), ('/Help', None, None, 0, '') , ('/Help/About', None, self.infoCB, 0, '') ]) self.menubar = self.itemf.get_widget('
') self.itemf.get_widget( '/Tools/Status/Available' ).set_active(gtk.TRUE) self.tbox.pack_start(self.menubar, fill=gtk.TRUE, expand=gtk.TRUE) self.menubar.show() def statusCB(self,action,widget): if self.checkItemCalled == 1: ## Make sure set_active does not return ## recall the callback self.checkItemCalled = 1; ## More nasty workarounds for ItemFactory Radiobutton problems for path in [ '/Tools/Status/Available', '/Tools/Status/Unavailable' ]: if widget != self.itemf.get_widget( path ): self.itemf.get_widget( path ).set_active(gtk.FALSE) self.checkItemCalled = 0; if action == 1: # available self.jabberObj.presence_details = [ 'available', None ] pres = jabber.Presence() else: self.jabberObj.presence_details = [ 'unavailable', None ] pres = jabber.Presence(type='unavailable') self.jabberObj.send(pres) def custstatusCB(self, *args): dia = Status_dialog() while dia.done is None: self.jabberObj.process() type, show = dia.done pres = jabber.Presence(type=type) pres.setShow(show) self.jabberObj.presence_details = [ type, show ] self.jabberObj.send(pres) dia.close() def urlTabCB(self, *args): url_tab = self.findTab( 'URLs' ) if url_tab: url_tab.destroy() else: self._tabs.append( Url_Tab(self) ) def debugTabCB(self, *args): dbg_tab = self.findTab( 'DEBUG' ) if dbg_tab: dbg_tab.destroy() else: self._tabs.append( Debug_Tab(self) ) def rotateTabCB(self, *args): if self.notebook.get_tab_pos() == gtk.POS_BOTTOM: self.notebook.set_tab_pos( gtk.POS_LEFT ) else: self.notebook.set_tab_pos( gtk.POS_BOTTOM ) def transCB(self, *args): trans_dia = Trans_dialog(None, self.jabberObj) while (trans_dia.done is None): self.jabberObj.process() if trans_dia.done == OK and trans_dia.selected: names = string.split(trans_dia.selected, '.') agent = names[0] trans_dia.close() new_acc_dia = New_ac_dialog(None, self.jabberObj, agent=agent) while (new_acc_dia.done is None): self.jabberObj.process() new_acc_dia.close() return trans_dia.close() def addCB(self, *args): add_dia = Add_dialog(self, self.jabberObj ) while (add_dia.done is None): self.jabberObj.process() self.jabberObj.send(jabber.Presence(add_dia.done, 'subscribe')) add_dia.close() def removeCB(self,*args): who = self.getTab(0).get_roster_selection() if not who: return msg_dia = Msg_dialog(None, "unsubscribe %s ?" % (who), MSG_DIA_TYPE_YESNO ) while (msg_dia.done is None): self.jabberObj.process() if (msg_dia.done == MSG_DIA_RET_OK): self.jabberObj.send(jabber.Presence(to=who, type='unsubscribe')) msg_dia.close() def closeTabCB(self, *args): if self.notebook.get_current_page(): self.getSelectedTab().destroy() def findCB(self, *args): pass def infoCB(self, *args): pass def handle_switch(self,*args): tab_no = self.notebook.get_current_page() self.getTab(tab_no).lowlight() def notebook_switched(self, *args): gtk.idle_add(self.handle_switch) def findTab(self,id): for tab in self._tabs: if tab._id == id: return tab return None def getTabs(self): return self._tabs def getTab(self,val): return self._tabs[val] def getSelectedTab(self): return self._tabs[self.notebook.get_current_page()] def addTab(self,tab_obj): self._tabs.append( tab_obj ) return tab_obj def removeTab(self,tab): if type(tab) == type(1): self.notebook.remove_tab(tab) del self._tabs[tab] else: print "not yet implemented" def quit(self, *args): #gtk.mainquit() sys.exit(0) class jabberClient(jabber.Client): def __init__(self): self.sleeper = None self.sleeper_state = None self.gui = None not_connected = 1 while not_connected: login_dia = Logon_dialog(None) while (login_dia.done is None): while gtk.events_pending(): gtk.mainiteration() login_dia.close() server = login_dia.server jabber.Client.__init__(self,host=server,debug=0) try: self.connect() except: msg_dia = Msg_dialog(None, "Couldnt connect to "+server) while (msg_dia.done is None): while gtk.events_pending(): gtk.mainiteration() msg_dia.close() sys.exit(0) else: print "connected!" if (login_dia.done == 2): new_acc_dia = New_ac_dialog(None, self) while (new_acc_dia.done is None): self.process() new_acc_dia.close() username = new_acc_dia.username password = new_acc_dia.password else: username = login_dia.username password = login_dia.password resource = 'pygtkjab' print "logging in" if self.auth(username,password,resource): not_connected = 0 else: msg_dia = Msg_dialog(None, self.lastErr) while (msg_dia.done is None): while gtk.events_pending(): gtk.mainiteration() msg_dia.close() #print "eek -> ", self.lastErr, self.lastErrCode sys.exit(1) self.loggedin_jid = jabber.JID( node = username, domain = server, resource = resource ); self.presence_details = [ 'available', None ] Known[server] = { 'xpm':'something' } ## Build the roster Tab ## self.roster = [] r = self.requestRoster() self.gui = mainWindow("jabber app",jabberObj=self) self.gui.getTab(0)._cb = self.addChatTabViaRoster; self.sendInitPresence() self._unsub_lock = 0 ## hack to fix unsubscribe wierdo bug self._pres_queue = [] self.sleeper = sleepy.Sleepy() def addToRoster(self, *args): pass def dispatch_to_gui(self,obj): recieved = None for t in self.gui.getTabs(): if t.recieve(obj): recieved = t return recieved def addChatTabViaRoster(self, *args): jid_raw = self.gui.getTab(0).get_roster_selection() if jid_raw: jid = jabber.JID(jid_raw) i = 0 for t in self.gui.getTabs(): if t.getJID() == jid.getStripped(): self.gui.notebook.set_page(i) return i=i+1 self.gui.addTab( Chat_Tab(self.gui, jid, makeKnownNice(jid) ) ) self.gui.getTab(-1)._send_button.connect('clicked', self.messageSend, self.gui.getTab(-1) ) self.gui.getTab(-1)._entry.connect('activate', self.messageSend, self.gui.getTab(-1) ) self.gui.notebook.set_page(i) def messageSend(self, *args): tab = args[-1] msg = tab.getData() msg_obj = jabber.Message(tab._id, msg) msg_obj.setType('chat') self.send(msg_obj) def messageHandler(self, msg_obj): tab = self.dispatch_to_gui(msg_obj) if tab is None: self.gui.addTab( Chat_Tab(self.gui, msg_obj.getFrom(), makeKnownNice(msg_obj.getFrom()) ) ).recieve(msg_obj) self.gui._tabs[-1]._send_button.connect('clicked', self.messageSend, self.gui._tabs[-1] ) self.gui.getTab(-1)._entry.connect('activate', self.messageSend, self.gui.getTab(-1) ) self.gui._tabs[-1].highlight() else: if tab != self.gui.getSelectedTab(): tab.highlight() def presenceHandler(self, prs_obj): type = prs_obj.getType() who = prs_obj.getFrom().getStripped() if type == 'subscribe': msg_dia = Msg_dialog(None, "subscribe request from %s" % (who), MSG_DIA_TYPE_YESNO ) while (msg_dia.done is None): self.process() if (msg_dia.done == MSG_DIA_RET_OK): self.send(jabber.Presence(to=who, type='subscribed')) if who not in self.getRoster().getJIDs() or \ self.getRoster().getSub(who) != 'both': self.send(jabber.Presence(to=who, type='subscribe')) msg_dia.close() elif type == 'unsubscribe' and not self._unsub_lock: self._unsub_lock = 1 ## HACK ! msg_dia = Msg_dialog(None, "unsubscribe request from %s" % (who), MSG_DIA_TYPE_YESNO ) while (msg_dia.done is None): self.process() if (msg_dia.done == MSG_DIA_RET_OK): self.send(jabber.Presence(to=who, type='unsubscribed')) msg_dia.close() else: pass self.dispatch_to_gui(prs_obj) self._unsub_lock = 0 def iqHandler(self, iq_obj): self.dispatch_to_gui(iq_obj) def process(self,time=0.1): while gtk.events_pending(): gtk.mainiteration() jabber.Client.process(self,time) if self.sleeper: state_pres = None self.sleeper.poll() state = self.sleeper.getState() if state != self.sleeper_state: if state == sleepy.STATE_WOKEN: state_pres = jabber.Presence(type='available') state_pres.setStatus('online') state_pres.setShow('') if state == sleepy.STATE_SLEEPING: state_pres = jabber.Presence(type='available') state_pres.setStatus('away') state_pres.setShow('Away from computer') if state_pres: self.send(state_pres) self.sleeper_state = state def log(self, data, inout=''): ## we overide xmlstreams log method with our own if self.gui: dbg_tab = self.gui.findTab( 'DEBUG' ) if dbg_tab: dbg_tab._txt.insert(None, None, None, "%s - %s - %s\n" % \ (time.asctime(time.localtime(time.time())), inout, data ) ) def main(): # pass args to jabberClient object # if -f exists mkfifo named with f param, open for writing ( r+ ) # launcher will open this for reading after forking the app # app will then pipe messages to it s = jabberClient() while(1): s.process() if __name__ == "__main__": main() jabber.py-0.5.0.orig/examples/pending.xpm0000644000175000017500000000437107372240020020476 0ustar kalfakalfa00000000000000/* XPM */ static char * unknown[] = { "17 16 102 2", " s None c None", ".. c #fd0000", "#. c #b50000", "a. c #e80808", "b. c #6f6f6f", "c. c #e5b684", "d. c #030303", "e. c #e70202", "f. c #ff0000", "g. c #158900", "h. c #d50f0c", "i. c #b80000", "j. c #bcbcbc", "k. c #00ff00", "l. c #f30504", "m. c #161514", "n. c #bf2119", "o. c #e80302", "p. c #d90503", "q. c #ad0400", "r. c #aeaeae", "s. c #535353", "t. c #af8a65", "u. c #b89978", "v. c #c9a682", "w. c #313131", "x. c #202020", "y. c #0ede00", "z. c #a0a0a0", "A. c #35281a", "B. c #e90705", "C. c #c12828", "D. c #8a4c00", "E. c #ed0302", "F. c #484848", "G. c #e70909", "H. c #121212", "I. c #e70f0b", "J. c #008800", "K. c #959595", "L. c #be8263", "M. c #b70101", "N. c #e11600", "O. c #bababa", "P. c #4e4e4e", "Q. c #c40000", "R. c #2a2a2d", "S. c #19191c", "T. c #e90000", "U. c #a41f1a", "V. c #e2e2e2", "W. c #d61a00", "X. c #1dd200", "Y. c #f69872", "Z. c #ba140f", "0. c #bf1f17", "1. c #ffce9c", "2. c #f41d16", "3. c #c60100", "4. c #d7d7d7", "5. c #212121", "6. c #d53e2f", "7. c #909090", "8. c #ef0000", "9. c #ec0100", ".# c #b50202", "## c #009500", "a# c #3f3020", "b# c #e70404", "c# c #aa0000", "d# c #828282", "e# c #a7a7a7", "f# c #eb0c09", "g# c #ec0200", "h# c #00aa00", "i# c #c24242", "j# c #d69d9d", "k# c #d30606", "l# c #f60000", "m# c #d0ab86", "n# c #cf1711", "o# c #d20a09", "p# c #bf9a75", "q# c #1c1c1c", "r# c #3e352c", "s# c #161413", "t# c #56493b", "u# c #efc293", "v# c #cf1b14", "w# c #7b6955", "x# c #b20000", "y# c #0de500", "z# c #f29974", "A# c #d44636", "B# c #bb9b7a", "C# c #4e3f2f", "D# c #e1b381", "E# c #b91212", "F# c #af2322", "G# c #bc1c00", "H# c #d0221a", "I# c #a37e59", " ", " c#p.3.#..#E#j# ", " Q.e.2.B.o.b#a.C.V. ", " c#T.f.Y.0.Z.v#l.G.i#4. ", " i.8...f.1.1.1.z#n#o#F#d# ", " M.k#f.1.w#r#1.f.9.h.U.5. ", " w.p#1.u#1.f...I.A#m#5. ", " s.I#1.1.f.f.f#6.1.t.F. ", " j.a#D#v.f.l#H#L.c.C#r. ", " 7.A.u.f.E.n.B#t#K. ", " O.H.s#f.g#c#m.d.e# ", " z.R.J.h#f.N.c#h#J.S.j. ", " b.J.k.k.k.k.X.k.k.J.P. ", " w.h#k.y#D.W.c#y.k.h#x. ", " w.J.J.g.G#9.c#J.##J.q# ", " q.x#c# "};jabber.py-0.5.0.orig/examples/test_client.py0000755000175000017500000001737507753107460021243 0ustar kalfakalfa00000000000000#!/usr/bin/python # $Id: test_client.py,v 1.11 2003/11/08 06:37:36 snakeru Exp $ # You may need to change the above line to point at # python rather than python2 depending on your os/distro import socket from select import select from string import split,strip,join import sys,os sys.path.insert(1, os.path.join(sys.path[0], '..')) import jabber True = 1 False = 0 # Change this to 0 if you dont want a color xterm USE_COLOR = 1 Who = '' MyStatus = '' MyShow = '' #jabber.xmlstream.ENCODING='koi8-r' # Default is "utf-8" def usage(): print "%s: a simple python jabber client " % sys.argv[0] print "usage:" print "%s - connect to and register" % sys.argv[0] print "%s " % sys.argv[0] print " - connect to server and login " sys.exit(0) def doCmd(con,txt): global Who if txt[0] == '/' : cmd = split(txt) if cmd[0] == '/select': Who = cmd[1] print "%s selected" % cmd[1] elif cmd[0] == '/presence': to = cmd[1] type = cmd[2] con.send(jabber.Presence(to, type)) elif cmd[0] == '/status': p = jabber.Presence() MyStatus = ' '.join(cmd[1:]) p.setStatus(MyStatus) con.send(p) elif cmd[0] == '/show': p = jabber.Presence() MyShow = ' '.join(cmd[1:]) p.setShow(MyShow) con.send(p) elif cmd[0] == '/subscribe': to = cmd[1] con.send(jabber.Presence(to, 'subscribe')) elif cmd[0] == '/unsubscribe': to = cmd[1] con.send(jabber.Presence(to, 'unsubscribe')) elif cmd[0] == '/roster': con.requestRoster() _roster = con.getRoster() for jid in _roster.getJIDs(): print colorize(u"%s :: %s (%s/%s)" % ( jid, _roster.getOnline(jid), _roster.getStatus(jid), _roster.getShow(jid), ) , 'blue' ) elif cmd[0] == '/agents': print con.requestAgents() elif cmd[0] == '/register': agent = '' if len(cmd) > 1: agent = cmd[1] con.requestRegInfo(agent) print con.getRegInfo() elif cmd[0] == '/exit': con.disconnect() print colorize("Bye!",'red') sys.exit(0) elif cmd[0] == '/help': print "commands are:" print " /select " print " - selects who to send messages to" print " /subscribe " print " - subscribe to jid's presence" print " /unsubscribe " print " - unsubscribe to jid's presence" print " /presence " print " - sends a presence of type to the jabber id" print " /status " print " - set your presence status message" print " /show " print " - set your presence show message" print " /roster" print " - requests roster from the server and " print " display a basic dump of it." print " /exit" print " - exit cleanly" else: print colorize("uh?", 'red') else: if Who != '': msg = jabber.Message(Who, strip(txt)) msg.setType('chat') print "<%s> %s" % (JID, msg.getBody()) con.send(msg) else: print colorize('Nobody selected','red') def messageCB(con, msg): """Called when a message is recieved""" if msg.getBody(): ## Dont show blank messages ## print colorize( u'<' + str(msg.getFrom()) + '>', 'green' ) + ' ' + msg.getBody() def presenceCB(con, prs): """Called when a presence is recieved""" who = str(prs.getFrom()) type = prs.getType() if type == None: type = 'available' # subscription request: # - accept their subscription # - send request for subscription to their presence if type == 'subscribe': print colorize(u"subscribe request from %s" % (who), 'blue') con.send(jabber.Presence(to=who, type='subscribed')) con.send(jabber.Presence(to=who, type='subscribe')) # unsubscription request: # - accept their unsubscription # - send request for unsubscription to their presence elif type == 'unsubscribe': print colorize(u"unsubscribe request from %s" % (who), 'blue') con.send(jabber.Presence(to=who, type='unsubscribed')) con.send(jabber.Presence(to=who, type='unsubscribe')) elif type == 'subscribed': print colorize(u"we are now subscribed to %s" % (who), 'blue') elif type == 'unsubscribed': print colorize(u"we are now unsubscribed to %s" % (who), 'blue') elif type == 'available': print colorize(u"%s is available (%s / %s)" % \ (who, prs.getShow(), prs.getStatus()),'blue') elif type == 'unavailable': print colorize(u"%s is unavailable (%s / %s)" % \ (who, prs.getShow(), prs.getStatus()),'blue') def iqCB(con,iq): """Called when an iq is recieved, we just let the library handle it at the moment""" pass def disconnectedCB(con): print colorize("Ouch, network error", 'red') sys.exit(1) def colorize(txt, col): """Return colorized text""" if not USE_COLOR: return txt ## DJ - just incase it breaks your terms ;) ## if type(txt)==type(u''): txt=txt.encode(jabber.xmlstream.ENCODING,'replace') cols = { 'red':1, 'green':2, 'yellow':3, 'blue':4} initcode = '\033[;3' endcode = '\033[0m' if type(col) == type(1): return initcode + str(col) + 'm' + txt + endcode try: return initcode + str(cols[col]) + 'm' + txt + endcode except: return txt if len(sys.argv) == 1: usage() Server = sys.argv[1] Username = '' Password = '' Resource = 'default' con = jabber.Client(host=Server,debug=jabber.DBG_ALWAYS ,log=sys.stderr) # Experimental SSL support # # con = jabber.Client(host=Server,debug=True ,log=sys.stderr, # port=5223, connection=xmlstream.TCP_SSL) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print colorize("Connected",'red') con.registerHandler('message',messageCB) con.registerHandler('presence',presenceCB) con.registerHandler('iq',iqCB) con.setDisconnectHandler(disconnectedCB) if len(sys.argv) == 2: # Set up a jabber account con.requestRegInfo() req = con.getRegInfo() print req[u'instructions'] for info in req.keys(): if info != u'instructions' and \ info != u'key': print "enter %s;" % info con.setRegInfo( info,strip(sys.stdin.readline()) ) con.sendRegInfo() req = con.getRegInfo() Username = req['username'] Password = req['password'] else: Username = sys.argv[2] Password = sys.argv[3] Resource = sys.argv[4] print colorize("Attempting to log in...", 'red') if con.auth(Username,Password,Resource): print colorize(u"Logged in as %s to server %s" % ( Username, Server), 'red') else: print "eek -> ", con.lastErr, con.lastErrCode sys.exit(1) print colorize("Requesting Roster Info" , 'red') con.requestRoster() con.sendInitPresence() print colorize("Ok, ready" , 'red') print colorize("Type /help for help", 'red') JID = Username + '@' + Server + '/' + Resource while(1): inputs, outputs, errors = select([sys.stdin], [], [],1) if sys.stdin in inputs: doCmd(con,sys.stdin.readline()) else: con.process(1) jabber.py-0.5.0.orig/jabber/0000755000175000017500000000000010007747554015743 5ustar kalfakalfa00000000000000jabber.py-0.5.0.orig/jabber/jabber.py0000644000175000017500000014467010007746547017557 0ustar kalfakalfa00000000000000## jabber.py ## ## Copyright (C) 2001 Matthew Allum ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation; either version 2, or (at your option) ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. ## """\ __intro__ jabber.py is a Python module for the jabber instant messaging protocol. jabber.py deals with the xml parsing and socket code, leaving the programmer to concentrate on developing quality jabber based applications with Python. The eventual aim is to produce a fully featured easy to use library for creating both jabber clients and servers. jabber.py requires at least python 2.0 and the XML expat parser module ( included in the standard Python distrubution ). It is developed on Linux but should run happily on over Unix's and win32. __Usage__ jabber.py basically subclasses the xmlstream classs and provides the processing of jabber protocol elements into object instances as well 'helper' functions for parts of the protocol such as authentication and roster management. An example of usage for a simple client would be ( only psuedo code !) <> Read documentation on jabber.org for the jabber protocol. <> Birth a jabber.Client object with your jabber servers host <> Define callback functions for the protocol elements you want to use and optionally a disconnection. <> Authenticate with the server via auth method, or register via the reg methods to get an account. <> Call requestRoster() and sendPresence() <> loop over process(). Send Iqs,messages and presences by birthing them via there respective clients , manipulating them and using the Client's send() method. <> Respond to incoming elements passed to your callback functions. <> Find bugs :) """ # $Id: jabber.py,v 1.58 2004/01/18 05:27:10 snakeru Exp $ import xmlstream import sha, time debug=xmlstream.debug VERSION = xmlstream.VERSION False = 0; True = 1; timeout = 300 DBG_INIT, DBG_ALWAYS = debug.DBG_INIT, debug.DBG_ALWAYS DBG_DISPATCH = 'jb-dispatch' ; debug.debug_flags.append( DBG_DISPATCH ) DBG_NODE = 'jb-node' ; debug.debug_flags.append( DBG_NODE) DBG_NODE_IQ = 'jb-node-iq' ; debug.debug_flags.append( DBG_NODE_IQ ) DBG_NODE_MESSAGE = 'jb-node-message' ; debug.debug_flags.append( DBG_NODE_MESSAGE ) DBG_NODE_PRESENCE = 'jb-node-pressence' ; debug.debug_flags.append( DBG_NODE_PRESENCE ) DBG_NODE_UNKNOWN = 'jb-node-unknown' ; debug.debug_flags.append( DBG_NODE_UNKNOWN ) # # JANA core namespaces # from http://www.jabber.org/jana/namespaces.php as of 2003-01-12 # "myname" means that namespace didnt have a name in the jabberd headers # NS_AGENT = "jabber:iq:agent" NS_AGENTS = "jabber:iq:agents" NS_AUTH = "jabber:iq:auth" NS_CLIENT = "jabber:client" NS_DELAY = "jabber:x:delay" NS_OOB = "jabber:iq:oob" NS_REGISTER = "jabber:iq:register" NS_ROSTER = "jabber:iq:roster" NS_XROSTER = "jabber:x:roster" # myname NS_SERVER = "jabber:server" NS_TIME = "jabber:iq:time" NS_VERSION = "jabber:iq:version" NS_COMP_ACCEPT = "jabber:component:accept" # myname NS_COMP_CONNECT = "jabber:component:connect" # myname # # JANA JEP namespaces, ordered by JEP # from http://www.jabber.org/jana/namespaces.php as of 2003-01-12 # all names by jaclu # _NS_PROTOCOL = "http://jabber.org/protocol" # base for other NS_PASS = "jabber:iq:pass" # JEP-0003 NS_XDATA = "jabber:x:data" # JEP-0004 NS_RPC = "jabber:iq:rpc" # JEP-0009 NS_BROWSE = "jabber:iq:browse" # JEP-0011 NS_LAST = "jabber:iq:last" #JEP-0012 NS_PRIVACY = "jabber:iq:privacy" # JEP-0016 NS_XEVENT = "jabber:x:event" # JEP-0022 NS_XEXPIRE = "jabber:x:expire" # JEP-0023 NS_XENCRYPTED = "jabber:x:encrypted" # JEP-0027 NS_XSIGNED = "jabber:x:signed" # JEP-0027 NS_P_MUC = _NS_PROTOCOL + "/muc" # JEP-0045 NS_VCARD = "vcard-temp" # JEP-0054 # # Non JANA aproved, ordered by JEP # all names by jaclu # _NS_P_DISCO = _NS_PROTOCOL + "/disco" # base for other NS_P_DISC_INFO = _NS_P_DISCO + "#info" # JEP-0030 NS_P_DISC_ITEMS = _NS_P_DISCO + "#items" # JEP-0030 NS_P_COMMANDS = _NS_PROTOCOL + "/commands" # JEP-0050 """ 2002-01-11 jaclu Defined in jabberd/lib/lib.h, but not JANA aproved and not used in jabber.py so commented out, should/could propably be removed... NS_ADMIN = "jabber:iq:admin" NS_AUTH_OK = "jabber:iq:auth:0k" NS_CONFERENCE = "jabber:iq:conference" NS_ENVELOPE = "jabber:x:envelope" NS_FILTER = "jabber:iq:filter" NS_GATEWAY = "jabber:iq:gateway" NS_OFFLINE = "jabber:x:offline" NS_PRIVATE = "jabber:iq:private" NS_SEARCH = "jabber:iq:search" NS_XDBGINSERT = "jabber:xdb:ginsert" NS_XDBNSLIST = "jabber:xdb:nslist" NS_XHTML = "http://www.w3.org/1999/xhtml" NS_XOOB = "jabber:x:oob" NS_COMP_EXECUTE = "jabber:component:execute" # myname """ ## Possible constants for Roster class .... hmmm ## RS_SUB_BOTH = 0 RS_SUB_FROM = 1 RS_SUB_TO = 2 RS_ASK_SUBSCRIBE = 1 RS_ASK_UNSUBSCRIBE = 0 RS_EXT_ONLINE = 2 RS_EXT_OFFLINE = 1 RS_EXT_PENDING = 0 ############################################################################# def ustr(what): """If sending object is already a unicode str, just return it, otherwise convert it using xmlstream.ENCODING""" if type(what) == type(u''): r = what else: try: r = what.__str__() except AttributeError: r = str(what) # make sure __str__() didnt return a unicode if type(r) <> type(u''): r = unicode(r,xmlstream.ENCODING,'replace') return r xmlstream.ustr = ustr class NodeProcessed(Exception): pass # currently only for Connection._expectedIqHandler class Connection(xmlstream.Client): """Forms the base for both Client and Component Classes""" def __init__(self, host, port, namespace, debug=[], log=False, connection=xmlstream.TCP, hostIP=None, proxy=None): xmlstream.Client.__init__(self, host, port, namespace, debug=debug, log=log, connection=connection, hostIP=hostIP, proxy=proxy) self.handlers={} self.registerProtocol('unknown', Protocol) self.registerProtocol('iq', Iq) self.registerProtocol('message', Message) self.registerProtocol('presence', Presence) self.registerHandler('iq',self._expectedIqHandler,system=True) self._expected = {} self._id = 0; self.lastErr = '' self.lastErrCode = 0 def setMessageHandler(self, func, type='', chainOutput=False): """Back compartibility method""" print "WARNING! setMessageHandler(...) method is obsolette, use registerHandler('message',...) instead." return self.registerHandler('message', func, type, chained=chainOutput) def setPresenceHandler(self, func, type='', chainOutput=False): """Back compartibility method""" print "WARNING! setPresenceHandler(...) method is obsolette, use registerHandler('presence',...) instead." return self.registerHandler('presence', func, type, chained=chainOutput) def setIqHandler(self, func, type='', ns=''): """Back compartibility method""" print "WARNING! setIqHandler(...) method is obsolette, use registerHandler('iq',...) instead." return self.registerHandler('iq', func, type, ns) def header(self): self.DEBUG("stream: sending initial header",DBG_INIT) str = u" \ " self.send(str) self.process(timeout) def send(self, what): """Sends a jabber protocol element (Node) to the server""" xmlstream.Client.write(self,ustr(what)) def _expectedIqHandler(self, conn, iq_obj): if iq_obj.getAttr('id') and \ self._expected.has_key(iq_obj.getAttr('id')): self._expected[iq_obj.getAttr('id')] = iq_obj raise NodeProcessed('No need for further Iq processing.') def dispatch(self,stanza): """Called internally when a 'protocol element' is received. Builds the relevant jabber.py object and dispatches it to a relevant function or callback.""" name=stanza.getName() if not self.handlers.has_key(name): self.DEBUG("whats a tag -> " + name,DBG_NODE_UNKNOWN) name='unknown' else: self.DEBUG("Got %s stanza"%name, DBG_NODE) stanza=self.handlers[name][type](node=stanza) typ=stanza.getType() if not typ: typ='' try: ns=stanza.getQuery() if not ns: ns='' except: ns='' self.DEBUG("dispatch called for: name->%s ns->%s"%(name,ns),DBG_DISPATCH) typns=typ+ns if not self.handlers[name].has_key(ns): ns='' if not self.handlers[name].has_key(typ): typ='' if not self.handlers[name].has_key(typns): typns='' chain=[] for key in ['default',typ,ns,typns]: # we will use all handlers: from very common to very particular if key: chain += self.handlers[name][key] output='' user=True for handler in chain: try: if user or handler['system']: if handler['chain']: output=handler['func'](self,stanza,output) else: handler['func'](self,stanza) except NodeProcessed: user=False def registerProtocol(self,tag_name,Proto): """Registers a protocol in protocol processing chain. You MUST register a protocol before you register any handler function for it. First parameter, that passed to this function is the tag name that belongs to all protocol elements. F.e.: message, presence, iq, xdb, ... Second parameter is the [ancestor of] Protocol class, which instance will built from the received node with call if received_packet.getName()==tag_name: stanza = Proto(node = received_packet) """ self.handlers[tag_name]={type:Proto, 'default':[]} def registerHandler(self,name,handler,type='',ns='',chained=False, makefirst=False, system=False): """Sets the callback func for processing incoming stanzas. Multiple callback functions can be set which are called in succession. Callback can optionally raise an NodeProcessed error to stop stanza from further processing. A type and namespace attributes can also be optionally passed so the callback is only called when a stanza of this type is received. Namespace attribute MUST be omitted if you registering an Iq processing handler. If 'chainOutput' is set to False (the default), the given function should be defined as follows: def myCallback(c, p) Where the first parameter is the Client object, and the second parameter is the [ancestor of] Protocol object representing the stanza which was received. If 'chainOutput' is set to True, the output from the various handler functions will be chained together. In this case, the given callback function should be defined like this: def myCallback(c, p, output) Where 'output' is the value returned by the previous callback function. For the first callback routine, 'output' will be set to an empty string. 'makefirst' argument gives you control over handler prioriy in its type and namespace scope. Note that handlers for particular type or namespace always have lower priority that common handlers. """ if not type and not ns: type='default' if not self.handlers[name].has_key(type+ns): self.handlers[name][type+ns]=[] if makefirst: self.handlers[name][type+ns].insert({'chain':chained,'func':handler,'system':system}) else: self.handlers[name][type+ns].append({'chain':chained,'func':handler,'system':system}) def setDisconnectHandler(self, func): """Set the callback for a disconnect. The given function will be called with a single parameter (the connection object) when the connection is broken unexpectedly (eg, in response to sending badly formed XML). self.lastErr and self.lastErrCode will be set to the error which caused the disconnection, if any. """ self.disconnectHandler = func ## functions for sending element with ID's ## def waitForResponse(self, ID, timeout=timeout): """Blocks untils a protocol element with the given id is received. If an error is received, waitForResponse returns None and self.lastErr and self.lastErrCode is set to the received error. If the operation times out (which only happens if a timeout value is given), waitForResponse will return None and self.lastErr will be set to "Timeout". Changed default from timeout=0 to timeout=300 to avoid hangs in scripts and such. If you _really_ want no timeout, just set it to 0""" ID = ustr(ID) self._expected[ID] = None has_timed_out = False abort_time = time.time() + timeout if timeout: self.DEBUG("waiting with timeout:%s for %s" % (timeout,ustr(ID)),DBG_NODE_IQ) else: self.DEBUG("waiting for %s" % ustr(ID),DBG_NODE_IQ) while (not self._expected[ID]) and not has_timed_out: if not self.process(0.2): return None if timeout and (time.time() > abort_time): has_timed_out = True if has_timed_out: self.lastErr = "Timeout" return None response = self._expected[ID] del self._expected[ID] if response.getErrorCode(): self.lastErr = response.getError() self.lastErrCode = response.getErrorCode() return None return response def SendAndWaitForResponse(self, obj, ID=None, timeout=timeout): """Sends a protocol element object and blocks until a response with the same ID is received. The received protocol object is returned as the function result. """ if ID is None : ID = obj.getID() if ID is None: ID = self.getAnID() obj.setID(ID) ID = ustr(ID) self.send(obj) return self.waitForResponse(ID,timeout) def getAnID(self): """Returns a unique ID""" self._id = self._id + 1 return ustr(self._id) ############################################################################# class Client(Connection): """Class for managing a client connection to a jabber server.""" def __init__(self, host, port=5222, debug=[], log=False, connection=xmlstream.TCP, hostIP=None, proxy=None): Connection.__init__(self, host, port, NS_CLIENT, debug, log, connection=connection, hostIP=hostIP, proxy=proxy) self.registerHandler('iq',self._IqRosterManage,'result',NS_ROSTER,system=True) self.registerHandler('iq',self._IqRosterManage,'set',NS_ROSTER,system=True) self.registerHandler('iq',self._IqRegisterResult,'result',NS_REGISTER,system=True) self.registerHandler('iq',self._IqAgentsResult,'result',NS_AGENTS,system=True) self.registerHandler('presence',self._presenceHandler,system=True) self._roster = Roster() self._agents = {} self._reg_info = {} self._reg_agent = '' def disconnect(self): """Safely disconnects from the connected server""" self.send(Presence(type='unavailable')) xmlstream.Client.disconnect(self) def sendPresence(self,type=None,priority=None,show=None,status=None): """Sends a presence protocol element to the server. Used to inform the server that you are online""" self.send(Presence(type=type,priority=priority,show=show,status=status)) sendInitPresence=sendPresence def _presenceHandler(self, conn, pres_obj): who = ustr(pres_obj.getFrom()) type = pres_obj.getType() self.DEBUG("presence type is %s" % type,DBG_NODE_PRESENCE) if type == 'available' or not type: self.DEBUG("roster setting %s to online" % who,DBG_NODE_PRESENCE) self._roster._setOnline(who,'online') elif type == 'unavailable': self.DEBUG("roster setting %s to offline" % who,DBG_NODE_PRESENCE) self._roster._setOnline(who,'offline') self._roster._setShow(who,pres_obj.getShow()) self._roster._setStatus(who,pres_obj.getStatus()) def _IqRosterManage(self, conn, iq_obj): "NS_ROSTER and type in [result,set]" for item in iq_obj.getQueryNode().getChildren(): jid = item.getAttr('jid') name = item.getAttr('name') sub = item.getAttr('subscription') ask = item.getAttr('ask') groups = [] for group in item.getTags("group"): groups.append(group.getData()) if jid: if sub == 'remove' or sub == 'none': self._roster._remove(jid) else: self._roster._set(jid=jid, name=name, groups=groups, sub=sub, ask=ask) else: self.DEBUG("roster - jid not defined ?",DBG_NODE_IQ) def _IqRegisterResult(self, conn, iq_obj): "NS_REGISTER and type==result" self._reg_info = {} for item in iq_obj.getQueryNode().getChildren(): self._reg_info[item.getName()] = item.getData() def _IqAgentsResult(self, conn, iq_obj): "NS_AGENTS and type==result" self.DEBUG("got agents result",DBG_NODE_IQ) self._agents = {} for agent in iq_obj.getQueryNode().getChildren(): if agent.getName() == 'agent': ## hmmm self._agents[agent.getAttr('jid')] = {} for info in agent.getChildren(): self._agents[agent.getAttr('jid')][info.getName()] = info.getData() def auth(self,username,passwd,resource): """Authenticates and logs in to the specified jabber server Automatically selects the 'best' authentication method provided by the server. Supports plain text, digest and zero-k authentication. Returns True if the login was successful, False otherwise. """ auth_get_iq = Iq(type='get') auth_get_iq.setID('auth-get') q = auth_get_iq.setQuery(NS_AUTH) q.insertTag('username').insertData(username) self.send(auth_get_iq) auth_response = self.waitForResponse("auth-get") if auth_response == None: return False # Error else: auth_ret_node = auth_response auth_ret_query = auth_ret_node.getTag('query') self.DEBUG("auth-get node arrived!",(DBG_INIT,DBG_NODE_IQ)) auth_set_iq = Iq(type='set') auth_set_iq.setID('auth-set') q = auth_set_iq.setQuery(NS_AUTH) q.insertTag('username').insertData(username) q.insertTag('resource').insertData(resource) if auth_ret_query.getTag('token'): token = auth_ret_query.getTag('token').getData() seq = auth_ret_query.getTag('sequence').getData() self.DEBUG("zero-k authentication supported",(DBG_INIT,DBG_NODE_IQ)) hash = sha.new(sha.new(passwd).hexdigest()+token).hexdigest() for foo in xrange(int(seq)): hash = sha.new(hash).hexdigest() q.insertTag('hash').insertData(hash) elif auth_ret_query.getTag('digest'): self.DEBUG("digest authentication supported",(DBG_INIT,DBG_NODE_IQ)) digest = q.insertTag('digest') digest.insertData(sha.new( self.getIncomingID() + passwd).hexdigest() ) else: self.DEBUG("plain text authentication supported",(DBG_INIT,DBG_NODE_IQ)) q.insertTag('password').insertData(passwd) iq_result = self.SendAndWaitForResponse(auth_set_iq) if iq_result==None: return False if iq_result.getError() is None: return True else: self.lastErr = iq_result.getError() self.lastErrCode = iq_result.getErrorCode() # raise error(iq_result.getError()) ? return False return True ## Roster 'helper' func's - also see the Roster class ## def requestRoster(self): """Requests the roster from the server and returns a Roster() class instance.""" rost_iq = Iq(type='get') rost_iq.setQuery(NS_ROSTER) self.SendAndWaitForResponse(rost_iq) self.DEBUG("got roster response",DBG_NODE_IQ) self.DEBUG("roster -> %s" % ustr(self._roster),DBG_NODE_IQ) return self._roster def getRoster(self): """Returns the current Roster() class instance. Does not contact the server.""" return self._roster def addRosterItem(self, jid): """ Send off a request to subscribe to the given jid. """ self.send(Presence(to=jid, type="subscribe")) def updateRosterItem(self, jid, name=None, groups=None): """ Update the information stored in the roster about a roster item. 'jid' is the Jabber ID of the roster entry; 'name' is the value to set the entry's name to, and 'groups' is a list of groups to which this roster entry can belong. If either 'name' or 'groups' is not specified, that value is not updated in the roster. """ iq = Iq(type='set') item = iq.setQuery(NS_ROSTER).insertTag('item') item.putAttr('jid', ustr(jid)) if name != None: item.putAttr('name', name) if groups != None: for group in groups: item.insertTag('group').insertData(group) dummy = self.SendAndWaitForResponse(iq) # Do we need to wait?? def removeRosterItem(self,jid): """Removes an item with Jabber ID jid from both the server's roster and the local internal Roster() instance""" rost_iq = Iq(type='set') q = rost_iq.setQuery(NS_ROSTER).insertTag('item') q.putAttr('jid', ustr(jid)) q.putAttr('subscription', 'remove') self.SendAndWaitForResponse(rost_iq) return self._roster ## Registration 'helper' funcs ## def requestRegInfo(self,agent=''): """Requests registration info from the server. Returns the Iq object received from the server.""" if agent: agent = agent + '.' self._reg_info = {} reg_iq = Iq(type='get', to = agent + self._host) reg_iq.setQuery(NS_REGISTER) self.DEBUG("Requesting reg info from %s%s:" % (agent, self._host), DBG_NODE_IQ) self.DEBUG(ustr(reg_iq),DBG_NODE_IQ) return self.SendAndWaitForResponse(reg_iq) def getRegInfo(self): """Returns a dictionary of fields requested by the server for a registration attempt. Each dictionary entry maps from the name of the field to the field's current value (either as returned by the server or set programmatically by calling self.setRegInfo(). """ return self._reg_info def setRegInfo(self,key,val): """Sets a name/value attribute. Note: requestRegInfo must be called before setting.""" self._reg_info[key] = val def sendRegInfo(self, agent=None): """Sends the populated registration dictionary back to the server""" if agent: agent = agent + '.' if agent is None: agent = '' reg_iq = Iq(to = agent + self._host, type='set') q = reg_iq.setQuery(NS_REGISTER) for info in self._reg_info.keys(): q.insertTag(info).putData(self._reg_info[info]) return self.SendAndWaitForResponse(reg_iq) def deregister(self, agent=None): """ Send off a request to deregister with the server or with the given agent. Returns True if successful, else False. Note that you must be authorised before attempting to deregister. """ if agent: agent = agent + '.' self.send(Presence(to=agent+self._host,type='unsubscribed')) # This is enough f.e. for icqv7t or jit if agent is None: agent = '' q = self.requestRegInfo() kids = q.getQueryPayload() keyTag = kids.getTag("key") iq = Iq(to=agent+self._host, type="set") iq.setQuery(NS_REGISTER) iq.setQueryNode("") q = iq.getQueryNode() if keyTag != None: q.insertXML("" + keyTag.getData() + "") q.insertXML("") result = self.SendAndWaitForResponse(iq) if result == None: return False elif result.getType() == "result": return True else: return False ## Agent helper funcs ## def requestAgents(self): """Requests a list of available agents. Returns a dictionary containing information about each agent; each entry in the dictionary maps the agent's JID to a dictionary of attributes describing what that agent can do (as returned by the NS_AGENTS query).""" self._agents = {} agents_iq = Iq(type='get') agents_iq.setQuery(NS_AGENTS) self.SendAndWaitForResponse(agents_iq) self.DEBUG("agents -> %s" % ustr(self._agents),DBG_NODE_IQ) return self._agents def _discover(self,ns,jid,node=None): iq=Iq(to=jid,type='get',query=ns) if node: iq.putAttr('node',node) rep=self.SendAndWaitForResponse(iq) if rep: return rep.getQueryPayload() def discoverItems(self,jid,node=None): """ According to JEP-0030: jid is mandatory, name, node, action is optional. """ ret=[] for i in self._discover(NS_P_DISC_ITEMS,jid,node): ret.append(i.attrs) return ret def discoverInfo(self,jid,node=None): """ According to JEP-0030: For identity: category, name is mandatory, type is optional. For feature: var is mandatory""" identities , features = [] , [] for i in self._discover(NS_P_DISC_INFO,jid,node): if i.getName()=='identity': identities.append(i.attrs) elif i.getName()=='feature': features.append(i.getAttr('var')) return identities , features ############################################################################# class Protocol(xmlstream.Node): """Base class for jabber 'protocol elements' - messages, presences and iqs. Implements methods that are common to all these""" def __init__(self, name=None, to=None, type=None, attrs=None, frm=None, payload=[], node=None): if not attrs: attrs={} if to: attrs['to']=to if frm: attrs['from']=frm if type: attrs['type']=type self._node=self xmlstream.Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node) def asNode(self): """Back compartibility method""" print 'WARNING! "asNode()" method is obsolette, use Protocol object as Node object instead.' return self def getError(self): """Returns the error string, if any""" try: return self.getTag('error').getData() except: return None def getErrorCode(self): """Returns the error code, if any""" try: return self.getTag('error').getAttr('code') except: return None def setError(self,val,code): """Sets an error string and code""" err = self.getTag('error') if not err: err = self.insertTag('error') err.putData(val) err.putAttr('code',str(code)) def __repr__(self): return self.__str__() def getTo(self): """Returns the 'to' attribute as a JID object.""" try: return JID(self.getAttr('to')) except: return None def getFrom(self): """Returns the 'from' attribute as a JID object.""" try: return JID(self.getAttr('from')) except: return None def getType(self): """Returns the 'type' attribute of the protocol element.""" try: return self.getAttr('type') except: return None def getID(self): """Returns the 'id' attribute of the protocol element.""" try: return self.getAttr('id') except: return None def setTo(self,val): """Sets the 'to' element to the given JID.""" self.putAttr('to', ustr(val)) def setFrom(self,val): """Sets the 'from' element to the given JID.""" self.putAttr('from', ustr(val)) def setType(self,val): """Sets the 'type' attribute of the protocol element""" self.putAttr('type', val) def setID(self,val): """Sets the ID of the protocol element""" self.putAttr('id', val) def getX(self,index=0): """Returns the x namespace, optionally passed an index if there are multiple tags.""" try: return self.getXNodes()[index].namespace except: return None def setX(self,namespace,index=0): """Sets the name space of the x tag. It also creates the node if it doesn't already exist.""" x = self.getTag('x',index) if not x: x = self.insertTag('x') x.setNamespace(namespace) return x def setXPayload(self, payload, namespace=''): """Sets the Child of an 'x' tag. Can be a Node instance or an XML document""" x = self.setX(namespace) if type(payload) == type('') or type(payload) == type(u''): payload = xmlstream.NodeBuilder(payload).getDom() x.kids = [] # should be a method for this realy x.insertNode(payload) def getXPayload(self, val=None): """Returns the x tags' payload as a list of Node instances.""" nodes = [] if val is not None: if type(val) == type(""): for xnode in self.getTags('x'): if xnode.getNamespace() == val: nodes.append(xnode.kids[0]) return nodes else: try: return self.getTags('x')[val].kids[0] except: return None for xnode in self.getTags('x'): nodes.append(xnode.kids[0]) return nodes def getXNode(self, val=None): """Returns the x Node instance. If there are multiple tags the first Node is returned. For multiple X nodes use getXNodes or pass an index integer value or namespace string to getXNode and if a match is found it will be returned.""" if val is not None: nodes = [] if type(val) == type(""): for xnode in self.getTags('x'): if xnode.getNamespace() == val: nodes.append(xnode) return nodes else: try: return self.getTags('x')[val] except: return None else: try: return self.getTag('x') except: return None def getXNodes(self): """Returns a list of X nodes.""" return self.getTags('x') def setXNode(self, val=''): """Sets the x tag's data to the given textual value.""" self.insertTag('x').putData(val) def fromTo(self): """Swaps the element's from and to attributes. Note that this is only useful for writing components; if you are writing a Jabber client you shouldn't use this, because the Jabber server will set the 'from' field automatically.""" tmp = self.getTo() self.setTo(self.getFrom()) self.setFrom(tmp) ############################################################################# class Message(Protocol): """Builds on the Protocol class to provide an interface for sending message protocol elements""" def __init__(self, to=None, body=None, type=None, subject=None, attrs=None, frm=None, payload=[], node=None): Protocol.__init__(self, 'message', to=to, type=type, attrs=attrs, frm=frm, payload=payload, node=node) if body: self.setBody(body) if subject: self.setSubject(subject) # examine x tag and set timestamp if pressent try: self.setTimestamp( self.getTag('x').getAttr('stamp') ) except: self.setTimestamp() def getBody(self): """Returns the message body.""" try: return self.getTag('body').getData() except: return None def getSubject(self): """Returns the message's subject.""" try: return self.getTag('subject').getData() except: return None def getThread(self): """Returns the message's thread ID.""" try: return self.getTag('thread').getData() except: return None def getTimestamp(self): return self.time_stamp def setBody(self,val): """Sets the message body text.""" body = self.getTag('body') if body: body.putData(val) else: body = self.insertTag('body').putData(val) def setSubject(self,val): """Sets the message subject text.""" subj = self.getTag('subject') if subj: subj.putData(val) else: self.insertTag('subject').putData(val) def setThread(self,val): """Sets the message thread ID.""" thread = self.getTag('thread') if thread: thread.putData(val) else: self.insertTag('thread').putData(val) def setTimestamp(self,val=None): if not val: val = time.strftime( '%Y%m%dT%H:%M:%S', time.gmtime( time.time())) self.time_stamp = val def buildReply(self, reply_txt=''): """Returns a new Message object as a reply to itself. The reply message has the 'to', 'type' and 'thread' attributes automatically set.""" m = Message(to=self.getFrom(), body=reply_txt) if not self.getType() == None: m.setType(self.getType()) t = self.getThread() if t: m.setThread(t) return m def build_reply(self, reply_txt=''): print "WARNING: build_reply method is obsolette. Use buildReply instead." return self.buildReply(reply_txt) ############################################################################# class Presence(Protocol): """Class for creating and managing jabber protocol elements""" def __init__(self, to=None, type=None, priority=None, show=None, status=None, attrs=None, frm=None, payload=[], node=None): Protocol.__init__(self, 'presence', to=to, type=type, attrs=attrs, frm=frm, payload=payload, node=node) if priority: self.setPriority(priority) if show: self.setShow(show) if status: self.setStatus(status) def getStatus(self): """Returns the presence status""" try: return self.getTag('status').getData() except: return None def getShow(self): """Returns the presence show""" try: return self.getTag('show').getData() except: return None def getPriority(self): """Returns the presence priority""" try: return self.getTag('priority').getData() except: return None def setShow(self,val): """Sets the presence show""" show = self.getTag('show') if show: show.putData(val) else: self.insertTag('show').putData(val) def setStatus(self,val): """Sets the presence status""" status = self.getTag('status') if status: status.putData(val) else: self.insertTag('status').putData(val) def setPriority(self,val): """Sets the presence priority""" pri = self.getTag('priority') if pri: pri.putData(val) else: self.insertTag('priority').putData(val) ############################################################################# class Iq(Protocol): """Class for creating and managing jabber protocol elements""" def __init__(self, to=None, type=None, query=None, attrs=None, frm=None, payload=[], node=None): Protocol.__init__(self, 'iq', to=to, type=type, attrs=attrs, frm=frm, payload=payload, node=node) if query: self.setQuery(query) def _getTag(self,tag): try: return self.getTag(tag).namespace except: return None def _setTag(self,tag,namespace): q = self.getTag(tag) if q: q.namespace = namespace else: q = self.insertTag(tag) q.setNamespace(namespace) return q def getList(self): "returns the list namespace" return self._getTag('list') def setList(self,namespace): return self._setTag('list',namespace) def getQuery(self): "returns the query namespace" return self._getTag('query') def setQuery(self,namespace): """Sets a query's namespace, and inserts a query tag if one doesn't already exist. The resulting query tag is returned as the function result.""" return self._setTag('query',namespace) def setQueryPayload(self, payload, add=False): """Sets a Iq's query payload. 'payload' can be either a Node structure or a valid xml document. The query tag is automatically inserted if it doesn't already exist.""" q = self.getQueryNode() if q is None: q = self.insertTag('query') if type(payload) == type('') or type(payload) == type(u''): payload = xmlstream.NodeBuilder(payload).getDom() if not add: q.kids = [] q.insertNode(payload) def getQueryPayload(self): """Returns the query's payload as a Node list""" q = self.getQueryNode() if q: return q.kids def getQueryNode(self): """Returns any textual data contained by the query tag""" try: return self.getTag('query') except: return None def setQueryNode(self, val): """Sets textual data contained by the query tag""" q = self.getTag('query') if q: q.putData(val) else: self.insertTag('query').putData(val) ############################################################################# class Roster: """A Class for simplifying roster management. Also tracks roster item availability.""" def __init__(self): self._data = {} self._listener = None ## unused for now ... ## self._lut = { 'both':RS_SUB_BOTH, 'from':RS_SUB_FROM, 'to':RS_SUB_TO } def setListener(self, listener): """ Set a listener function to be called whenever the roster changes. The given function will be called whenever the contents of the roster changes in response to a received or packet. The listener function should be defined as follows: def listener(action, jid, info) 'action' is a string indicating what type of change has occurred: "add" A new item has been added to the roster. "update" An existing roster item has been updated. "remove" A roster entry has been removed. 'jid' is the Jabber ID (as a string) of the affected roster entry. 'info' is a dictionary containing the information that has been added or updated for this roster entry. This dictionary may contain any combination of the following: "name" The associated name of this roster entry. "groups" A list of groups associated with this roster entry. "online" The roster entry's "online" value ("online", "offline" or "pending"). "sub" The roster entry's subscription value ("none", "from", "to" or "both"). "ask" The roster entry's ask value, if any (None, "subscribe", "unsubscribe"). "show" The roster entry's show value, if any (None, "away", "chat", "dnd", "normal", "xa"). "status" The roster entry's current 'status' value, if specified. """ self._listener = listener def getStatus(self, jid): ## extended """Returns the 'status' value for a Roster item with the given jid.""" jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['status'] return None def getShow(self, jid): ## extended """Returns the 'show' value for a Roster item with the given jid.""" jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['show'] return None def getOnline(self,jid): ## extended """Returns the 'online' status for a Roster item with the given jid. """ jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['online'] return None def getSub(self,jid): """Returns the 'subscription' status for a Roster item with the given jid.""" jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['sub'] return None def getName(self,jid): """Returns the 'name' for a Roster item with the given jid.""" jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['name'] return None def getGroups(self,jid): """ Returns the lsit of groups associated with the given roster item. """ jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['groups'] return None def getAsk(self,jid): """Returns the 'ask' status for a Roster item with the given jid.""" jid = ustr(jid) if self._data.has_key(jid): return self._data[jid]['ask'] return None def getSummary(self): """Returns a summary of the roster's contents. The returned value is a dictionary mapping the basic (no resource) JIDs to their current availability status (online, offline, pending). """ to_ret = {} for jid in self._data.keys(): to_ret[jid] = self._data[jid]['online'] return to_ret def getJIDs(self): """Returns a list of JIDs stored within the roster. Each entry in the list is a JID object.""" to_ret = []; for jid in self._data.keys(): to_ret.append(JID(jid)) return to_ret def getRaw(self): """Returns the internal data representation of the roster.""" return self._data def isOnline(self,jid): """Returns True if the given jid is online, False if not.""" jid = ustr(jid) if self.getOnline(jid) != 'online': return False else: return True def _set(self,jid,name,groups,sub,ask): # meant to be called by actual iq tag """Used internally - private""" jid = ustr(jid) # just in case online = 'offline' if ask: online = 'pending' if self._data.has_key(jid): # update it self._data[jid]['name'] = name self._data[jid]['groups'] = groups self._data[jid]['ask'] = ask self._data[jid]['sub'] = sub if self._listener != None: self._listener("update", jid, {'name' : name, 'groups' : groups, 'sub' : sub, 'ask' : ask}) else: self._data[jid] = { 'name': name, 'groups' : groups, 'ask': ask, 'sub': sub, 'online': online, 'status': None, 'show': None} if self._listener != None: self._listener("add", jid, {'name' : name, 'groups' : groups, 'sub' : sub, 'ask' : ask, 'online' : online}) def _setOnline(self,jid,val): """Used internally - private""" jid = ustr(jid) if self._data.has_key(jid): self._data[jid]['online'] = val if self._listener != None: self._listener("update", jid, {'online' : val}) else: ## fall back jid_basic = JID(jid).getStripped() if self._data.has_key(jid_basic): self._data[jid_basic]['online'] = val if self._listener != None: self._listener("update", jid_basic, {'online' : val}) def _setShow(self,jid,val): """Used internally - private""" jid = ustr(jid) if self._data.has_key(jid): self._data[jid]['show'] = val if self._listener != None: self._listener("update", jid, {'show' : val}) else: ## fall back jid_basic = JID(jid).getStripped() if self._data.has_key(jid_basic): self._data[jid_basic]['show'] = val if self._listener != None: self._listener("update", jid_basic, {'show' : val}) def _setStatus(self,jid,val): """Used internally - private""" jid = ustr(jid) if self._data.has_key(jid): self._data[jid]['status'] = val if self._listener != None: self._listener("update", jid, {'status' : val}) else: ## fall back jid_basic = JID(jid).getStripped() if self._data.has_key(jid_basic): self._data[jid_basic]['status'] = val if self._listener != None: self._listener("update", jid_basic, {'status' : val}) def _remove(self,jid): """Used internally - private""" if self._data.has_key(jid): del self._data[jid] if self._listener != None: self._listener("remove", jid, {}) ############################################################################# class JID: """A Simple class for managing jabber users id's """ def __init__(self, jid='', node='', domain='', resource=''): if jid: if jid.find('@') == -1: self.node = '' else: bits = jid.split('@', 1) self.node = bits[0] jid = bits[1] if jid.find('/') == -1: self.domain = jid self.resource = '' else: self.domain, self.resource = jid.split('/', 1) else: self.node = node self.domain = domain self.resource = resource def __str__(self): jid_str = self.domain if self.node: jid_str = self.node + '@' + jid_str if self.resource: jid_str += '/' + self.resource return jid_str __repr__ = __str__ def getNode(self): """Returns JID Node as string""" return self.node def getDomain(self): """Returns JID domain as string or None if absent""" return self.domain def getResource(self): """Returns JID resource as string or None if absent""" return self.resource def setNode(self,val): """Sets JID Node from string""" self.node = val def setDomain(self,val): """Sets JID domain from string""" self.domain = val def setResource(self,val): """Sets JID resource from string""" self.resource = val def getStripped(self): """Returns a JID string with no resource""" if self.node: return self.node + '@' + self.domain else: return self.domain def __eq__(self, other): """Returns whether this JID is identical to another one. The "other" can be a JID object or a string.""" return str(self) == str(other) ############################################################################# ## component types ## Accept NS_COMP_ACCEPT ## Connect NS_COMP_CONNECT ## Execute NS_COMP_EXECUTE class Component(Connection): """docs to come soon... """ def __init__(self, host, port, connection=xmlstream.TCP, debug=[], log=False, ns=NS_COMP_ACCEPT, hostIP=None, proxy=None): Connection.__init__(self, host, port, namespace=ns, debug=debug, log=log, connection=connection, hostIP=hostIP, proxy=proxy) self._auth_OK = False self.registerProtocol('xdb', XDB) def auth(self,secret): """will disconnect on failure""" self.send( u"%s" % sha.new( self.getIncomingID() + secret ).hexdigest() ) while not self._auth_OK: self.DEBUG("waiting on handshake") self.process(1) return True def dispatch(self, root_node): """Catch the here""" if root_node.name == 'handshake': # check id too ? self._auth_OK = True Connection.dispatch(self, root_node) ############################################################################# ## component protocol elements class XDB(Protocol): def __init__(self, attrs=None, type=None, frm=None, to=None, payload=[], node=None): Protocol.__init__(self, 'xdb', attrs=attrs, type=type, frm=frm, to=to, payload=payload, node=node) ############################################################################# class Log(Protocol): ## eg: Hello Log File def __init__(self, attrs=None, type=None, frm=None, to=None, payload=[], node=None): Protocol.__init__(self, 'log', attrs=attrs, type=type, frm=frm, to=to, payload=payload, node=node) def setBody(self,val): "Sets the log message text." self.getTag('log').putData(val) def getBody(self): "Returns the log message text." return self.getTag('log').getData() ############################################################################# class Server: pass jabber.py-0.5.0.orig/jabber/debug.py0000644000175000017500000003227707765343255017425 0ustar kalfakalfa00000000000000## debug.py ## ## Copyright (C) 2003 Jacob Lundqvist ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation; either version 2, or (at your option) ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. _version_ = '1.4.0' """\ Generic debug class Other modules can always define extra debug flags for local usage, as long as they make sure they append them to debug_flags Also its always a good thing to prefix local flags with something, to reduce risk of coliding flags. Nothing breaks if two flags would be identical, but it might activate unintended debugging. flags can be numeric, but that makes analysing harder, on creation its not obvious what is activated, and when flag_show is given, output isnt really meaningfull. This Debug class can either be initialized and used on app level, or used independantly by the individual classes. For samples of usage, see samples subdir in distro source, and selftest in this code """ import sys import time from string import join import types debug_flags = [] color_none = chr(27) + "[0m" color_black = chr(27) + "[30m" color_red = chr(27) + "[31m" color_green = chr(27) + "[32m" color_brown = chr(27) + "[33m" color_blue = chr(27) + "[34m" color_magenta = chr(27) + "[35m" color_cyan = chr(27) + "[36m" color_light_gray = chr(27) + "[37m" color_dark_gray = chr(27) + "[30;1m" color_bright_red = chr(27) + "[31;1m" color_bright_green = chr(27) + "[32;1m" color_yellow = chr(27) + "[33;1m" color_bright_blue = chr(27) + "[34;1m" color_purple = chr(27) + "[35;1m" color_bright_cyan = chr(27) + "[36;1m" color_white = chr(27) + "[37;1m" """ Define your flags in yor modules like this: from debug import * DBG_INIT = 'init' ; debug_flags.append( DBG_INIT ) DBG_CONNECTION = 'connection' ; debug_flags.append( DBG_CONNECTION ) The reason for having a double statement wis so we can validate params and catch all undefined debug flags This gives us control over all used flags, and makes it easier to allow global debugging in your code, just do something like foo = Debug( debug_flags ) group flags, that is a flag in it self containing multiple flags should be defined without the debug_flags.append() sequence, since the parts are already in the list, also they must of course be defined after the flags they depend on ;) example: DBG_MULTI = [ DBG_INIT, DBG_CONNECTION ] NoDebug ------- To speed code up, typically for product releases or such use this class instead if you globaly want to disable debugging """ DBG_INIT = 'init' ; debug_flags.append( DBG_INIT ) DBG_ALWAYS = 'always' ; debug_flags.append( DBG_ALWAYS ) class NoDebug: def __init__( self, *args, **kwargs ): pass def show( self, *args, **kwargs): pass def is_active( self, flag ): pass def active_set( self, active_flags = None ): return 0 LINE_FEED = '\n' class Debug: def __init__( self, # # active_flags are those that will trigger output # active_flags = None, # # Log file should be file object or file namne # log_file = sys.stderr, # # prefix and sufix can either be set globaly or per call. # personally I use this to color code debug statements # with prefix = chr(27) + '[34m' # sufix = chr(27) + '[37;1m\n' # prefix = 'DEBUG: ', sufix = '\n', # # If you want unix style timestamps, # 0 disables timestamps # 1 before prefix, good when prefix is a string # 2 after prefix, good when prefix is a color # time_stamp = 0, # # flag_show should normaly be of, but can be turned on to get a # good view of what flags are actually used for calls, # if it is not None, it should be a string # flags for current call will be displayed # with flag_show as separator # recomended values vould be '-' or ':', but any string goes # flag_show = None, # # If you dont want to validate flags on each call to # show(), set this to 0 # validate_flags = 1, # # If you dont want the welcome message, set to 0 # default is to show welcome if any flags are active welcome = -1, # # Non plain-ascii encodings can benefit from it encoding = None ): if type(active_flags) not in [type([]), type(())]: print '***' print '*** Invalid or oldformat debug param given: %s' % active_flags print '*** please correct your param, should be of [] type!' print '*** Due to this, full debuging is enabled' active_flags=[DBG_ALWAYS] if welcome == -1: if active_flags and len(active_flags): welcome = 1 else: welcome = 0 self._remove_dupe_flags() if log_file: if type( log_file ) is type(''): try: self._fh = open(log_file,'w') except: print 'ERROR: can open %s for writing' sys.exit(0) else: ## assume its a stream type object self._fh = log_file else: self._fh = sys.stdout if time_stamp not in (0,1,2): msg2 = '%s' % time_stamp raise 'Invalid time_stamp param', msg2 self.prefix = prefix self.sufix = sufix self.time_stamp = time_stamp self.flag_show = None # must be initialised after possible welcome self.validate_flags = validate_flags self.encoding = encoding self.active_set( active_flags ) if welcome: self.show('') caller = sys._getframe(1) # used to get name of caller try: mod_name= ":%s" % caller.f_locals['__name__'] except: mod_name = "" self.show('Debug created for %s%s' % (caller.f_code.co_filename, mod_name )) self.show(' flags defined: %s' % join( self.active )) if type(flag_show) in (type(''), type(None)): self.flag_show = flag_show else: msg2 = '%s' % type(flag_show ) raise 'Invalid type for flag_show!', msg2 def show( self, msg, flag = None, prefix = None, sufix = None, lf = 0 ): """ flag can be of folowing types: None - this msg will always be shown if any debugging is on flag - will be shown if flag is active (flag1,flag2,,,) - will be shown if any of the given flags are active if prefix / sufix are not given, default ones from init will be used lf = -1 means strip linefeed if pressent lf = 1 means add linefeed if not pressent """ if self.validate_flags: self._validate_flag( flag ) if not self.is_active(flag): return if prefix: pre = prefix else: pre = self.prefix if sufix: suf = sufix else: suf = self.sufix if self.time_stamp == 2: output = '%s%s ' % ( pre, time.strftime('%b %d %H:%M:%S', time.localtime(time.time() )), ) elif self.time_stamp == 1: output = '%s %s' % ( time.strftime('%b %d %H:%M:%S', time.localtime(time.time() )), pre, ) else: output = pre if self.flag_show: if flag: output = '%s%s%s' % ( output, flag, self.flag_show ) else: # this call uses the global default, # dont print "None", just show the separator output = '%s %s' % ( output, self.flag_show ) if type(msg)==type(u'') and self.encoding: msg=msg.encode(self.encoding, 'replace') output = '%s%s%s' % ( output, msg, suf ) if lf: # strip/add lf if needed last_char = output[-1] if lf == 1 and last_char != LINE_FEED: output = output + LINE_FEED elif lf == -1 and last_char == LINE_FEED: output = output[:-1] try: self._fh.write( output ) except: # unicode strikes again ;) s=u'' for i in range(len(output)): if ord(output[i]) < 128: c = output[i] else: c = '?' s=s+c self._fh.write( '%s%s%s' % ( pre, s, suf )) self._fh.flush() def is_active( self, flag ): 'If given flag(s) should generate output.' # try to abort early to quicken code if not self.active: return 0 if not flag or flag in self.active or DBG_ALWAYS in self.active: return 1 else: # check for multi flag type: if type( flag ) in ( type(()), type([]) ): for s in flag: if s in self.active: return 1 return 0 def active_set( self, active_flags = None ): "returns 1 if any flags where actually set, otherwise 0." r = 0 ok_flags = [] if not active_flags: #no debuging at all self.active = [] elif type( active_flags ) in ( types.TupleType, types.ListType ): flags = self._as_one_list( active_flags ) for t in flags: if t not in debug_flags: print 'Invalid debugflag given', t else: ok_flags.append( t ) self.active = ok_flags r = 1 else: # assume comma string try: flags = active_flags.split(',') except: self.show( '***' ) self.show( '*** Invalid debug param given: %s' % active_flags ) self.show( '*** please correct your param!' ) self.show( '*** due to this, full debuging is enabled' ) self.active = debug_flags for f in flags: s = f.strip() ok_flags.append( s ) self.active = ok_flags self._remove_dupe_flags() return r def active_get( self ): "returns currently active flags." return self.active def _as_one_list( self, items ): """ init param might contain nested lists, typically from group flags. This code organises lst and remves dupes """ if type( items ) <> type( [] ) and type( items ) <> type( () ): return [ items ] r = [] for l in items: if type( l ) == type([]): lst2 = self._as_one_list( l ) for l2 in lst2: self._append_unique_str(r, l2 ) elif l == None: continue else: self._append_unique_str(r, l ) return r def _append_unique_str( self, lst, item ): """filter out any dupes.""" if type(item) <> type(''): msg2 = '%s' % item raise 'Invalid item type (should be string)',msg2 if item not in lst: lst.append( item ) return lst def _validate_flag( self, flags ): 'verify that flag is defined.' if flags: for f in self._as_one_list( flags ): if not f in debug_flags: msg2 = '%s' % f raise 'Invalid debugflag given', msg2 def _remove_dupe_flags( self ): """ if multiple instances of Debug is used in same app, some flags might be created multiple time, filter out dupes """ global debug_flags unique_flags = [] for f in debug_flags: if f not in unique_flags: unique_flags.append(f) debug_flags = unique_flags jabber.py-0.5.0.orig/jabber/xmlstream.py0000644000175000017500000005062710007746541020336 0ustar kalfakalfa00000000000000## xmlstream.py ## ## Copyright (C) 2001 Matthew Allum ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation; either version 2, or (at your option) ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. """\ xmlstream.py provides simple functionality for implementing XML stream based network protocols. It is used as a base for jabber.py. xmlstream.py manages the network connectivity and xml parsing of the stream. When a complete 'protocol element' ( meaning a complete child of the xmlstreams root ) is parsed the dipatch method is called with a 'Node' instance of this structure. The Node class is a very simple XML DOM like class for manipulating XML documents or 'protocol elements' in this case. """ # $Id: xmlstream.py,v 1.45 2004/02/03 16:33:37 snakeru Exp $ import time, sys, re, socket from select import select from base64 import encodestring import xml.parsers.expat import debug _debug=debug VERSION = "0.5" False = 0 True = 1 TCP = 1 STDIO = 0 TCP_SSL = 2 ENCODING = 'utf-8' # Though it is uncommon, this is the only right setting. ustr = str BLOCK_SIZE = 1024 ## Number of bytes to get at at time via socket ## transactions DBG_INIT, DBG_ALWAYS = debug.DBG_INIT, debug.DBG_ALWAYS DBG_CONN_ERROR = 'conn-error' ; debug.debug_flags.append( DBG_CONN_ERROR ) DBG_XML_PARSE = 'xml-parse' ; debug.debug_flags.append( DBG_XML_PARSE ) DBG_XML_RAW = 'xml-raw' ; debug.debug_flags.append( DBG_XML_RAW ) DBG_XML = [ DBG_XML_PARSE, DBG_XML_RAW ] # sample multiflag def XMLescape(txt): "Escape XML entities" txt = txt.replace("&", "&") txt = txt.replace("<", "<") txt = txt.replace(">", ">") return txt def XMLunescape(txt): "Unescape XML entities" txt = txt.replace(">", ">") txt = txt.replace("<", "<") txt = txt.replace("&", "&") return txt class error: def __init__(self, value): self.value = str(value) def __str__(self): return self.value class Node: """A simple XML DOM like class""" def __init__(self, tag=None, parent=None, attrs={}, payload=[], node=None): if node: if type(node)<>type(self): node=NodeBuilder(node).getDom() self.name,self.namespace,self.attrs,self.data,self.kids,self.parent = \ node.name,node.namespace,node.attrs,node.data,node.kids,node.parent else: self.name,self.namespace,self.attrs,self.data,self.kids,self.parent = 'tag','',{},[],[],None if tag: self.namespace, self.name = (['']+tag.split())[-2:] if parent: self.parent = parent # if self.parent and not self.namespace: self.namespace=self.parent.namespace # Doesn't checked if this neccessary for attr in attrs.keys(): self.attrs[attr]=attrs[attr] for i in payload: if type(i)==type(self): self.insertNode(i) else: self.insertXML(i) # self.insertNode(Node(node=i)) # Alternative way. Needs perfomance testing. def setParent(self, node): "Set the nodes parent node." self.parent = node def getParent(self): "return the nodes parent node." return self.parent def getName(self): "Set the nodes tag name." return self.name def setName(self,val): "Set the nodes tag name." self.name = val def putAttr(self, key, val): "Add a name/value attribute to the node." self.attrs[key] = val def getAttr(self, key): "Get a value for the nodes named attribute." try: return self.attrs[key] except: return None def putData(self, data): "Set the nodes textual data" self.data.append(data) def insertData(self, data): "Set the nodes textual data" self.data.append(data) def getData(self): "Return the nodes textual data" return ''.join(self.data) def getDataAsParts(self): "Return the node data as an array" return self.data def getNamespace(self): "Returns the nodes namespace." return self.namespace def setNamespace(self, namespace): "Set the nodes namespace." self.namespace = namespace def insertTag(self, name=None, attrs={}, payload=[], node=None): """ Add a child tag of name 'name' to the node. Returns the newly created node. """ newnode = Node(tag=name, parent=self, attrs=attrs, payload=payload, node=node) self.kids.append(newnode) return newnode def insertNode(self, node): "Add a child node to the node" self.kids.append(node) return node def insertXML(self, xml_str): "Add raw xml as a child of the node" newnode = NodeBuilder(xml_str).getDom() self.kids.append(newnode) return newnode def __str__(self): return self._xmlnode2str() def _xmlnode2str(self, parent=None): """Returns an xml ( string ) representation of the node and it children""" s = "<" + self.name if self.namespace: if parent and parent.namespace != self.namespace: s = s + " xmlns = '%s' " % self.namespace for key in self.attrs.keys(): val = ustr(self.attrs[key]) s = s + " %s='%s'" % ( key, XMLescape(val) ) s = s + ">" cnt = 0 if self.kids != None: for a in self.kids: if (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt]) s = s + a._xmlnode2str(parent=self) cnt=cnt+1 if (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt]) if not self.kids and s[-1:]=='>': s=s[:-1]+' />' else: s = s + "" return s def getTag(self, name, index=None): """Returns a child node with tag name. Returns None if not found.""" for node in self.kids: if node.getName() == name: if not index: return node if index is not None: index-=1 return None def getTags(self, name): """Like getTag but returns a list with matching child nodes""" nodes=[] for node in self.kids: if node.getName() == name: nodes.append(node) return nodes def getChildren(self): """Returns a nodes children""" return self.kids def removeTag(self,tag): """Pops out specified child and returns it.""" if type(tag)==type(self): try: self.kids.remove(tag) return tag except: return None for node in self.kids: if node.getName()==tag: self.kids.remove(node) return node class NodeBuilder: """builds a 'minidom' from data parsed to it. Primarily for insertXML method of Node""" def __init__(self,data=None): self._parser = xml.parsers.expat.ParserCreate(namespace_separator=' ') self._parser.StartElementHandler = self.unknown_starttag self._parser.EndElementHandler = self.unknown_endtag self._parser.CharacterDataHandler = self.handle_data self.__depth = 0 self._dispatch_depth = 1 if data: self._parser.Parse(data,1) def unknown_starttag(self, tag, attrs): """XML Parser callback""" self.__depth = self.__depth + 1 self.DEBUG("DEPTH -> %i , tag -> %s, attrs -> %s" % \ (self.__depth, tag, str(attrs)),DBG_XML_PARSE ) if self.__depth == self._dispatch_depth: self._mini_dom = Node(tag=tag, attrs=attrs) self._ptr = self._mini_dom elif self.__depth > self._dispatch_depth: self._ptr.kids.append(Node(tag=tag,parent=self._ptr,attrs=attrs)) self._ptr = self._ptr.kids[-1] else: ## it the stream tag: if attrs.has_key('id'): self._incomingID = attrs['id'] self.last_is_data = False def unknown_endtag(self, tag ): """XML Parser callback""" self.DEBUG("DEPTH -> %i" % self.__depth,DBG_XML_PARSE) if self.__depth == self._dispatch_depth: self.dispatch(self._mini_dom) elif self.__depth > self._dispatch_depth: self._ptr = self._ptr.parent else: self.DEBUG("*** Stream terminated ? ****",DBG_CONN_ERROR) self.__depth = self.__depth - 1 self.last_is_data = False def handle_data(self, data): """XML Parser callback""" self.DEBUG("data-> " + data,DBG_XML_PARSE) if self.last_is_data: self._ptr.data[-1] += data else: self._ptr.data.append(data) self.last_is_data = True def dispatch(self,dom): pass def DEBUG(self,dup1,dup2=None): pass def getDom(self): return self._mini_dom class Stream(NodeBuilder): """Extention of NodeBuilder class. Handles stream of XML stanzas. Calls dispatch method for every child of root node (stream:stream for jabber stream). attributes _read, _write and _reader must be set by external entity """ def __init__(self, namespace, debug=[DBG_ALWAYS], log=None, id=None, timestampLog=True): self._namespace = namespace self._read , self._reader , self._write = None , None , None self._incomingID = None self._outgoingID = id self._debug = _debug.Debug(debug,encoding=ENCODING) self.DEBUG = self._debug.show # makes it backwards compatible with v0.4 code self.DEBUG("stream init called",DBG_INIT) if log: if type(log) is type(""): try: self._logFH = open(log,'w') except: print "ERROR: can open %s for writing" % log sys.exit(0) else: ## assume its a stream type object self._logFH = log else: self._logFH = None self._timestampLog = timestampLog def connect(self): NodeBuilder.__init__(self) self._dispatch_depth = 2 def timestampLog(self,timestamp): """ Enable or disable the showing of a timestamp in the log. By default, timestamping is enabled. """ self._timestampLog = timestamp def read(self): """Reads incoming data. Blocks until done. Calls self.disconnected(self) if appropriate.""" try: received = self._read(BLOCK_SIZE) except: received = '' while select([self._reader],[],[],0)[0]: add = self._read(BLOCK_SIZE) received +=add if not add: break if len(received): # length of 0 means disconnect self.DEBUG("got data " + received , DBG_XML_RAW ) self.log(received, 'RECV:') else: self.disconnected(self) return received def write(self,raw_data): """Writes raw outgoing data. Blocks until done. If supplied data is not unicode string, ENCODING is used for convertion. Avoid this! Always send your data as a unicode string.""" if type(raw_data) == type(''): self.DEBUG('Non-utf-8 string "%s" passed to Stream.write! Treating it as %s encoded.'%(raw_data,ENCODING)) raw_data = unicode(raw_data,ENCODING) data_out = raw_data.encode('utf-8') try: self._write(data_out) self.log(data_out, 'SENT:') self.DEBUG("sent %s" % data_out,DBG_XML_RAW) except: self.DEBUG("xmlstream write threw error",DBG_CONN_ERROR) self.disconnected(self) def process(self, timeout=0): """Receives incoming data (if any) and processes it. Waits for data no more than timeout seconds.""" if select([self._reader],[],[],timeout)[0]: data = self.read() self._parser.Parse(data) return len(data) return '0' # Zero means that nothing received but link is alive. def disconnect(self): """Close the stream and socket""" self.write ( u"" ) while self.process(): pass self._sock.close() self._sock = None def disconnected(self,conn): """Called when a Network Error or disconnection occurs.""" try: self.disconnectHandler(conn) except TypeError: self.disconnectHandler() def disconnectHandler(self,conn): ## To be overidden ## """Called when a Network Error or disconnection occurs. Designed to be overidden""" raise error("Standart disconnectionHandler called. Replace it with appropriate for your client.") def log(self, data, inout=''): """Logs data to the specified filehandle. Data is time stamped and prefixed with inout""" if self._logFH is not None: if self._timestampLog: self._logFH.write("%s - %s - %s\n" % (time.asctime(), inout, data)) else: self._logFH.write("%s - %s\n" % (inout, data ) ) self._logFH.flush() def getIncomingID(self): """Returns the streams ID""" return self._incomingID def getOutgoingID(self): """Returns the streams ID""" return self._incomingID class Client(Stream): def __init__(self, host, port, namespace, debug=[DBG_ALWAYS], log=None, sock=None, id=None, connection=TCP, hostIP=None, proxy=None): Stream.__init__(self, namespace, debug, log, id) self._host = host self._port = port self._sock = sock self._connection = connection if hostIP: self._hostIP = hostIP else: self._hostIP = host self._proxy = proxy self._sslObj = None self._sslIssuer = None self._sslServer = None def getSocket(self): return self._sock def connect(self): """Attempt to connect to specified host""" self.DEBUG("client connect called to %s %s type %i" % (self._host, self._port, self._connection), DBG_INIT ) Stream.connect(self) ## TODO: check below that stdin/stdout are actually open if self._connection == STDIO: self._setupComms() return self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self._proxy: self._sock.connect((self._proxy['host'], self._proxy['port'])) else: self._sock.connect((self._hostIP, self._port)) except socket.error, e: self.DEBUG("socket error: "+str(e),DBG_CONN_ERROR) raise if self._connection == TCP_SSL: try: self.DEBUG("Attempting to create ssl socket",DBG_INIT) self._sslObj = socket.ssl( self._sock, None, None ) self._sslIssuer = self._sslObj.issuer() self._sslServer = self._sslObj.server() except: self.DEBUG("Socket Error: No SSL Support",DBG_CONN_ERROR) raise self._setupComms() if self._proxy: self.DEBUG("Proxy connected",DBG_INIT) if self._proxy.has_key('type'): type = self._proxy['type'].upper() else: type = 'CONNECT' connector = [] if type == 'CONNECT': connector.append(u'CONNECT %s:%s HTTP/1.0'%(self._hostIP,self._port)) elif type == 'PUT': connector.append(u'PUT http://%s:%s/ HTTP/1.0'%(self._hostIP,self._port)) else: self.DEBUG("Proxy Error: unknown proxy type",DBG_CONN_ERROR) raise error('Unknown proxy type: '+type) connector.append('Proxy-Connection: Keep-Alive') connector.append('Pragma: no-cache') connector.append('Host: %s:%s'%(self._hostIP,self._port)) connector.append('User-Agent: Jabberpy/'+VERSION) if self._proxy.has_key('user') and self._proxy.has_key('password'): credentials = '%s:%s'%(self._proxy['user'],self._proxy['password']) credentials = encodestring(credentials).strip() connector.append('Proxy-Authorization: Basic '+credentials) connector.append('\r\n') bak = self._read , self._write self.write('\r\n'.join(connector)) reply = self.read().replace('\r','') self._read , self._write = bak try: proto,code,desc=reply.split('\n')[0].split(' ',2) except: raise error('Invalid proxy reply') if code<>'200': raise error('Invalid proxy reply: %s %s %s'%(proto,code,desc)) while reply.find('\n\n') == -1: reply += self.read().replace('\r','') self.DEBUG("Jabber server connected",DBG_INIT) self.header() def _setupComms(self): if self._connection == TCP: self._read = self._sock.recv self._write = self._sock.sendall self._reader = self._sock elif self._connection == TCP_SSL: self._read = self._sslObj.read self._write = self._sslObj.write self._reader = self._sock elif self._connection == STDIO: self._read = self.stdin.read self._write = self.stdout.write self._reader = sys.stdin else: self.DEBUG('unknown connection type',DBG_CONN_ERROR) raise IOError('unknown connection type') class Server: def now(self): return time.ctime(time.time()) def __init__(self, maxclients=10): self.host = '' self.port = 5222 self.streams = [] # make main sockets for accepting new client requests self.mainsocks, self.readsocks, self.writesocks = [], [], [] self.portsock = socket(AF_INET, SOCK_STREAM) self.portsock.bind((self.host, self.port)) self.portsock.listen(maxclients) self.mainsocks.append(self.portsock) # add to main list to identify self.readsocks.append(self.portsock) # add to select inputs list # event loop: listen and multiplex until server process killed def serve(self): print 'select-server loop starting' while 1: print "LOOPING" readables, writeables, exceptions = select(self.readsocks, self.writesocks, []) for sockobj in readables: if sockobj in self. mainsocks: # for ready input sockets newsock, address = sockobj.accept() # accept not block print 'Connect:', address, id(newsock) self.readsocks.append(newsock) self._makeNewStream(newsock) # add to select list, wait else: # client socket: read next line data = sockobj.recv(1024) # recv should not block print '\tgot', data, 'on', id(sockobj) if not data: # if closed by the clients sockobj.close() # close here and remv from self.readsocks.remove(sockobj) else: # this may block: should really select for writes too sockobj.send('Echo=>%s' % data) def _makeNewStream(self, sckt): new_stream = Stream('localhost', 5222, 'jabber:client', sock=sckt) self.streams.append(new_stream) ## maybe overide for a 'server stream' new_stream.header() return new_stream def _getStreamSockets(self): socks = []; for s in self.streams: socks.append(s.getSocket()) return socks def _getStreamFromSocket(self, sock): for s in self.streams: if s.getSocket() == sock: return s return None