]> code.delx.au - pymsnt/blobdiff - src/tlib/msn/msnw.py
Use vCard fullname if nickname isn't around.
[pymsnt] / src / tlib / msn / msnw.py
index f0794b652e230e09ffb9d7b61ff66b491292693c..6b58f50ed0097698ccb2621451218dc5bce07e87 100644 (file)
@@ -7,17 +7,13 @@ from twisted.internet.defer import Deferred
 from twisted.internet.protocol import ClientFactory
 
 # System imports
-import math, base64, binascii, math
+import math, base64, binascii
 
 # Local imports
 from debug import LogEvent, INFO, WARN, ERROR
 from tlib.msn import msn
 
 
-MAXMESSAGESIZE     = 1400
-SWITCHBOARDTIMEOUT = 30.0*60.0
-GETALLAVATARS      = False
-
 
 """
 All interaction should be with the MSNConnection and MultiSwitchboardSession classes.
@@ -26,6 +22,10 @@ You should not directly instantiate any objects of other classes.
 
 class MSNConnection:
        """ Manages all the Twisted factories, etc """
+       MAXMESSAGESIZE     = 1400
+       SWITCHBOARDTIMEOUT = 30.0*60.0
+       GETALLAVATARS      = False
+
        def __init__(self, username, password, ident):
                """ Connects to the MSN servers.
                @param username: the MSN passport to connect with.
@@ -36,6 +36,7 @@ class MSNConnection:
                self.password = password
                self.ident = ident
                self.timeout = None
+               self.notificationFactory = None
                self.notificationClient = None
                self.connect()
                LogEvent(INFO, self.ident)
@@ -49,7 +50,9 @@ class MSNConnection:
 
        def _getNotificationReferral(self):
                def timeout():
-                       if not d.called: d.errback()
+                       if not d.called:
+                               d.errback()
+                               self.logOut() # Clean up everything
                self.timeout = reactor.callLater(30, timeout)
                dispatchFactory = msn.DispatchFactory()
                dispatchFactory.userHandle = self.username
@@ -126,7 +129,7 @@ class MSNConnection:
 
                LogEvent(INFO, self.ident)
                if not self.notificationClient: return
-               if GETALLAVATARS:
+               if MSNConnection.GETALLAVATARS:
                        self._ensureSwitchboardSession(userHandle)
                sb = self.switchboardSessions.get(userHandle)
                if sb: return sb.sendAvatarRequest()
@@ -141,7 +144,7 @@ class MSNConnection:
         
                @return: A Deferred, which will fire with an argument of:
                         (fileSend, d) A FileSend object and a Deferred.
-                        The Deferred will pass one argument in a tuple,
+                        The new Deferred will pass one argument in a tuple,
                         whether or not the transfer is accepted. If you
                         receive a True, then you can call write() on the
                         fileSend object to send your file. Call close()
@@ -187,9 +190,10 @@ class MSNConnection:
 
                if not screenName: screenName = self.username
                if self.notificationClient:
-                       count = 0
+                       changeCount = [0] # Hack
                        def cb(ignored=None):
-                               if count == 3:
+                               changeCount[0] += 1
+                               if changeCount[0] == 3:
                                        self.ourStatusChanged(statusCode, screenName, personal)
                        LogEvent(INFO, self.ident)
                        self.notificationClient.changeStatus(statusCode.encode("utf-8")).addCallback(cb)
@@ -217,7 +221,7 @@ class MSNConnection:
        
        def logOut(self):
                """ Shuts down the whole connection. Don't try to call any
-               other methods after this one. """
+               other methods after this one. Except maybe connect() """
                if self.notificationClient:
                        self.notificationClient.logOut()
                for c in self.connectors:
@@ -225,6 +229,9 @@ class MSNConnection:
                if self.notificationFactory:
                        self.notificationFactory.msncon = None
                self.connectors = []
+               for sbs in self.switchboardSessions.values():
+                       if hasattr(sbs, "transport") and sbs.transport:
+                               sbs.transport.loseConnection()
                self.switchboardSessions = {}
                LogEvent(INFO, self.ident)
                
@@ -268,8 +275,9 @@ class MSNConnection:
        def gotMessage(self, userHandle, text):
                """ Called when a contact sends us a message """
        
-       def gotGroupchat(self, msnGroupchat):
+       def gotGroupchat(self, msnGroupchat, userHandle):
                """ Called when a conversation with more than one contact begins.
+               userHandle is the person who invited us.
                The overriding method is expected to set msnGroupchat.groupchat to an object
                that implements the following methods:
                        contactJoined(userHandle)
@@ -313,11 +321,15 @@ class MSNConnection:
                """ An MSN Alert (http://alerts.msn.com) was received. Body is the
                text of the alert. 'action' is a url for more information,
                'subscr' is a url to modify your your alerts subscriptions. """
