]> code.delx.au - pymsnt/blob - src/tlib/msn/msnw.py
Added auto-reconnect.
[pymsnt] / src / tlib / msn / msnw.py
1 # Copyright 2004-2005 James Bunton <james@delx.cjb.net>
2 # Licensed for distribution under the GPL version 2, check COPYING for details
3
4 # Twisted imports
5 from twisted.internet import reactor
6 from twisted.internet.defer import Deferred
7 from twisted.internet.protocol import ClientFactory
8
9 # System imports
10 import math, base64, binascii
11
12 # Local imports
13 from debug import LogEvent, INFO, WARN, ERROR
14 from tlib.msn import msn
15
16
17
18 """
19 All interaction should be with the MSNConnection and MultiSwitchboardSession classes.
20 You should not directly instantiate any objects of other classes.
21 """
22
23 class MSNConnection:
24 """ Manages all the Twisted factories, etc """
25 MAXMESSAGESIZE = 1400
26 SWITCHBOARDTIMEOUT = 30.0*60.0
27 GETALLAVATARS = False
28
29 def __init__(self, username, password, ident):
30 """ Connects to the MSN servers.
31 @param username: the MSN passport to connect with.
32 @param password: the password for this account.
33 @param ident: a unique identifier to use in logging.
34 """
35 self.username = username
36 self.password = password
37 self.ident = ident
38 self.timeout = None
39 self.notificationFactory = None
40 self.notificationClient = None
41 self.connect()
42 LogEvent(INFO, self.ident)
43
44 def connect(self):
45 """ Automatically called by the constructor """
46 self.connectors = []
47 self.switchboardSessions = {}
48 self.savedEvents = SavedEvents() # Save any events that occur before connect
49 self._getNotificationReferral()
50
51 def _getNotificationReferral(self):
52 def timeout():
53 self.timeout = None
54 if not d.called:
55 d.errback("Timeout")
56 self.logOut() # Clean up everything
57 self.timeout = reactor.callLater(30, timeout)
58 dispatchFactory = msn.DispatchFactory()
59 dispatchFactory.userHandle = self.username
60 dispatchFactory.protocol = DispatchClient
61 d = Deferred()
62 dispatchFactory.d = d
63 d.addCallbacks(self._gotNotificationReferral, self.connectionFailed)
64 self.connectors.append(reactor.connectTCP("messenger.hotmail.com", 1863, dispatchFactory))
65 LogEvent(INFO, self.ident)
66
67 def _gotNotificationReferral(self, (host, port)):
68 self.timeout.cancel()
69 self.timeout = None
70 # Create the NotificationClient
71 self.notificationFactory = msn.NotificationFactory()
72 self.notificationFactory.userHandle = self.username
73 self.notificationFactory.password = self.password
74 self.notificationFactory.msncon = self
75 self.notificationFactory.protocol = NotificationClient
76 self.connectors.append(reactor.connectTCP(host, port, self.notificationFactory))
77 LogEvent(INFO, self.ident)
78
79 def _sendSavedEvents(self):
80 self.savedEvents.send(self)
81
82 def _notificationClientReady(self, notificationClient):
83 self.notificationClient = notificationClient
84
85 def _ensureSwitchboardSession(self, userHandle):
86 if not self.switchboardSessions.has_key(userHandle):
87 sb = OneSwitchboardSession(self, userHandle)
88 sb.connect()
89 self.switchboardSessions[userHandle] = sb
90
91
92
93 # API calls
94 def getContacts(self):
95 """ Gets the contact list.
96
97 @return an instance of MSNContactList (do not modify) if connected,
98 or None if not.
99 """
100 if self.notificationFactory:
101 return self.notificationFactory.contacts
102 else:
103 return None
104
105 def sendMessage(self, userHandle, text, noerror=False):
106 """
107 Sends a message to a contact. Can only be called after listSynchronized().
108
109 @param userHandle: the contact's MSN passport.
110 @param text: the text to send.
111 @param noerror: Set this to True if you don't want failed messages to bounce.
112 """
113 LogEvent(INFO, self.ident)
114 if self.notificationClient:
115 self._ensureSwitchboardSession(userHandle)
116 self.switchboardSessions[userHandle].sendMessage(text, noerror)
117 elif not noerror:
118 self.failedMessage(userHandle, text)
119
120 def sendAvatarRequest(self, userHandle):
121 """
122 Requests the avatar of a contact.
123
124 @param userHandle: the contact to request an avatar from.
125 @return: a Deferred() if the avatar can be fetched at this time.
126 This will fire with an argument of a tuple with the PNG
127 image data as the only element.
128 Otherwise returns None
129 """
130
131 LogEvent(INFO, self.ident)
132 if not self.notificationClient: return
133 if MSNConnection.GETALLAVATARS:
134 self._ensureSwitchboardSession(userHandle)
135 sb = self.switchboardSessions.get(userHandle)
136 if sb: return sb.sendAvatarRequest()
137
138 def sendFile(self, userHandle, filename, filesize):
139 """
140 Used to send a file to a contact.
141
142 @param username: the passport of the contact to send a file to.
143 @param filename: the name of the file to send.
144 @param filesize: the size of the file to send.
145
146 @return: A Deferred, which will fire with an argument of:
147 (fileSend, d) A FileSend object and a Deferred.
148 The new Deferred will pass one argument in a tuple,
149 whether or not the transfer is accepted. If you
150 receive a True, then you can call write() on the
151 fileSend object to send your file. Call close()
152 when the file is done.
153 NOTE: You MUST write() exactly as much as you
154 declare in filesize.
155 """
156 msnContact = self.getContacts().getContact(userHandle)
157 if not msnContact:
158 raise ValueError, "Contact not found"
159 self._ensureSwitchboardSession(userHandle)
160 return self.switchboardSessions[userHandle].sendFile(msnContact, filename, filesize)
161
162 def sendTypingToContact(self, userHandle):
163 """
164 Sends typing notification to a contact. Should send every 5secs.
165 @param userHandle: the contact to notify of our typing.
166 """
167
168 sb = self.switchboardSessions.get(userHandle)
169 if sb: return sb.sendTypingNotification()
170
171 def changeAvatar(self, imageData):
172 """
173 Changes the user's avatar.
174 @param imageData: the new PNG avatar image data.
175 """
176 if self.notificationClient:
177 LogEvent(INFO, self.ident)
178 self.notificationClient.changeAvatar(imageData, push=True)
179 # Save the avatar for reuse on disconnection
180 self.savedEvents.avatarImageData = imageData
181
182 def changeStatus(self, statusCode, screenName, personal):
183 """
184 Changes your status details. All details must be given with
185 each call. This can be called before connection if you wish.
186
187 @param statusCode: the user's new status (look in msn.statusCodes).
188 @param screenName: the user's new screenName (up to 127 characters).
189 @param personal: the user's new personal message.
190 """
191
192 if not screenName: screenName = self.username
193 if not statusCode: statusCode = msn.STATUS_ONLINE
194 if not personal: personal = ""
195 if self.notificationClient:
196 changeCount = [0] # Hack
197 def cb(ignored=None):
198 changeCount[0] += 1
199 if changeCount[0] == 3:
200 self.ourStatusChanged(statusCode, screenName, personal)
201 LogEvent(INFO, self.ident)
202 self.notificationClient.changeStatus(statusCode.encode("utf-8")).addCallback(cb)
203 self.notificationClient.changeScreenName(screenName.encode("utf-8")).addCallback(cb)
204 self.notificationClient.changePersonalMessage(personal.encode("utf-8")).addCallback(cb)
205 # Remember the saved status
206 self.savedEvents.statusCode = statusCode
207 self.savedEvents.screenName = screenName
208 self.savedEvents.personal = personal
209
210 def addContact(self, listType, userHandle):
211 """ See msn.NotificationClient.addContact """
212 if self.notificationClient:
213 return self.notificationClient.addContact(listType, str(userHandle))
214 else:
215 self.savedEvents.addContacts.append((listType, str(userHandle)))
216
217 def remContact(self, listType, userHandle):
218 """ See msn.NotificationClient.remContact """
219 if self.notificationClient:
220 return self.notificationClient.remContact(listType, str(userHandle))
221 else:
222 self.savedEvents.remContacts.append((listType, str(userHandle)))
223
224 def logOut(self):
225 """ Shuts down the whole connection. Don't try to call any
226 other methods after this one. Except maybe connect() """
227 if self.notificationClient:
228 self.notificationClient.logOut()
229 for c in self.connectors:
230 c.disconnect()
231 if self.notificationFactory:
232 self.notificationFactory.msncon = None
233 self.connectors = []
234 for sbs in self.switchboardSessions.values():
235 if hasattr(sbs, "transport") and sbs.transport:
236 sbs.transport.loseConnection()
237 self.switchboardSessions = {}
238 if self.timeout:
239 self.timeout.cancel()
240 self.timeout = None
241 LogEvent(INFO, self.ident)
242
243
244 # Reimplement these!
245 def connectionFailed(self, reason=''):
246 """ Called when the connection to the server failed. """
247
248 def loginFailed(self, reason=''):
249 """ Called when the account could not be logged in. """
250
251 def connectionLost(self, reason=''):
252 """ Called when we are disconnected. """
253
254 def multipleLogin(self):
255 """ Called when the server says there has been another login
256 for this account. """
257
258 def serverGoingDown(self):
259 """ Called when the server says that it will be going down. """
260
261 def accountNotVerified(self):
262 """ Called if this passport has not been verified. Certain
263 functions are not available. """
264
265 def userMapping(self, passport, jid):
266 """ Called when it is brought to our attention that one of the
267 MSN contacts has a Jabber ID. You should communicate with Jabber. """
268
269 def loggedIn(self):
270 """ Called when we have authenticated, but before we receive
271 the contact list. """
272
273 def listSynchronized(self):
274 """ Called when we have received the contact list. All methods
275 in this class are now valid. """
276
277 def ourStatusChanged(self, statusCode, screenName, personal):
278 """ Called when the user's status has changed. """
279
280 def gotMessage(self, userHandle, text):
281 """ Called when a contact sends us a message """
282
283 def gotGroupchat(self, msnGroupchat, userHandle):
284 """ Called when a conversation with more than one contact begins.
285 userHandle is the person who invited us.
286 The overriding method is expected to set msnGroupchat.groupchat to an object
287 that implements the following methods:
288 contactJoined(userHandle)
289 contactLeft(userHandle)
290 gotMessage(userHandle, text)
291
292 The object received as 'msnGroupchat' is an instance of MultiSwitchboardSession.
293 """
294
295 def gotContactTyping(self, userHandle):
296 """ Called when a contact sends typing notification.
297 Will be called once every 5 seconds. """
298
299 def failedMessage(self, userHandle, text):
300 """ Called when a message we sent has been bounced back. """
301
302 def contactAvatarChanged(self, userHandle, hash):
303 """ Called when we receive a changed avatar hash for a contact.
304 You should call sendAvatarRequest(). """
305
306 def contactStatusChanged(self, userHandle):
307 """ Called when we receive status information for a contact. """
308
309 def gotFileReceive(self, fileReceive):
310 """ Called when a contact sends the user a file.
311 Call accept(fileHandle) or reject() on the object. """
312
313 def contactAddedMe(self, userHandle):
314 """ Called when a contact adds the user to their list. """
315
316 def contactRemovedMe(self, userHandle):
317 """ Called when a contact removes the user from their list. """
318
319 def gotInitialEmailNotification(self, inboxunread, foldersunread):
320 """ Received at login to tell about the user's Hotmail status """
321
322 def gotRealtimeEmailNotification(self, mailfrom, fromaddr, subject):
323 """ Received in realtime whenever an email comes into the hotmail account """
324
325 def gotMSNAlert(self, body, action, subscr):
326 """ An MSN Alert (http://alerts.msn.com) was received. Body is the
327 text of the alert. 'action' is a url for more information,
328 'subscr' is a url to modify your your alerts subscriptions. """
329
330 def gotAvatarImageData(self, userHandle, imageData):
331 """ An contact's avatar has been received because a switchboard
332 session with them was started. """
333
334
335 class SavedEvents:
336 def __init__(self):
337 self.screenName = ""
338 self.statusCode = ""
339 self.personal = ""
340 self.avatarImageData = ""
341 self.addContacts = []
342 self.remContacts = []
343
344 def send(self, msncon):
345 if self.avatarImageData:
346 msncon.notificationClient.changeAvatar(self.avatarImageData, push=False)
347 if self.screenName or self.statusCode or self.personal:
348 msncon.changeStatus(self.statusCode, self.screenName, self.personal)
349 for listType, userHandle in self.addContacts:
350 msncon.addContact(listType, userHandle)
351 for listType, userHandle in self.remContacts:
352 msncon.remContact(listType, userHandle)
353
354
355
356 class DispatchClient(msn.DispatchClient):
357 def gotNotificationReferral(self, host, port):
358 if self.factory.d.called: return # Too slow! We've already timed out
359 self.factory.d.callback((host, port))
360
361
362 class NotificationClient(msn.NotificationClient):
363 def loginFailure(self, message):
364 self.factory.msncon.loginFailed(message)
365
366 def loggedIn(self, userHandle, verified):
367 LogEvent(INFO, self.factory.msncon.ident)
368 msn.NotificationClient.loggedIn(self, userHandle, verified)
369 self.factory.msncon._notificationClientReady(self)
370 self.factory.msncon.loggedIn()
371 if not verified:
372 self.factory.msncon.accountNotVerified()
373
374 def logOut(self):
375 msn.NotificationClient.logOut(self)
376
377 def connectionLost(self, reason):
378 print "NotificationClient.connectionLost!!!"
379 if not self.factory.msncon: return # If we called logOut
380 def wait():
381 LogEvent(INFO, self.factory.msncon.ident)
382 msn.NotificationClient.connectionLost(self, reason)
383 if self.factory.maxRetries >= self.factory.retries:
384 self.factory.msncon.connectionLost(reason)
385 # Make sure this event is handled after any others
386 reactor.callLater(0, wait)
387
388 def gotMSNAlert(self, body, action, subscr):
389 LogEvent(INFO, self.factory.msncon.ident)
390 self.factory.msncon.gotMSNAlert(body, action, subscr)
391
392 def gotInitialEmailNotification(self, inboxunread, foldersunread):
393 LogEvent(INFO, self.factory.msncon.ident)
394 self.factory.msncon.gotInitialEmailNotification(inboxunread, foldersunread)
395
396 def gotRealtimeEmailNotification(self, mailfrom, fromaddr, subject):
397 LogEvent(INFO, self.factory.msncon.ident)
398 self.factory.msncon.gotRealtimeEmailNotification(mailfrom, fromaddr, subject)
399
400 def userAddedMe(self, userGuid, userHandle, screenName):
401 LogEvent(INFO, self.factory.msncon.ident)
402 self.factory.msncon.contactAddedMe(userHandle)
403
404 def userRemovedMe(self, userHandle):
405 LogEvent(INFO, self.factory.msncon.ident)
406 self.factory.msncon.contactRemovedMe(userHandle)
407
408 def listSynchronized(self, *args):
409 LogEvent(INFO, self.factory.msncon.ident)
410 self.factory.msncon._sendSavedEvents()
411 self.factory.msncon.listSynchronized()
412
413 def contactAvatarChanged(self, userHandle, hash):
414 LogEvent(INFO, self.factory.msncon.ident)
415 self.factory.msncon.contactAvatarChanged(userHandle, hash)
416
417 def gotContactStatus(self, userHandle, statusCode, screenName):
418 LogEvent(INFO, self.factory.msncon.ident)
419 self.factory.msncon.contactStatusChanged(userHandle)
420
421 def contactStatusChanged(self, userHandle, statusCode, screenName):
422 LogEvent(INFO, self.factory.msncon.ident)
423 self.factory.msncon.contactStatusChanged(userHandle)
424
425 def contactPersonalChanged(self, userHandle, personal):
426 LogEvent(INFO, self.factory.msncon.ident)
427 self.factory.msncon.contactStatusChanged(userHandle)
428
429 def contactOffline(self, userHandle):
430 LogEvent(INFO, self.factory.msncon.ident)
431 self.factory.msncon.contactStatusChanged(userHandle)
432
433 def gotSwitchboardInvitation(self, sessionID, host, port, key, userHandle, screenName):
434 LogEvent(INFO, self.factory.msncon.ident)
435 sb = self.factory.msncon.switchboardSessions.get(userHandle)
436 if sb and sb.transport:
437 sb.transport.loseConnection()
438 else:
439 sb = OneSwitchboardSession(self.factory.msncon, userHandle)
440 self.factory.msncon.switchboardSessions[userHandle] = sb
441 sb.connectReply(host, port, key, sessionID)
442
443 def multipleLogin(self):
444 LogEvent(INFO, self.factory.msncon.ident)
445 self.factory.msncon.multipleLogin()
446
447 def serverGoingDown(self):
448 LogEvent(INFO, self.factory.msncon.ident)
449 self.factory.msncon.serverGoingDown()
450
451
452
453 class SwitchboardSessionBase(msn.SwitchboardClient):
454 def __init__(self, msncon):
455 msn.SwitchboardClient.__init__(self)
456 self.msncon = msncon
457 self.msnobj = msncon.notificationClient.msnobj
458 self.userHandle = msncon.username
459 self.ident = (msncon.ident, "INVALID!!")
460 self.messageBuffer = []
461 self.funcBuffer = []
462 self.ready = False
463
464 def __del__(self):
465 LogEvent(INFO, self.ident)
466 del self.msncon
467 self.transport.disconnect()
468
469 def loggedIn(self):
470 LogEvent(INFO, self.ident)
471 self.ready = True
472 self.flushBuffer()
473
474 def connect(self):
475 LogEvent(INFO, self.ident)
476 self.ready = False
477 def sbRequestAccepted((host, port, key)):
478 LogEvent(INFO, self.ident)
479 self.key = key
480 self.reply = 0
481 factory = ClientFactory()
482 factory.buildProtocol = lambda addr: self
483 reactor.connectTCP(host, port, factory)
484 def sbRequestFailed(ignored=None):
485 LogEvent(INFO, self.ident)
486 del self.msncon.switchboardSessions[self.remoteUser]
487 d = self.msncon.notificationClient.requestSwitchboardServer()
488 d.addCallbacks(sbRequestAccepted, sbRequestFailed)
489
490 def connectReply(self, host, port, key, sessionID):
491 LogEvent(INFO, self.ident)
492 self.ready = False
493 self.key = key
494 self.sessionID = sessionID
495 self.reply = 1
496 factory = ClientFactory()
497 factory.buildProtocol = lambda addr: self
498 reactor.connectTCP(host, port, factory)
499
500 def flushBuffer(self):
501 for message, noerror in self.messageBuffer[:]:
502 self.messageBuffer.remove((message, noerror))
503 self.sendMessage(message, noerror)
504 for f in self.funcBuffer[:]:
505 self.funcBuffer.remove(f)
506 f()
507
508 def failedMessage(self, *ignored):
509 raise NotImplementedError
510
511 def sendClientCaps(self):
512 message = msn.MSNMessage()
513 message.setHeader("Content-Type", "text/x-clientcaps")
514 message.setHeader("Client-Name", "PyMSNt")
515 if hasattr(self.msncon, "jabberID"):
516 message.setHeader("JabberID", str(self.msncon.jabberID))
517 self.sendMessage(message)
518
519 def sendMessage(self, message, noerror=False):
520 # Check to make sure that clientcaps only gets sent after
521 # the first text type message.
522 if isinstance(message, msn.MSNMessage) and message.getHeader("Content-Type").startswith("text"):
523 self.sendMessage = self.sendMessageReal
524 self.sendClientCaps()
525 return self.sendMessage(message, noerror)
526 else:
527 return self.sendMessageReal(message, noerror)
528
529 def sendMessageReal(self, text, noerror=False):
530 if not isinstance(text, basestring):
531 msn.SwitchboardClient.sendMessage(self, text)
532 return
533 if not self.ready:
534 self.messageBuffer.append((text, noerror))
535 else:
536 LogEvent(INFO, self.ident)
537 text = str(text.replace("\n", "\r\n").encode("utf-8"))
538 def failedMessage(ignored):
539 if not noerror:
540 self.failedMessage(text)
541
542 if len(text) < MSNConnection.MAXMESSAGESIZE:
543 message = msn.MSNMessage(message=text)
544 message.ack = msn.MSNMessage.MESSAGE_NACK
545
546 d = msn.SwitchboardClient.sendMessage(self, message)
547 if not noerror:
548 d.addCallback(failedMessage)
549
550 else:
551 chunks = int(math.ceil(len(text) / float(MSNConnection.MAXMESSAGESIZE)))
552 chunk = 0
553 guid = msn.random_guid()
554 while chunk < chunks:
555 offset = chunk * MSNConnection.MAXMESSAGESIZE
556 message = msn.MSNMessage(message=text[offset : offset + MSNConnection.MAXMESSAGESIZE])
557 message.ack = msn.MSNMessage.MESSAGE_NACK
558 message.setHeader("Message-ID", guid)
559 if chunk == 0:
560 message.setHeader("Chunks", str(chunks))
561 else:
562 message.delHeader("MIME-Version")
563 message.delHeader("Content-Type")
564 message.setHeader("Chunk", str(chunk))
565
566 d = msn.SwitchboardClient.sendMessage(self, message)
567 if not noerror:
568 d.addCallback(failedMessage)
569
570 chunk += 1
571
572
573 class MultiSwitchboardSession(SwitchboardSessionBase):
574 """ Create one of me to chat to multiple contacts """
575
576 def __init__(self, msncon):
577 """ Automatically creates a new switchboard connection to the server """
578 SwitchboardSessionBase.__init__(self, msncon)
579 self.ident = (self.msncon.ident, self)
580 self.contactCount = 0
581 self.groupchat = None
582 self.connect()
583
584 def failedMessage(self, text):
585 self.groupchat.gotMessage("BOUNCE", text)
586
587 def sendMessage(self, text, noerror=False):
588 """ Used to send a mesage to the groupchat. Can be called immediately
589 after instantiation. """
590 if self.contactCount > 0:
591 SwitchboardSessionBase.sendMessage(self, text, noerror)
592 else:
593 #self.messageBuffer.append((message, noerror))
594 pass # They're sending messages to an empty room. Ignore.
595
596 def inviteUser(self, userHandle):
597 """ Used to invite a contact to the groupchat. Can be called immediately
598 after instantiation. """
599 userHandle = str(userHandle)
600 if self.ready:
601 LogEvent(INFO, self.ident, "immediate")
602 msn.SwitchboardClient.inviteUser(self, userHandle)
603 else:
604 LogEvent(INFO, self.ident, "pending")
605 self.funcBuffer.append(lambda: msn.SwitchboardClient.inviteUser(self, userHandle))
606
607 def gotMessage(self, message):
608 self.groupchat.gotMessage(message.userHandle, message.getMessage())
609
610 def userJoined(self, userHandle, screenName=''):
611 LogEvent(INFO, self.ident)
612 self.contactCount += 1
613 self.groupchat.contactJoined(userHandle)
614
615 def userLeft(self, userHandle):
616 LogEvent(INFO, self.ident)
617 self.contactCount -= 1
618 self.groupchat.contactLeft(userHandle)
619
620
621
622 class OneSwitchboardSession(SwitchboardSessionBase):
623 def __init__(self, msncon, remoteUser):
624 SwitchboardSessionBase.__init__(self, msncon)
625 self.remoteUser = str(remoteUser)
626 self.ident = (self.msncon.ident, self.remoteUser)
627 self.chattingUsers = []
628 self.timeout = None
629
630 def __del__(self):
631 if self.timeout:
632 self.timeout.cancel()
633 self.timeout = None
634 for message, noerror in self.messageBuffer:
635 if not noerror:
636 self.failedMessage(message)
637
638 def _ready(self):
639 LogEvent(INFO, self.ident)
640 self.ready = True
641 for user in self.chattingUsers:
642 self.userJoined(user)
643 if self.timeout:
644 self.timeout.cancel()
645 self.timeout = None
646 self.flushBuffer()
647
648 def _switchToMulti(self, userHandle):
649 LogEvent(INFO, self.ident)
650 del self.msncon.switchboardSessions[self.remoteUser]
651 self.__class__ = MultiSwitchboardSession
652 del self.remoteUser
653 self.contactCount = 0
654 self.msncon.gotGroupchat(self, userHandle)
655 assert self.groupchat
656
657 def failedMessage(self, text):
658 self.msncon.failedMessage(self.remoteUser, text)
659
660 # Callbacks
661 def loggedIn(self):
662 LogEvent(INFO, self.ident)
663 if not self.reply:
664 def failCB(arg=None):
665 if not (self.msncon and self.msncon.switchboardSessions.has_key(self.remoteUser)):
666 return
667 LogEvent(INFO, self.ident, "User has not joined after 30 seconds.")
668 del self.msncon.switchboardSessions[self.remoteUser]
669 self.timeout = None
670 d = self.inviteUser(self.remoteUser)
671 d.addErrback(failCB)
672 self.timeout = reactor.callLater(30.0, failCB)
673 else:
674 self._ready()
675
676 def gotChattingUsers(self, users):
677 for userHandle in users.keys():
678 self.chattingUsers.append(userHandle)
679
680 def userJoined(self, userHandle, screenName=''):
681 LogEvent(INFO, self.ident)
682 if not self.reply:
683 self._ready()
684 if userHandle != self.remoteUser:
685 # Another user has joined, so we now have three participants.
686 remoteUser = self.remoteUser
687 self._switchToMulti(remoteUser)
688 self.userJoined(remoteUser)
689 self.userJoined(userHandle)
690 else:
691 def updateAvatarCB((imageData, )):
692 if self.msncon:
693 self.msncon.gotAvatarImageData(self.remoteUser, imageData)
694 d = self.sendAvatarRequest()
695 if d:
696 d.addCallback(updateAvatarCB)
697
698 def userLeft(self, userHandle):
699 def wait():
700 if userHandle == self.remoteUser:
701 if self.msncon and self.msncon.switchboardSessions.has_key(self.remoteUser):
702 del self.msncon.switchboardSessions[self.remoteUser]
703 reactor.callLater(0, wait) # Make sure this is handled after everything else
704
705 def gotMessage(self, message):
706 LogEvent(INFO, self.ident)
707 cTypes = [s.strip() for s in message.getHeader("Content-Type").split(';')]
708 if "text/plain" == cTypes[0]:
709 try:
710 if len(cTypes) > 1 and cTypes[1].lower().find("utf-8") >= 0:
711 text = message.getMessage().decode("utf-8")
712 else:
713 text = message.getMessage()
714 self.msncon.gotMessage(self.remoteUser, text)
715 except:
716 self.msncon.gotMessage(self.remoteUser, "A message was lost.")
717 raise
718 elif "text/x-clientcaps" == cTypes[0]:
719 if message.hasHeader("JabberID"):
720 jid = message.getHeader("JabberID")
721 self.msncon.userMapping(message.userHandle, jid)
722 else:
723 LogEvent(INFO, self.ident, "Discarding unknown message type.")
724
725 def gotFileReceive(self, fileReceive):
726 LogEvent(INFO, self.ident)
727 self.msncon.gotFileReceive(fileReceive)
728
729 def gotContactTyping(self, message):
730 LogEvent(INFO, self.ident)
731 self.msncon.gotContactTyping(message.userHandle)
732
733 def sendTypingNotification(self):
734 LogEvent(INFO, self.ident)
735 if self.ready:
736 msn.SwitchboardClient.sendTypingNotification(self)
737
738 CAPS = msn.MSNContact.MSNC1 | msn.MSNContact.MSNC2 | msn.MSNContact.MSNC3 | msn.MSNContact.MSNC4
739 def sendAvatarRequest(self):
740 if not self.ready: return
741 msnContacts = self.msncon.getContacts()
742 if not msnContacts: return
743 msnContact = msnContacts.getContact(self.remoteUser)
744 if not (msnContact and msnContact.caps & self.CAPS and msnContact.msnobj): return
745 if msnContact.msnobjGot: return
746 msnContact.msnobjGot = True # This is deliberately set before we get the avatar. So that we don't try to reget failed avatars over & over
747 return msn.SwitchboardClient.sendAvatarRequest(self, msnContact)
748
749 def sendFile(self, msnContact, filename, filesize):
750 def doSendFile(ignored=None):
751 d.callback(msn.SwitchboardClient.sendFile(self, msnContact, filename, filesize))
752 d = Deferred()
753 if self.ready:
754 reactor.callLater(0, doSendFile)
755 else:
756 self.funcBuffer.append(doSendFile)
757 return d
758