rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return maybeDeferred(render, req).addCallback(setHeaders)
return maybeDeferred(self.render, req).addCallback(setHeaders)
def setHeaders(response): for (header, value) in ( ("content-length", self.contentLength()), ("content-type", self.contentType()), ("content-encoding", self.contentType()), ): if value is not None: response.headers.setHeader(header, value)
raise TypeError, "Failure, not Exception -- you lose."
print "Failure, not Exception -- can't postmortem." pdb.set_trace()
def reportResults(self, testClass, method, resultType, results=None): tup = (testClass, method, results) self.numTests += 1 if resultType in (FAILURE, ERROR, EXPECTED_FAILURE): if self.debugger: if isinstance(results, failure.Failure): raise TypeError, "Failure, not Exception -- you lose." else: pdb.post_mortem(results...
if seenNames.has_key(plugindir): debugInspection('Seen %s already' % plugindir)
tmlname = join((d, plugindir, "plugins.tml")) if seenNames.has_key(tmlname): debugInspection('Seen %s already' % tmlname)
def getPluginFileList(debugInspection=None, showProgress=None): """Find plugin.tml files in subdirectories of paths in C{sys.path} @type debugInspection: C{None} or a callable taking one argument @param debugInspection: If not None, this is invoked with strings containing debug information about the loading process. ...
seenNames[plugindir] = 1 tmlname = join((d, plugindir, "plugins.tml"))
seenNames[tmlname] = 1
def getPluginFileList(debugInspection=None, showProgress=None): """Find plugin.tml files in subdirectories of paths in C{sys.path} @type debugInspection: C{None} or a callable taking one argument @param debugInspection: If not None, this is invoked with strings containing debug information about the loading process. ...
dict = {'__file__': pyfile, '__name__': pyfile}
dict = {'__file__': pyfile}
def rotateLog(signal, frame, logFile=logFile): logFile.rotate()
print ''.join(traceback.format_exception(*sys.exc_info())[-3:])
traceback.print_exc()
def run(): options = FirstPassOptions() try: options.parseOptions(sys.argv[1:]) except usage.UsageError, e: print str(options) print str(e) sys.exit(2) except (SystemExit, KeyboardInterrupt): sys.exit(1) except: import traceback print 'An error unexpected occurred:' print ''.join(traceback.format_exception(*sys.exc_inf...
print 'FOO2', repr(cont)
def continueReceived(self, cont): print 'FOO2', repr(cont) if not cont: return if cont[0].isupper(): f = getattr(self, 'macro_' + cont[:2].rstrip().upper(), None) print 'conting with', cont[:2].rstrip().upper(), f if f: f(cont[2:].strip()) else: self.text(cont)
print 'conting with', cont[:2].rstrip().upper(), f
def continueReceived(self, cont): print 'FOO2', repr(cont) if not cont: return if cont[0].isupper(): f = getattr(self, 'macro_' + cont[:2].rstrip().upper(), None) print 'conting with', cont[:2].rstrip().upper(), f if f: f(cont[2:].strip()) else: self.text(cont)
st = string.replace(st, k, v)
st = st.replace(k, v)
def multireplace(st, dct): for k, v in dct.items(): st = string.replace(st, k, v) return st
idx = string.find(self.buffer, delim)
idx = self.buffer.find(delim)
def processChunk(self, chunk): """I take a chunk of data and delegate out to telnet_* methods by way of processLine. If the current mode is 'Done', I'll close the connection. """ self.buffer = self.buffer + chunk
p = reactor.spawnProcess(protocol.ProcessProtocol(), "process_reader.py")
pproto = PProtocol() p = reactor.spawnProcess(pproto, "process_reader.py")
def testCyclicAlias(self): aliases = {} domain = {'': TestDomain(aliases, [])} A1 = mail.alias.AddressAlias('alias2', domain, 'alias1') A2 = mail.alias.AddressAlias('alias3', domain, 'alias2') A3 = mail.alias.AddressAlias('alias1', domain, 'alias3') aliases.update({ 'alias1': A1, 'alias2': A2, 'alias3': A3 })
self.assertEquals(r, expected) reactor.iterate() reactor.iterate() reactor.iterate()
tutil.spinUntil(lambda :r == expected) tutil.spinUntil(lambda :pproto.ended)
def testCyclicAlias(self): aliases = {} domain = {'': TestDomain(aliases, [])} A1 = mail.alias.AddressAlias('alias2', domain, 'alias1') A2 = mail.alias.AddressAlias('alias3', domain, 'alias2') A3 = mail.alias.AddressAlias('alias1', domain, 'alias3') aliases.update({ 'alias1': A1, 'alias2': A2, 'alias3': A3 })
"""Delayed.loop(ticks,func[,args=()]) -> Stoppable
"""Delayed.loop(func[, ticks=0][, args=()]) -> Stoppable
def loop(self, func,ticks=0,args=()): """Delayed.loop(ticks,func[,args=()]) -> Stoppable
except IllegalClientResponse, e: self.sendBadResponse(tag, 'Illegal syntax: ' + str(e)) except IllegalOperation, e: self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e)) except IllegalMailboxEncoding, e: self.sendNegativeResponse(tag, 'Illegal mailbox name: ' + str(e))
def lineReceived(self, line): print 'S:', repr(line) self.resetTimeout() f = getattr(self, 'parse_' + self.parseState) try: f(line) except IllegalClientResponse, e: self.sendBadResponse(tag, 'Illegal syntax: ' + str(e)) except IllegalOperation, e: self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e)) except I...
self.sendBadResponse(tag, 'Server error: ' + str(e))
self.sendUntaggedResponse('BAD Server error: ' + str(e))
def lineReceived(self, line): print 'S:', repr(line) self.resetTimeout() f = getattr(self, 'parse_' + self.parseState) try: f(line) except IllegalClientResponse, e: self.sendBadResponse(tag, 'Illegal syntax: ' + str(e)) except IllegalOperation, e: self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e)) except I...
return self.dispatchCommand(tag, cmd, rest)
try: return self.dispatchCommand(tag, cmd, rest) except IllegalClientResponse, e: self.sendBadResponse(tag, 'Illegal syntax: ' + str(e)) except IllegalOperation, e: self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e)) except IllegalMailboxEncoding, e: self.sendNegativeResponse(tag, 'Illegal mailbox name: ' + ...
def parse_command(self, line): args = line.split(None, 2) rest = None if len(args) == 3: tag, cmd, rest = args elif len(args) == 2: tag, cmd = args elif len(args) == 1: tag = args[0] self.sendBadResponse(tag, 'Missing command') return None else: self.sendBadResponse(None, 'Null command') return None
self.state = 'command'
self.parseState = 'command'
def parse_pending(self, line): self._pendingLiteral.callback(line) self._pendingLiteral = None self.state = 'command'
self.xmlstream.streamError(None)
self.xmlstream.dispatch(iq, self.AUTH_FAILED_EVENT)
def _authResultEvent(self, iq): if iq["type"] == "result": self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT) else: self.xmlstream.streamError(None)
if isinstance(content, StringTypes):
if isinstance(content, types.StringTypes):
def remote_console(self, messages): for kind, content in messages: if isinstance(content, StringTypes): self.original.output.append(content, kind) elif (kind == "exception") and isinstance(content, failure.Failure): content.printTraceback(_Notafile(self.original.output, "exception")) else: self.original.output.append(s...
self.accountName = self.account.username
def __init__(self, account, chatui): toc.TOCClient.__init__(self, account.username, account.password) basesupport.AbstractClientMixin.__init__(self, account, chatui) self.accountName = self.account.username self.roomID = {} self.roomIDreverse = {}
if online:
if away: status=AWAY elif online:
def updateBuddy(self,username,online,evilness,signontime,idletime,userclass,away): if online: status=ONLINE elif away: status=AWAY else: status=OFFLINE self.getPerson(username).setStatusAndIdle(status, idletime)
elif away: status=AWAY
def updateBuddy(self,username,online,evilness,signontime,idletime,userclass,away): if online: status=ONLINE elif away: status=AWAY else: status=OFFLINE self.getPerson(username).setStatusAndIdle(status, idletime)
print 'no packet type for', kind
log.msg('no packet type for', kind)
def dataReceived(self, data): self.buf += data while len(self.buf) > 5: length, kind = struct.unpack('!LB', self.buf[:5]) if len(self.buf) < 4 + length: return data, self.buf = self.buf[5:4+length], self.buf[4+length:] packetType = self.packetTypes.get(kind, None) if not packetType: print 'no packet type for', kind con...
print 'not implemented', packetType
log.msg('not implemented: %s' % packetType) log.msg(repr(data[4:]))
def dataReceived(self, data): self.buf += data while len(self.buf) > 5: length, kind = struct.unpack('!LB', self.buf[:5]) if len(self.buf) < 4 + length: return data, self.buf = self.buf[5:4+length], self.buf[4+length:] packetType = self.packetTypes.get(kind, None) if not packetType: print 'no packet type for', kind con...
f(data)
try: f(data) except Exception, e: reqId = struct.unpack('!L', data[:4])[0] self._ebStatus(failure.Failure(e), reqId)
def dataReceived(self, data): self.buf += data while len(self.buf) > 5: length, kind = struct.unpack('!LB', self.buf[:5]) if len(self.buf) < 4 + length: return data, self.buf = self.buf[5:4+length], self.buf[4+length:] packetType = self.packetTypes.get(kind, None) if not packetType: print 'no packet type for', kind con...
if e.args[0] == 'encrypted key with no password':
if e.args[0] == 'encrypted key with no passphrase':
def getPrivateKey(self): file = os.path.expanduser(self.usedFiles[-1]) if not os.path.exists(file): return None try: return defer.succeed(keys.getPrivateKeyObject(file)) except keys.BadKeyError, e: if e.args[0] == 'encrypted key with no password': for i in range(3): prompt = "Enter passphrase for key '%s': " % \ self.u...
return defer.succeed(keys.getPrivateKeyObject(file, password = p))
return defer.succeed(keys.getPrivateKeyObject(file, passphrase = p))
def getPrivateKey(self): file = os.path.expanduser(self.usedFiles[-1]) if not os.path.exists(file): return None try: return defer.succeed(keys.getPrivateKeyObject(file)) except keys.BadKeyError, e: if e.args[0] == 'encrypted key with no password': for i in range(3): prompt = "Enter passphrase for key '%s': " % \ self.u...
while not clientF.disconnected: reactor.iterate(0.01)
def loopbackTCP(server, client, port=0, noisy=True): """Run session between server and client protocol instances over TCP.""" from twisted.internet import reactor f = protocol.Factory() f.noisy = noisy f.buildProtocol = lambda addr, p=server: p serverPort = reactor.listenTCP(port, f, interface='127.0.0.1') reactor.iter...
reactor.iterate()
spinWhile(lambda :serverPort.connected)
def loopbackTCP(server, client, port=0, noisy=True): """Run session between server and client protocol instances over TCP.""" from twisted.internet import reactor f = protocol.Factory() f.noisy = noisy f.buildProtocol = lambda addr, p=server: p serverPort = reactor.listenTCP(port, f, interface='127.0.0.1') reactor.iter...
timeout = 1000 else: timeout = int(timeout * 1000)
timeout = 1 timeout = int(timeout * 1000)
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log): """Poll the poller for new events.""" if timeout is None: timeout = 1000 else: timeout = int(timeout * 1000) # convert seconds to milliseconds
try: l = poller.wait(len(selectables), timeout) except select.error, e: if e[0] == errno.EINTR: return else: raise
l = poller.wait(len(selectables), timeout)
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log): """Poll the poller for new events.""" if timeout is None: timeout = 1000 else: timeout = int(timeout * 1000) # convert seconds to milliseconds
selectable = selectables[fd] log.callWithLogger(selectable, _drdw, selectable, fd, event)
try: selectable = selectables[fd] except KeyError: pass else: log.callWithLogger(selectable, _drdw, selectable, fd, event)
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log): """Poll the poller for new events.""" if timeout is None: timeout = 1000 else: timeout = int(timeout * 1000) # convert seconds to milliseconds
if (service.protocol, service.socketType) not in [('tcp', 'stream')]:
if (service.protocol, service.socketType) not in [('tcp', 'stream'), ('udp', 'dgram')]:
def main(options=None): if not options: options = InetdOptions() options.parseOptions() conf = inetdconf.InetdConf() conf.parseFile(open(options['file'])) app = Application('tinetd') for service in conf.services: if (service.protocol, service.socketType) not in [('tcp', 'stream')]: log.msg('Skipping unsupported type...
self.group.account.perspective.addContact(self.members[lw.selection[0]])
self.group.account.perspective.callRemote('addContact', self.members[lw.selection[0]])
def on_AddContactButton_clicked(self, b): lw = self.xml.get_widget("ParticipantList")
self.substitute(request, child, subs)
substitute(request, child, subs)
def substitute(request, node, subs): """ Look through the given node's children for strings, and attempt to do string substitution with the given parameter. """ for child in node.childNodes: if child.nodeValue: child.replaceData(0, len(child.nodeValue), child.nodeValue % subs) self.substitute(request, child, subs)
accept() on a server. Programmers for the twisted.net framework should not have to use me directly, since I am automatically instantiated in TCPServer's doRead method. For documentation on what I do, refer to the documentation for twisted.protocols.protocol.Transport.
accept() on a server.
def __init__(self, host, port, bindAddress, connector, reactor=None): self.connector = connector skt = self.createInternetSocket() self.addr = (host, port) whenDone = self.resolveAddress err = None # try to bind to given address if bindAddress is not None: try: skt.bind(bindAddress) except socket.error, se: err = error...
return ('INET',)+self.client
if isinstance(self.client, types.TupleType): return ('INET',)+self.client else: return ("INET", self.client)
def getPeer(self): """ Returns a tuple of ('INET', hostname, port), indicating the connected client's address. """ return ('INET',)+self.client
deferredError(self.dbpool.runQuery("select * from NOTABLE")) deferredError(self.dbpool.runOperation("delete from * from NOTABLE")) deferredError(self.dbpool.runInteraction(self.bad_interaction)) log.flushErrors()
if self.test_failures: deferredError(self.dbpool.runQuery("select * from NOTABLE")) deferredError(self.dbpool.runOperation("deletexxx from NOTABLE")) deferredError(self.dbpool.runInteraction(self.bad_interaction)) log.flushErrors()
def testPool(self): # make sure failures are raised correctly deferredError(self.dbpool.runQuery("select * from NOTABLE")) deferredError(self.dbpool.runOperation("delete from * from NOTABLE")) deferredError(self.dbpool.runInteraction(self.bad_interaction)) log.flushErrors()
conn = psycopg.connect(database=PostgresTestCase.DB_NAME, user=PostgresTestCase.DB_USER, password=PostgresTestCase.DB_PASS)
conn = psycopg.connect(database=PsycopgTestCase.DB_NAME, user=PsycopgTestCase.DB_USER, password=PsycopgTestCase.DB_PASS)
def testQuoting(self): for value, typ, expected in [ (12, "integer", "12"), ("foo'd", "text", "'foo''d'"), ("\x00abc\\s\xFF", "bytea", "'\\\\000abc\\\\\\\\s\\377'"), ]: self.assertEquals(util.quote(value, typ), expected)
global n
global _n
def _generateMaildirName(): """utility function to generate a unique maildir name """ global n t = str(int(time.time())) s = socket.gethostname() p = os.getpid() n = n+1 return '%s.%s_%s.%s' % (t, p, n, s)
n = n+1 return '%s.%s_%s.%s' % (t, p, n, s)
_n = _n+1 return '%s.%s_%s.%s' % (t, p, _n, s)
def _generateMaildirName(): """utility function to generate a unique maildir name """ global n t = str(int(time.time())) s = socket.gethostname() p = os.getpid() n = n+1 return '%s.%s_%s.%s' % (t, p, n, s)
except OSError, (err, str):
except OSError, (err, estr):
def undeleteMessages(self): """Undelete any deleted messages it is possible to undelete This moves any messages from .Trash/ subfolder back to their original position, and empties out the deleted dictionary. """ for (real, trash) in self.deleted.items(): try: os.rename(trash, real) except OSError, (err, str): # If the...
if self.chunked:
if self.chunked and self.code not in NO_BODY_CODES:
def finish(self): """We are finished writing data.""" if self.chunked: # write last chunk and closing CRLF self.transport.write("0\r\n\r\n") elif not self.startedWriting: # write headers self.write('')
(self.headers.get('content-length', None) is None)): l.append("%s: %s\r\n" % ('Transfer-encoding', 'chunked'))
(self.headers.get('content-length', None) is None) and (self.code not in NO_BODY_CODES)): l.append("%s: %s\r\n" % ('Transfer-encoding', 'chunked'))
def write(self, data): """ Write some data as a result of an HTTP request. The first time this is called, it writes out response data. """ if not self.startedWriting: self.startedWriting = 1 version = self.clientproto if version != "HTTP/0.9": l = [] l.append('%s %s %s\r\n' % (version, self.code, self.code_message)) #...
val = eval(code)
val = eval(code, self.namespace)
def perspective_do(self, mesg): fn = "$manhole" try: code = compile(mesg, fn, 'eval') except: try: code = compile(mesg, fn, 'exec') except: io = StringIO.StringIO() traceback.print_exc(file=io) return io.getvalue() try: val = eval(code) except: io = StringIO.StringIO() traceback.print_exc(file=io) return io.getvalue() ...
d = utils.getProcessOutput(sys.executable, [scriptFile])
d = utils.getProcessOutput(sys.executable, ['-u', scriptFile])
def testOutput(self): scriptFile = self.makeSourceFile([ 'print "hello world"' ]) d = utils.getProcessOutput(sys.executable, [scriptFile]) return d.addCallback(self.assertEquals, "hello world\n")
d = utils.getProcessOutput(exe, [scriptFile], errortoo=0)
d = utils.getProcessOutput(exe, ['-u', scriptFile], errortoo=0)
def testOutputWithErrorIgnored(self): # make sure stderr raises an error normally exe = sys.executable scriptFile = self.makeSourceFile([ 'import sys', 'sys.stderr.write("hello world\\n")' ])
d = utils.getProcessOutput(exe, [scriptFile], errortoo=1)
d = utils.getProcessOutput(exe, ['-u', scriptFile], errortoo=1)
def testOutputWithErrorCollected(self): # make sure stderr raises an error normally exe = sys.executable scriptFile = self.makeSourceFile([ 'import sys', 'sys.stderr.write("hello world\\n")' ])
d = utils.getProcessValue(exe, [scriptFile])
d = utils.getProcessValue(exe, ['-u', scriptFile])
def testValue(self): exe = sys.executable scriptFile = self.makeSourceFile([ "import sys", "sys.exit(1)" ])
d = utils.getProcessOutputAndValue(exe, [scriptFile])
d = utils.getProcessOutputAndValue(exe, ['-u', scriptFile])
def gotOutputAndValue((out, err, code)): self.assertEquals(out, "hello world!" + os.linesep) self.assertEquals(err, "goodbye world!" + os.linesep) self.assertEquals(code, 1)
d = utils.getProcessOutputAndValue(exe, [scriptFile])
d = utils.getProcessOutputAndValue(exe, ['-u', scriptFile])
def gotOutputAndValue(err): (out, err, sig) = err.value # XXX Sigh wtf self.assertEquals(out, "stdout bytes" + os.linesep) self.assertEquals(err, "stderr bytes" + os.linesep) self.assertEquals(sig, signal.SIGKILL)
m = o.getattr(str(ov.object))
m = getattr(o, str(ov.object), None)
def doIteration(self, timeout): if timeout is None: timeout = INFINITE else: timeout = int(timeout * 1000) (ret, bytes, key, ov) = GetQueuedCompletionStatus(self.iocp, timeout) if int(key) not in self.completables: raise ValueError("unexpected completion key %s" % (key,)) # what's the right thing to do here? o = self.c...
try: from xml.dom.minidom import parse except ImportError: return
from xml.dom.minidom import parse
def _getSVNVersion(self): """ Figure out the SVN revision number based on the existance of twisted/.svn/entries, and its contents. This requires parsing the entries file and reading the first XML tag in the xml document that has a revision="" attribute.
- create factories for each respective client
- switchboard factory
to handle this 'cleanly'. One way would be to define methods like: def callBack(self, (arg1, arg2, arg)): ... another
from twisted.python import log
from twisted.internet.protocol import ClientFactory from twisted.internet.ssl import ClientContextFactory from twisted.python import failure, log
to handle this 'cleanly'. One way would be to define methods like: def callBack(self, (arg1, arg2, arg)): ... another
import md5, types, operator, os
import types, operator, os, md5
to handle this 'cleanly'. One way would be to define methods like: def callBack(self, (arg1, arg2, arg)): ... another
MSN_PROTOCOL_VERSION = "MSNP7" MSN_PORT = 1863 MSN_MAX_MESSAGE = 1664 MSN_CHALLENGE_STR = "Q1P7W2E4J9R8U3S5"
MSN_PROTOCOL_VERSION = "MSNP8 CVR0" MSN_PORT = 1863 MSN_MAX_MESSAGE = 1664 MSN_CHALLENGE_STR = "Q1P7W2E4J9R8U3S5" MSN_CVR_STR = "0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS" LOGIN_SUCCESS = 1 LOGIN_FAILURE = 2 LOGIN_REDIRECT = 3
to handle this 'cleanly'. One way would be to define methods like: def callBack(self, (arg1, arg2, arg)): ... another
FORWARD_LIST = 'fl' ALLOW_LIST = 'al' REVERSE_LIST = 'rl' BLOCK_LIST = 'bl'
FORWARD_LIST = 1 ALLOW_LIST = 2 BLOCK_LIST = 4 REVERSE_LIST = 8
to handle this 'cleanly'. One way would be to define methods like: def callBack(self, (arg1, arg2, arg)): ... another
""" This Exception is basically used for debugging purposes, as the official MSN server should never send anything _wrong_ and nobody in their right mind would run their B{own} MSN server...if it is raised by default command handlers (handle_BLAH) the error will be logged.
""" This Exception is basically used for debugging purposes, as the official MSN server should never send anything _wrong_ and nobody in their right mind would run their B{own} MSN server. If it is raised by default command handlers (handle_BLAH) the error will be logged.
def checkParamLen(num, expected, cmd, error=None): if error == None: error = "Invalid Number of Parameters for %s" % cmd if num != expected: raise MSNProtocolError, error
@ivar ack: This variable is used to tell the server how to respond once the message has been sent. If set to MESSAGE_ACK (default) the server will respond with an ACK upon receiving the message, if set to MESSAGE_NACK the server will respond with a NACK upon failure to receive the message. If set to MESSAGE_ACK_NONE ...
@ivar ack: This variable is used to tell the server how to respond once the message has been sent. If set to MESSAGE_ACK (default) the server will respond with an ACK upon receiving the message, if set to MESSAGE_NACK the server will respond with a NACK upon failure to receive the message. If set to MESSAGE_ACK_NONE th...
def checkParamLen(num, expected, cmd, error=None): if error == None: error = "Invalid Number of Parameters for %s" % cmd if num != expected: raise MSNProtocolError, error
""" This class represents a contact (user). @ivar userHandle: The contact's user handle (passport). @ivar screenName: The contact's screen name. @ivar group: The group ID. @type group: int if contact is in a group, None otherwise. @ivar status: The contact's status code. @type status: str if contact's status is known,...
""" This class represents a contact (user). @ivar userHandle: The contact's user handle (passport). @ivar screenName: The contact's screen name. @ivar groups: A list of all the group IDs which this contact belongs to. @ivar lists: An integer representing the sum of all lists that this contact belongs to. @ivar status:...
def setMessage(self, message): """ set the message text """ self.message = message
def __init__(self, userHandle="", screenName="", listType=None, group=None, status=None):
def __init__(self, userHandle="", screenName="", lists=0, groups=[], status=None):
def __init__(self, userHandle="", screenName="", listType=None, group=None, status=None): self.userHandle = userHandle self.screenName = screenName self.list = listType # list ('fl','rl','bl','al') self.group = group # group id (if applicable) self.status = status # current status
self.list = listType self.group = group self.status = status
self.lists = lists self.groups = [] self.status = status
def __init__(self, userHandle="", screenName="", listType=None, group=None, status=None): self.userHandle = userHandle self.screenName = screenName self.list = listType # list ('fl','rl','bl','al') self.group = group # group id (if applicable) self.status = status # current status
""" This class represents a basic MSN contact list. @ivar contacts: The forward list (users on my list) @type contacts: dict (mapping user handles to MSNContact objects) @ivar authorizedContacts: Contacts that I have allowed to be notified when my state changes (allow list) @type authorizedContacts: dict (mapping use...
""" This class represents a basic MSN contact list. @ivar contacts: All contacts on my various lists @type contacts: dict (mapping user handles to MSNContact objects) @ivar version: The current contact list version (used for list syncing) @ivar groups: a mapping of group ids to group names (groups can only exist on th...
def setPhone(self, phoneType, value): """ set phone numbers/values for this specific user .. for phoneType check the *_PHONE constants and HAS_PAGER """
self.authorizedContacts = {} self.reverseContacts = {} self.blockedContacts = {}
def __init__(self): self.contacts = {} self.authorizedContacts = {} self.reverseContacts = {} self.blockedContacts = {} self.version = 0 self.groups = {}
def addContact(self, listType, contact, force=0): """ Add a contact to the desired list. @param listType: Which underlying contact list to add the user to: - FORWARD_LIST - 'B{fl}': the forward list - ALLOW_LIST - 'B{al}': the allow list - REVERSE_LIST - 'B{rl}': the reverse list - BLOCK_LIST - 'B{bl}': the block l...
self.autoAdd = 0 self.privacy = 0 def _getContactsFromList(self, listType): """ Obtain all contacts which belong to the given list type. """ return dict([(uH,obj) for uH,obj in self.contacts.items() if obj.lists & listType]) def addContact(self, contact): """ Add a contact """ self.contacts[contact.userHandle] = cont...
def __init__(self): self.contacts = {} self.authorizedContacts = {} self.reverseContacts = {} self.blockedContacts = {} self.version = 0 self.groups = {}
class MSNDispatchClient(MSNEventBase): """ This class provides support for clients connecting to the dispatch server @ivar userHandle: your user handle (passport) needed before connecting. """
class DispatchClient(MSNEventBase): """ This class provides support for clients connecting to the dispatch server @ivar userHandle: your user handle (passport) needed before connecting. """
def gotError(self, errorCode): """ called when the server sends an error which is not in response to a sent command (ie. it has no matching transaction ID) """ log.msg('Error %s' % (errorCodes[errorCode]))
if versions is None or versions[0].upper() != MSN_PROTOCOL_VERSION:
if versions is None or ' '.join(versions) != MSN_PROTOCOL_VERSION:
def handle_VER(self, params): versions = params[1:] if versions is None or versions[0].upper() != MSN_PROTOCOL_VERSION: self.transport.loseConnection() raise MSNProtocolError, "Version Mismatch" id = self._nextTransactionID() self.sendLine("INF %s" % id)
raise MSNProtocolError, "Version Mismatch"
raise MSNProtocolError, "Invalid version response"
def handle_VER(self, params): versions = params[1:] if versions is None or versions[0].upper() != MSN_PROTOCOL_VERSION: self.transport.loseConnection() raise MSNProtocolError, "Version Mismatch" id = self._nextTransactionID() self.sendLine("INF %s" % id)
self.sendLine("INF %s" % id) def handle_INF(self, params): try: mechanism = params[1] except IndexError: raise MSNProtocolError, "Invalid parameters for INF" if mechanism.upper() != "MD5": self.transport.loseConnection() raise MSNProtocolError, "Unknown Auth Mechanism Specified by Server" id = self._nextTransactionID(...
self.sendLine("CVR %s %s %s" % (id, MSN_CVR_STR, self.userHandle)) def handle_CVR(self, params): self.sendLine("USR %s TWN I %s" % (self._nextTransactionID(), self.userHandle))
def handle_VER(self, params): versions = params[1:] if versions is None or versions[0].upper() != MSN_PROTOCOL_VERSION: self.transport.loseConnection() raise MSNProtocolError, "Version Mismatch" id = self._nextTransactionID() self.sendLine("INF %s" % id)
class MSNNotificationClient(MSNEventBase): """ This class provides support for clients connecting to the notification server. @ivar userHandle: your user handle. @ivar screenName: your screen name @ivar password: MSN password """
class NotificationClient(MSNEventBase): """ This class provides support for clients connecting to the notification server. """ factory = None
def gotNotificationReferral(self, host, port): """ called when we get a referral to the notification server.
self.userHandle = "" self.screenName = "" self.password = ""
def __init__(self, currentID=0): MSNEventBase.__init__(self) self.userHandle = "" self.screenName = "" self.password = "" self.currentID = currentID
self.listState = (None, None) self._pendingLists = {} self._pendingState = {} self._pendingGroups = {}
self._state = ['DISCONNECTED', {}] def _setState(self, state): self._state[0] = state def _getState(self): return self._state[0] def _getStateData(self, key): return self._state[1][key] def _setStateData(self, key, value): self._state[1][key] = value def _remStateData(self, *args): for key in args: del self._state...
def __init__(self, currentID=0): MSNEventBase.__init__(self) self.userHandle = "" self.screenName = "" self.password = "" self.currentID = currentID
def _createUserFromListReply(self, params): numParams = len(params) if numParams == 6: if params[0] == "FL": raise MSNProtocolError, "Invalid Parameters for LST" user = MSNContact(userHandle=params[4], screenName=unquote(params[5]), listType=params[0]) return user elif numParams == 7: if params[0] != "FL": raise MSNPro...
def connectionLost(self, reason): self._setState('DISCONNECTED') self._state[1] = {} MSNEventBase.connectionLost(self, reason)
def _createUserFromListReply(self, params): numParams = len(params) if numParams == 6: if params[0] == "FL": raise MSNProtocolError, "Invalid Parameters for LST" user = MSNContact(userHandle=params[4], screenName=unquote(params[5]), listType=params[0]) return user elif numParams == 7: if params[0] != "FL": raise MSNPro...
if versions is None or versions[0] != MSN_PROTOCOL_VERSION:
if versions is None or ' '.join(versions) != MSN_PROTOCOL_VERSION:
def handle_VER(self, params): versions = params[1:] if versions is None or versions[0] != MSN_PROTOCOL_VERSION: self.transport.loseConnection() raise MSNProtocolError, "Invalid version response" self.sendLine("INF %s" % self._nextTransactionID())
self.sendLine("INF %s" % self._nextTransactionID()) def handle_INF(self, params): try: mechanism = params[1] except IndexError: raise MSNProtocolError, "Invalid auth mechanism supplied by server" if mechanism.upper() != "MD5": raise MSNProtocolError, "Invalid auth mechanism supplied by server" self.sendLine("USR %s MD...
self.sendLine("CVR %s %s %s" % (self._nextTransactionID(), MSN_CVR_STR, self.factory.userHandle)) def handle_CVR(self, params): self.sendLine("USR %s TWN I %s" % (self._nextTransactionID(), self.factory.userHandle))
def handle_VER(self, params): versions = params[1:] if versions is None or versions[0] != MSN_PROTOCOL_VERSION: self.transport.loseConnection() raise MSNProtocolError, "Invalid version response" self.sendLine("INF %s" % self._nextTransactionID())
if len(params) != 4 and len(params) != 5:
if len(params) != 4 and len(params) != 6:
def handle_USR(self, params): if len(params) != 4 and len(params) != 5: raise MSNProtocolError, "Invalid Number of Parameters for USR"
self.sendLine("USR %s MD5 S %s" % (self._nextTransactionID(), md5.md5(params[3]+self.password).hexdigest().lower()))
f = self.factory d = _login(f.userHandle, f.password, f.passportServer, authData=params[3]) d.addCallback(self._passportLogin) d.addErrback(self._passportError) def _passportLogin(self, result): if result[0] == LOGIN_REDIRECT: d = _login(self.factory.userHandle, self.factory.password, result[1], cached=1, authData=res...
def handle_USR(self, params): if len(params) != 4 and len(params) != 5: raise MSNProtocolError, "Invalid Number of Parameters for USR"
checkParamLen(len(params), 2, 'CHG')
checkParamLen(len(params), 3, 'CHG')
def handle_CHG(self, params): checkParamLen(len(params), 2, 'CHG') id = int(params[0]) if not self._fireCallback(id, params[1]): self.statusChanged(params[1])
checkParamLen(len(params), 4, 'ILN')
checkParamLen(len(params), 5, 'ILN')
def handle_ILN(self, params): checkParamLen(len(params), 4, 'ILN') self.gotContactStatus(params[1], params[2], unquote(params[3]))
checkParamLen(len(params), 3, 'NLN')
checkParamLen(len(params), 4, 'NLN')
def handle_NLN(self, params): checkParamLen(len(params), 3, 'NLN') self.contactStatusChanged(params[0], params[1], unquote(params[2]))
if not self.ids.has_key(id): return if self.ids[id][1]: syn = 1 else: syn = 0 user = self._createUserFromListReply(params[1:]) if user: if self._pendingLists.has_key(id): self._pendingLists[id].append(user) else: self._pendingLists[id] = [user] self.listState = (None, id) if not syn and (params[3] == params[4]): if p...
if len(params) == 2: self._setState('SESSION') self._fireCallback(id, None, None) else: contacts = MSNContactList() contacts.version = int(params[1]) self._setStateData('list', contacts) self._setStateData('lst_reply', int(params[2])) self._setStateData('lsg_reply', int(params[3])) self._setStateData('lst_sofar', 0) se...
def handle_LST(self, params): id = int(params[0]) if not self.ids.has_key(id): return # XXX: should we raise an exception? if self.ids[id][1]: syn = 1 # part of a syn response else: syn = 0 # part of a lst response
if numParams < 2: raise MSNProtocolError, "Invalid Number of Paramaters for GTC" id = int(params[0]) if self.ids.has_key(id): if self.ids[id][1]: checkParamLen(numParams, 3, 'GTC') if params[2].lower() == "a": self._pendingState['autoAdd'] = 0 elif params[2].lower() == "n": self._pendingState['autoAdd'] = 1 else: rais...
if numParams == 2: self._getStateData('last_contact').setPhone(params[0], unquote(params[1])) elif numParams == 4: self.gotPhoneNumber(int(params[0]), params[1], params[2], unquote(params[3]))
def handle_GTC(self, params): numParams = len(params) if numParams < 2: raise MSNProtocolError, "Invalid Number of Paramaters for GTC" # debug id = int(params[0]) if self.ids.has_key(id): # check to see if this is in response to a SYN if self.ids[id][1]: checkParamLen(numParams, 3, 'GTC') # debug if params[2].lower() =...
listType = params[1]
listType = params[1].lower()
def handle_ADD(self, params): numParams = len(params) if numParams < 5 or params[1].upper() not in ('AL','BL','RL','FL'): raise MSNProtocolError, "Invalid Paramaters for ADD" # debug id = int(params[0]) listType = params[1] listVer = int(params[2]) userHandle = params[3] groupID = None if numParams == 6: # they sent a ...
if not self._fireCallback(id, listType, userHandle, listVer, groupID):
if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
def handle_ADD(self, params): numParams = len(params) if numParams < 5 or params[1].upper() not in ('AL','BL','RL','FL'): raise MSNProtocolError, "Invalid Paramaters for ADD" # debug id = int(params[0]) listType = params[1] listVer = int(params[2]) userHandle = params[3] groupID = None if numParams == 6: # they sent a ...
listType = params[1]
listType = params[1].lower()
def handle_REM(self, params): numParams = len(params) if numParams < 4 or params[1].upper() not in ('AL','BL','FL','RL'): raise MSNProtocolError, "Invalid Paramaters for REM" # debug id = int(params[0]) listType = params[1] listVer = int(params[2]) userHandle = params[3] groupID = None if numParams == 5: if params[1] !...
if not self._fireCallback(id, listType, userHandle, listVer, groupID):
if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
def handle_REM(self, params): numParams = len(params) if numParams < 4 or params[1].upper() not in ('AL','BL','FL','RL'): raise MSNProtocolError, "Invalid Paramaters for REM" # debug id = int(params[0]) listType = params[1] listVer = int(params[2]) userHandle = params[3] groupID = None if numParams == 5: if params[1] !...
""" called when the client has logged in @param userHandle: our userHandle @param screenName: our screenName @param verified: 1 if our passport has been (verified), 0 if not. (i'm not sure of the significace of this) @type verified: int
self.factory.screenName = screenName if not self.factory.contacts: listVersion = 0 else: listVersion = self.factory.contacts.version self.syncList(listVersion).addCallback(self.listSynchronized) def loginFailure(self, message): """ Called when the client fails to login. @param message: a message indicating the proble...
def loggedIn(self, userHandle, screenName, verified): """ called when the client has logged in
""" called after logging in when the server sends an initial message with MSN/passport specific profile information such as country, number of kids, etc... Check the message headers for the specific values. @param message: The profile message
""" Called after logging in when the server sends an initial message with MSN/passport specific profile information such as country, number of kids, etc. Check the message headers for the specific values. @param message: The profile message
def gotProfile(self, message): """ called after logging in when the server sends an initial message with MSN/passport specific profile information such as country, number of kids, etc... Check the message headers for the specific values.
pass
self.factory.status = statusCode
def statusChanged(self, statusCode): """ called when our status changes and it isn't in response to a client command.
pass
self.factory.contacts.getContact(userHandle).status = statusCode
def gotContactStatus(self, statusCode, userHandle, screenName): """ called after loggin in when the server sends status of online contacts.
pass
self.factory.contacts.getContact(userHandle).status = statusCode
def contactStatusChanged(self, statusCode, userHandle, screenName): """ called when we're notified that a contact's status has changed.
pass
self.factory.contacts.getContact(userHandle).status = STATUS_OFFLINE
def contactOffline(self, userHandle): """ called when a contact goes offline.
pass
self.factory.contacts.version = listVersion self.factory.contacts.getContact(userHandle).setPhone(phoneType, number)
def gotPhoneNumber(self, listVersion, userHandle, phoneType, number): """ called when the server sends us phone details about a specific user (for example after a user is added the server will send their status, phone details etc ...
pass
self.factory.contacts.version = listVersion c = self.factory.contacts.getContact(userHandle) if not c: c = MSNContact(userHandle=userHandle, screenName=screenName) self.factory.contacts.addContact(c) c.addToList(REVERSE_LIST)
def userAddedMe(self, userHandle, screenName, listVersion): """ called when a user adds me to their list. (ie. they have been added to the reverse list.
pass
self.factory.contacts.version = listVersion c = self.factory.contacts.getContact(userHandle) c.removeFromList(REVERSE_LIST) if c.lists == 0: self.factory.contacts.remContact(c.userHandle)
def userRemovedMe(self, userHandle, listVersion): """ called when a user removes us from their contact list (they are no longer on our reverseContacts list and changes to the underlying list should be made to reflect this).
""" called when we get an invitation to a switchboard server. This happens when a user requests a chat session with us. @param sessionID: session ID number, must be remembered for logging in @param host: the hostname of the switchboard server @param port: the port to connect to @param key: used for authorization when ...
""" Called when we get an invitation to a switchboard server. This happens when a user requests a chat session with us. @param sessionID: session ID number, must be remembered for logging in @param host: the hostname of the switchboard server @param port: the port to connect to @param key: used for authorization when ...
def gotSwitchboardInvitation(self, sessionID, host, port, key, userHandle, screenName): """ called when we get an invitation to a switchboard server. This happens when a user requests a chat session with us.
""" called when the server says there has been another login under our account, the server should disconnect us right away.
""" Called when the server says there has been another login under our account, the server should disconnect us right away.
def multipleLogin(self): """ called when the server says there has been another login under our account, the server should disconnect us right away. """ pass
""" called when the server has notified us that it is going down for maintenance.
""" Called when the server has notified us that it is going down for maintenance.
def serverGoingDown(self): """ called when the server has notified us that it is going down for maintenance. """ pass
""" change my current status. @param status: 3-letter status code (as defined by the STATUS_* constants) @return: A Deferred, the callback of which will be fired when the server confirms the change of status. The callback argument will be a tuple with the new status code as the only element.
""" Change my current status. This method will add a default callback to the returned Deferred which will update the status attribute of the factory. @param status: 3-letter status code (as defined by the STATUS_* constants) @return: A Deferred, the callback of which will be fired when the server confirms the change o...
def changeStatus(self, status): """ change my current status.