+       
+       def gotAvatarImageData(self, userHandle, imageData):
+               """ An contact's avatar has been received because a switchboard
+               session with them was started. """
 
 
 class SavedEvents:
        def __init__(self):
-               self.nickname = ""
+               self.screenName = ""
                self.statusCode = ""
                self.personal = ""
                self.avatarImageData = ""
@@ -327,8 +339,8 @@ class SavedEvents:
        def send(self, msncon):
                if self.avatarImageData:
                        msncon.notificationClient.changeAvatar(self.avatarImageData, push=False)
-               if self.nickname or self.statusCode or self.personal:
-                       msncon.changeStatus(self.statusCode, self.nickname, self.personal)
+               if self.screenName or self.statusCode or self.personal:
+                       msncon.changeStatus(self.statusCode, self.screenName, self.personal)
                for listType, userHandle in self.addContacts:
                        msncon.addContact(listType, userHandle)
                for listType, userHandle in self.remContacts:
@@ -435,6 +447,7 @@ class SwitchboardSessionBase(msn.SwitchboardClient):
        def __init__(self, msncon):
                msn.SwitchboardClient.__init__(self)
                self.msncon = msncon
+               self.msnobj = msncon.notificationClient.msnobj
                self.userHandle = msncon.username
                self.ident = (msncon.ident, "INVALID!!")
                self.messageBuffer = []
@@ -488,7 +501,25 @@ class SwitchboardSessionBase(msn.SwitchboardClient):
        def failedMessage(self, *ignored):
                raise NotImplementedError
 
-       def sendMessage(self, text, noerror=False):
+       def sendClientCaps(self):
+               message = msn.MSNMessage()
+               message.setHeader("Content-Type", "text/x-clientcaps")
+               message.setHeader("Client-Name", "PyMSNt")
+               if hasattr(self.msncon, "jabberID"):
+                       message.setHeader("JabberID", str(self.msncon.jabberID))
+               self.sendMessage(message)
+       
+       def sendMessage(self, message, noerror=False):
+               # Check to make sure that clientcaps only gets sent after
+               # the first text type message.
+               if isinstance(message, msn.MSNMessage) and message.getHeader("Content-Type").startswith("text"):
+                       self.sendMessage = self.sendMessageReal
+                       self.sendClientCaps()
+                       return self.sendMessage(message, noerror)
+               else:
+                       return self.sendMessageReal(message, noerror)
+       
+       def sendMessageReal(self, text, noerror=False):
                if not isinstance(text, basestring):
                        msn.SwitchboardClient.sendMessage(self, text)
                        return
@@ -500,7 +531,7 @@ class SwitchboardSessionBase(msn.SwitchboardClient):
                                if not noerror:
                                        self.failedMessage(text)
 
-                       if len(text) < MAXMESSAGESIZE:
+                       if len(text) < MSNConnection.MAXMESSAGESIZE:
                                message = msn.MSNMessage(message=str(text.replace("\n", "\r\n").encode("utf-8")))
                                message.setHeader("Content-Type", "text/plain; charset=UTF-8")
                                message.ack = msn.MSNMessage.MESSAGE_NACK
@@ -510,12 +541,12 @@ class SwitchboardSessionBase(msn.SwitchboardClient):
                                        d.addCallback(failedMessage)
 
                        else:
-                               chunks = int(math.ceil(len(text) / float(MAXMESSAGESIZE)))
+                               chunks = int(math.ceil(len(text) / float(MSNConnection.MAXMESSAGESIZE)))
                                chunk = 0
                                guid = msn.random_guid()
                                while chunk < chunks:
-                                       offset = chunk * MAXMESSAGESIZE
-                                       text = message[offset : offset + MAXMESSAGESIZE]
+                                       offset = chunk * MSNConnection.MAXMESSAGESIZE
+                                       text = message[offset : offset + MSNConnection.MAXMESSAGESIZE]
                                        message = msn.MSNMessage(message=str(text.replace("\n", "\r\n").encode("utf-8")))
                                        message.ack = msn.MSNMessage.MESSAGE_NACK
                                        if chunk == 0:
@@ -542,12 +573,14 @@ class MultiSwitchboardSession(SwitchboardSessionBase):
                self.groupchat = None
                self.connect()
        
-       def sendMessage(self, userHandle, text, noerror):
+       def failedMessage(self, text):
+               self.groupchat.gotMessage("BOUNCE", text)
+       
+       def sendMessage(self, text, noerror=False):
                """ Used to send a mesage to the groupchat. Can be called immediately
                after instantiation. """
                if self.contactCount > 0:
