]> code.delx.au - pymsnt/blobdiff - src/tlib/msn/msnw.py
Handle disconnects better.
[pymsnt] / src / tlib / msn / msnw.py
index 10b7b3468e88342c27d8a6154d69dbdca069c039..87ed0442623ce420d1881590cf7059ed98383447 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,11 @@ class MSNConnection:
 
        def _getNotificationReferral(self):
                def timeout():
-                       if not d.called: d.errback()
+                       self.timeout = None
+                       dispatchFactory.d = None
+                       if not d.called:
+                               d.errback(Exception("Timeout"))
+                               self.logOut() # Clean up everything
                self.timeout = reactor.callLater(30, timeout)
                dispatchFactory = msn.DispatchFactory()
                dispatchFactory.userHandle = self.username
@@ -62,6 +67,7 @@ class MSNConnection:
        
        def _gotNotificationReferral(self, (host, port)):
                self.timeout.cancel()
+               self.timeout = None
                # Create the NotificationClient
                self.notificationFactory = msn.NotificationFactory()
                self.notificationFactory.userHandle = self.username
@@ -73,7 +79,6 @@ class MSNConnection:
        
        def _sendSavedEvents(self):
                self.savedEvents.send(self)
-               self.savedEvents = None
        
        def _notificationClientReady(self, notificationClient):
                self.notificationClient = notificationClient
@@ -126,7 +131,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 +146,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()
@@ -172,8 +177,8 @@ class MSNConnection:
                if self.notificationClient:
                        LogEvent(INFO, self.ident)
                        self.notificationClient.changeAvatar(imageData, push=True)
-               else:
-                       self.savedEvents.avatarImageData = imageData
+               # Save the avatar for reuse on disconnection
+               self.savedEvents.avatarImageData = imageData
        
        def changeStatus(self, statusCode, screenName, personal):
                """
@@ -186,22 +191,24 @@ class MSNConnection:
                """
 
                if not screenName: screenName = self.username
+               if not statusCode: statusCode = msn.STATUS_ONLINE
+               if not personal: personal = ""
                if self.notificationClient:
-                       self.changeCount = 0
+                       changeCount = [0] # Hack for Python's limited scope :(
                        def cb(ignored=None):
-                               self.changeCount += 1
-                               if self.changeCount == 3:
+                               changeCount[0] += 1
+                               if changeCount[0] == 3:
                                        self.ourStatusChanged(statusCode, screenName, personal)
-                                       del self.changeCount
+                       def errcb(ignored=None):
+                               pass # FIXME, should we do something here?
                        LogEvent(INFO, self.ident)
-                       self.notificationClient.changeStatus(statusCode.encode("utf-8")).addCallback(cb)
-                       self.notificationClient.changeScreenName(screenName.encode("utf-8")).addCallback(cb)
-                       if not personal: personal = ""
-                       self.notificationClient.changePersonalMessage(personal.encode("utf-8")).addCallback(cb)
-               else:
-                       self.savedEvents.statusCode = statusCode
-                       self.savedEvents.screenName = screenName
-                       self.savedEvents.personal = personal
+                       self.notificationClient.changeStatus(statusCode.encode("utf-8")).addCallbacks(cb, errcb)
+                       self.notificationClient.changeScreenName(screenName.encode("utf-8")).addCallbacks(cb, errcb)
+                       self.notificationClient.changePersonalMessage(personal.encode("utf-8")).addCallbacks(cb, errcb)
+               # Remember the saved status
+               self.savedEvents.statusCode = statusCode
+               self.savedEvents.screenName = screenName
+               self.savedEvents.personal = personal
                                
        def addContact(self, listType, userHandle):
                """ See msn.NotificationClient.addContact """
@@ -219,15 +226,23 @@ 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:
                        c.disconnect()
+               self.connectors = []
                if self.notificationFactory:
+                       self.notificationFactory.stopTrying()
                        self.notificationFactory.msncon = None
-               self.connectors = []
+                       self.notificationFactory = None
+               for sbs in self.switchboardSessions.values():
+                       if hasattr(sbs, "transport") and sbs.transport:
+                               sbs.transport.loseConnection()
                self.switchboardSessions = {}