-                       message = msn.MSNMessage(userHandle=userHandle, message=text)
-                       SwitchboardSessionBase.sendMessage(self, message, noerror)
+                       SwitchboardSessionBase.sendMessage(self, text, noerror)
                else:
                        #self.messageBuffer.append((message, noerror))
                        pass # They're sending messages to an empty room. Ignore.
@@ -587,9 +620,12 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                self.timeout = None
        
        def __del__(self):
+               if self.timeout:
+                       self.timeout.cancel()
+               self.timeout = None
                for message, noerror in self.messageBuffer:
                        if not noerror:
-                               self.failedMessage(self.remoteUser, message)
+                               self.failedMessage(message)
 
        def _ready(self):
                LogEvent(INFO, self.ident)
@@ -601,12 +637,13 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                self.timeout = None
                self.flushBuffer()
 
-       def _switchToMulti(self):
+       def _switchToMulti(self, userHandle):
                LogEvent(INFO, self.ident)
-               del self.switchboardSessions[self.remoteUser]
+               del self.msncon.switchboardSessions[self.remoteUser]
                self.__class__ = MultiSwitchboardSession
                del self.remoteUser
-               self.msncon.gotGroupchat(switchboardSession)
+               self.contactCount = 0
+               self.msncon.gotGroupchat(self, userHandle)
                if not self.groupchat:
                        LogEvent(ERROR, self.ident)
                        raise Exception("YouNeedAGroupchat-WeHaveAProblemError") # FIXME
@@ -619,8 +656,11 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                LogEvent(INFO, self.ident)
                if not self.reply:
                        def failCB(arg=None):
+                               if not (self.msncon and self.msncon.switchboardSessions.has_key(self.remoteUser)):
+                                       return
                                LogEvent(INFO, self.ident, "User has not joined after 30 seconds.")
                                del self.msncon.switchboardSessions[self.remoteUser]
+                               self.timeout = None
                        d = self.inviteUser(self.remoteUser)
                        d.addErrback(failCB)
                        self.timeout = reactor.callLater(30.0, failCB)
@@ -637,18 +677,44 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                        self._ready()
                if userHandle != self.remoteUser:
                        # Another user has joined, so we now have three participants.
-                       self._switchToMulti(self)
+                       remoteUser = self.remoteUser
+                       self._switchToMulti(remoteUser)
+                       self.userJoined(remoteUser)
                        self.userJoined(userHandle)
+               else:
+                       def updateAvatarCB((imageData, )):
+                               if self.msncon:
+                                       self.msncon.gotAvatarImageData(self.remoteUser, imageData)
+                       d = self.sendAvatarRequest()
+                       if d:
+                               d.addCallback(updateAvatarCB)
 
        def userLeft(self, userHandle):
                def wait():
                        if userHandle == self.remoteUser:
-                               del self.msncon.switchboardSessions[self.remoteUser]
+                               if self.msncon and self.msncon.switchboardSessions.has_key(self.remoteUser):
+                                       del self.msncon.switchboardSessions[self.remoteUser]
                reactor.callLater(0, wait) # Make sure this is handled after everything else
 
        def gotMessage(self, message):
                LogEvent(INFO, self.ident)
-               self.msncon.gotMessage(self.remoteUser, message.getMessage())
+               cTypes = [s.strip() for s in message.getHeader("Content-Type").split(';')]
+               if "text/plain" == cTypes[0]:
+                       try:
+                               if len(cTypes) > 1 and cTypes[1].lower().find("utf-8") >= 0:
+                                       text = message.getMessage().decode("utf-8")
+                               else:
+                                       text = message.getMessage()
+                               self.msncon.gotMessage(self.remoteUser, text)
+                       except:
+                               self.msncon.gotMessage(self.remoteUser, "A message was lost.")
+                               raise
+               elif "text/x-clientcaps" == cTypes[0]:
+                       if message.hasHeader("JabberID"):
+                               jid = message.getHeader("JabberID")
+                               self.msncon.userMapping(message.userHandle, jid)
+               else:
+                       LogEvent(INFO, self.ident, "Discarding unknown message type.")
        
        def gotFileReceive(self, fileReceive):
                LogEvent(INFO, self.ident)
@@ -672,7 +738,7 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                if not (msnContact and msnContact.caps & self.CAPS and msnContact.msnobj): return
                if msnContact.msnobjGot: return
                msnContact.msnobjGot = True # This is deliberately set before we get the avatar. So that we don't try to reget failed avatars over & over
-               msn.SwitchboardClient.sendAvatarRequest(self, msnContact)
+               return msn.SwitchboardClient.sendAvatarRequest(self, msnContact)
        
        def sendFile(self, msnContact, filename, filesize):
                def doSendFile(ignored=None):
@@ -684,4 +750,3 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                        self.funcBuffer.append(doSendFile)
                return d
        
-