+               if self.timeout:
+                       self.timeout.cancel()
+                       self.timeout = None
                LogEvent(INFO, self.ident)
                
        
@@ -316,11 +331,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 = ""
@@ -330,8 +349,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:
@@ -341,11 +360,18 @@ class SavedEvents:
 
 class DispatchClient(msn.DispatchClient):
        def gotNotificationReferral(self, host, port):
-               if self.factory.d.called: return # Too slow! We've already timed out
-               self.factory.d.callback((host, port))
+               d = self.factory.d
+               self.factory.d = None
+               if not d or d.called:
+                       return # Too slow! We've already timed out
+               d.callback((host, port))
 
 
 class NotificationClient(msn.NotificationClient):
+       def doDisconnect(self, *args):
+               if hasattr(self, "transport") and self.transport:
+                       self.transport.loseConnection()
+
        def loginFailure(self, message):
                self.factory.msncon.loginFailed(message)
        
@@ -359,13 +385,23 @@ class NotificationClient(msn.NotificationClient):
        
        def logOut(self):
                msn.NotificationClient.logOut(self)
+               # If we explicitly log out, then all of these events
+               # are now redundant
+               self.loginFailure = self.doDisconnect
+               self.loggedIn = self.doDisconnect
+               self.connectionLost = lambda reason: msn.NotificationClient.connectionLost(self, reason)
        
        def connectionLost(self, reason):
-               if not self.factory.msncon: return # If we called logOut
+               if not self.factory.msncon:
+                       # If MSNConnection.logOut is called before _notificationClientReady
+                       return
+
                def wait():
                        LogEvent(INFO, self.factory.msncon.ident)
                        msn.NotificationClient.connectionLost(self, reason)
-                       self.factory.msncon.connectionLost(reason)
+                       if self.factory.maxRetries > self.factory.retries:
+                               self.factory.stopTrying()
+                               self.factory.msncon.connectionLost(reason)
                # Make sure this event is handled after any others
                reactor.callLater(0, wait)
        
@@ -419,9 +455,8 @@ class NotificationClient(msn.NotificationClient):
                sb = self.factory.msncon.switchboardSessions.get(userHandle)
                if sb and sb.transport:
                        sb.transport.loseConnection()
-               else:
-                       sb = OneSwitchboardSession(self.factory.msncon, userHandle)
-                       self.factory.msncon.switchboardSessions[userHandle] = sb
+               sb = OneSwitchboardSession(self.factory.msncon, userHandle)
+               self.factory.msncon.switchboardSessions[userHandle] = sb
                sb.connectReply(host, port, key, sessionID)
        
        def multipleLogin(self):
@@ -438,16 +473,20 @@ 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 = []
                self.funcBuffer = []
                self.ready = False
 
-       def __del__(self):
+       def connectionLost(self, reason):
+               msn.SwitchboardClient.connectionLost(self, reason)
                LogEvent(INFO, self.ident)
-               del self.msncon
-               self.transport.disconnect()
+               self.ready = False
+               self.msncon = None
+               self.msnobj = None
+               self.ident = (self.ident[0], self.ident[1], "Disconnected!")
 
        def loggedIn(self):
                LogEvent(INFO, self.ident)
@@ -491,7 +530,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
@@ -499,37 +556,38 @@ class SwitchboardSessionBase(msn.SwitchboardClient):
                        self.messageBuffer.append((text, noerror))
                else:
                        LogEvent(INFO, self.ident)
+                       text = str(text.replace("\n", "\r\n").encode("utf-8"))
                        def failedMessage(ignored):
                                if not noerror:
                                        self.failedMessage(text)
 
-                       if len(text) < MAXMESSAGESIZE:
-                               message = msn.MSNMessage(message=str(text.replace("\n", "\r\n").encode("utf-8")))
-                               message.setHeader("Content-Type", "text/plain; charset=UTF-8")
+                       if len(text) < MSNConnection.MAXMESSAGESIZE:
+                               message = msn.MSNMessage(message=text)
                                message.ack = msn.MSNMessage.MESSAGE_NACK
 
                                d = msn.SwitchboardClient.sendMessage(self, message)
                                if not noerror:
-                                       d.addCallback(failedMessage)
+                                       d.addCallbacks(failedMessage, 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]
-                                       message = msn.MSNMessage(message=str(text.replace("\n", "\r\n").encode("utf-8")))
+                                       offset = chunk * MSNConnection.MAXMESSAGESIZE
+                                       message = msn.MSNMessage(message=text[offset : offset + MSNConnection.MAXMESSAGESIZE])
                                        message.ack = msn.MSNMessage.MESSAGE_NACK
+                                       message.setHeader("Message-ID", guid)
                                        if chunk == 0:
-                                               message.setHeader("Content-Type", "text/plain; charset=UTF-8")
                                                message.setHeader("Chunks", str(chunks))
                                        else:
+                                               message.delHeader("MIME-Version")
+                                               message.delHeader("Content-Type")
                                                message.setHeader("Chunk", str(chunk))
 
                                        d = msn.SwitchboardClient.sendMessage(self, message)
                                        if not noerror:
-                                               d.addCallback(failedMessage)
+                                               d.addCallbacks(failedMessage, failedMessage)
 
                                        chunk += 1
 
@@ -540,7 +598,7 @@ class MultiSwitchboardSession(SwitchboardSessionBase):
        def __init__(self, msncon):
                """ Automatically creates a new switchboard connection to the server """
                SwitchboardSessionBase.__init__(self, msncon)
-               self.ident = (self.msncon.ident, self)
+               self.ident = (self.msncon.ident, repr(self))
                self.contactCount = 0
                self.groupchat = None
                self.connect()
@@ -548,7 +606,7 @@ class MultiSwitchboardSession(SwitchboardSessionBase):
        def failedMessage(self, text):
                self.groupchat.gotMessage("BOUNCE", text)
        
-       def sendMessage(self, text, noerror):
+       def sendMessage(self, text, noerror=False):
                """ Used to send a mesage to the groupchat. Can be called immediately
                after instantiation. """
                if self.contactCount > 0:
@@ -591,10 +649,20 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                self.chattingUsers = []
                self.timeout = None
        
-       def __del__(self):
+       def connectionLost(self, reason):
+               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)
+               self.messageBuffer = []
+
+               if self.msncon and self.msncon.switchboardSessions.has_key(self.remoteUser):
+                       # Unexpected disconnection. Must remove us from msncon
+                       self.msncon.switchboardSessions.pop(self.remoteUser)
+
+               SwitchboardSessionBase.connectionLost(self, reason)
 
        def _ready(self):
                LogEvent(INFO, self.ident)
@@ -606,16 +674,14 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                self.timeout = None
                self.flushBuffer()
 
-       def _switchToMulti(self):
+       def _switchToMulti(self, userHandle):
                LogEvent(INFO, self.ident)
                del self.msncon.switchboardSessions[self.remoteUser]
                self.__class__ = MultiSwitchboardSession
                del self.remoteUser
                self.contactCount = 0
                self.msncon.gotGroupchat(self, userHandle)
-               if not self.groupchat:
-                       LogEvent(ERROR, self.ident)
-                       raise Exception("YouNeedAGroupchat-WeHaveAProblemError") # FIXME
+               assert self.groupchat
        
        def failedMessage(self, text):
                self.msncon.failedMessage(self.remoteUser, text)
@@ -625,6 +691,10 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                LogEvent(INFO, self.ident)
                if not self.reply:
                        def failCB(arg=None):
+                               self.timeout = None
+                               self.transport.loseConnection()
+                               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]
                        d = self.inviteUser(self.remoteUser)
@@ -644,19 +714,44 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                if userHandle != self.remoteUser:
                        # Another user has joined, so we now have three participants.
                        remoteUser = self.remoteUser
-                       self._switchToMulti(userHandle)
+                       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 UnicodeDecodeError:
+                               LogEvent(WARN, self.ident, "Message lost!")
+                               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)
@@ -680,7 +775,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):
@@ -692,4 +787,3 @@ class OneSwitchboardSession(SwitchboardSessionBase):
                        self.funcBuffer.append(doSendFile)
                return d
        
-