pbsupport.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. L{twisted.words} support for Instance Messenger.
  5. """
  6. from __future__ import print_function
  7. from twisted.internet import defer
  8. from twisted.internet import error
  9. from twisted.python import log
  10. from twisted.python.failure import Failure
  11. from twisted.spread import pb
  12. from twisted.words.im.locals import ONLINE, OFFLINE, AWAY
  13. from twisted.words.im import basesupport, interfaces
  14. from zope.interface import implementer
  15. class TwistedWordsPerson(basesupport.AbstractPerson):
  16. """I a facade for a person you can talk to through a twisted.words service.
  17. """
  18. def __init__(self, name, wordsAccount):
  19. basesupport.AbstractPerson.__init__(self, name, wordsAccount)
  20. self.status = OFFLINE
  21. def isOnline(self):
  22. return ((self.status == ONLINE) or
  23. (self.status == AWAY))
  24. def getStatus(self):
  25. return self.status
  26. def sendMessage(self, text, metadata):
  27. """Return a deferred...
  28. """
  29. if metadata:
  30. d=self.account.client.perspective.directMessage(self.name,
  31. text, metadata)
  32. d.addErrback(self.metadataFailed, "* "+text)
  33. return d
  34. else:
  35. return self.account.client.perspective.callRemote('directMessage',self.name, text)
  36. def metadataFailed(self, result, text):
  37. print("result:",result,"text:",text)
  38. return self.account.client.perspective.directMessage(self.name, text)
  39. def setStatus(self, status):
  40. self.status = status
  41. self.chat.getContactsList().setContactStatus(self)
  42. @implementer(interfaces.IGroup)
  43. class TwistedWordsGroup(basesupport.AbstractGroup):
  44. def __init__(self, name, wordsClient):
  45. basesupport.AbstractGroup.__init__(self, name, wordsClient)
  46. self.joined = 0
  47. def sendGroupMessage(self, text, metadata=None):
  48. """Return a deferred.
  49. """
  50. #for backwards compatibility with older twisted.words servers.
  51. if metadata:
  52. d=self.account.client.perspective.callRemote(
  53. 'groupMessage', self.name, text, metadata)
  54. d.addErrback(self.metadataFailed, "* "+text)
  55. return d
  56. else:
  57. return self.account.client.perspective.callRemote('groupMessage',
  58. self.name, text)
  59. def setTopic(self, text):
  60. self.account.client.perspective.callRemote(
  61. 'setGroupMetadata',
  62. {'topic': text, 'topic_author': self.client.name},
  63. self.name)
  64. def metadataFailed(self, result, text):
  65. print("result:",result,"text:",text)
  66. return self.account.client.perspective.callRemote('groupMessage',
  67. self.name, text)
  68. def joining(self):
  69. self.joined = 1
  70. def leaving(self):
  71. self.joined = 0
  72. def leave(self):
  73. return self.account.client.perspective.callRemote('leaveGroup',
  74. self.name)
  75. class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin):
  76. """In some cases, this acts as an Account, since it a source of text
  77. messages (multiple Words instances may be on a single PB connection)
  78. """
  79. def __init__(self, acct, serviceName, perspectiveName, chatui,
  80. _logonDeferred=None):
  81. self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName)
  82. self.name = perspectiveName
  83. print("HELLO I AM A PB SERVICE", serviceName, perspectiveName)
  84. self.chat = chatui
  85. self.account = acct
  86. self._logonDeferred = _logonDeferred
  87. def getPerson(self, name):
  88. return self.chat.getPerson(name, self)
  89. def getGroup(self, name):
  90. return self.chat.getGroup(name, self)
  91. def getGroupConversation(self, name):
  92. return self.chat.getGroupConversation(self.getGroup(name))
  93. def addContact(self, name):
  94. self.perspective.callRemote('addContact', name)
  95. def remote_receiveGroupMembers(self, names, group):
  96. print('received group members:', names, group)
  97. self.getGroupConversation(group).setGroupMembers(names)
  98. def remote_receiveGroupMessage(self, sender, group, message, metadata=None):
  99. print('received a group message', sender, group, message, metadata)
  100. self.getGroupConversation(group).showGroupMessage(sender, message, metadata)
  101. def remote_memberJoined(self, member, group):
  102. print('member joined', member, group)
  103. self.getGroupConversation(group).memberJoined(member)
  104. def remote_memberLeft(self, member, group):
  105. print('member left')
  106. self.getGroupConversation(group).memberLeft(member)
  107. def remote_notifyStatusChanged(self, name, status):
  108. self.chat.getPerson(name, self).setStatus(status)
  109. def remote_receiveDirectMessage(self, name, message, metadata=None):
  110. self.chat.getConversation(self.chat.getPerson(name, self)).showMessage(message, metadata)
  111. def remote_receiveContactList(self, clist):
  112. for name, status in clist:
  113. self.chat.getPerson(name, self).setStatus(status)
  114. def remote_setGroupMetadata(self, dict_, groupName):
  115. if "topic" in dict_:
  116. self.getGroupConversation(groupName).setTopic(dict_["topic"], dict_.get("topic_author", None))
  117. def joinGroup(self, name):
  118. self.getGroup(name).joining()
  119. return self.perspective.callRemote('joinGroup', name).addCallback(self._cbGroupJoined, name)
  120. def leaveGroup(self, name):
  121. self.getGroup(name).leaving()
  122. return self.perspective.callRemote('leaveGroup', name).addCallback(self._cbGroupLeft, name)
  123. def _cbGroupJoined(self, result, name):
  124. groupConv = self.chat.getGroupConversation(self.getGroup(name))
  125. groupConv.showGroupMessage("sys", "you joined")
  126. self.perspective.callRemote('getGroupMembers', name)
  127. def _cbGroupLeft(self, result, name):
  128. print('left',name)
  129. groupConv = self.chat.getGroupConversation(self.getGroup(name), 1)
  130. groupConv.showGroupMessage("sys", "you left")
  131. def connected(self, perspective):
  132. print('Connected Words Client!', perspective)
  133. if self._logonDeferred is not None:
  134. self._logonDeferred.callback(self)
  135. self.perspective = perspective
  136. self.chat.getContactsList()
  137. pbFrontEnds = {
  138. "twisted.words": TwistedWordsClient,
  139. "twisted.reality": None
  140. }
  141. @implementer(interfaces.IAccount)
  142. class PBAccount(basesupport.AbstractAccount):
  143. gatewayType = "PB"
  144. _groupFactory = TwistedWordsGroup
  145. _personFactory = TwistedWordsPerson
  146. def __init__(self, accountName, autoLogin, username, password, host, port,
  147. services=None):
  148. """
  149. @param username: The name of your PB Identity.
  150. @type username: string
  151. """
  152. basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
  153. username, password, host, port)
  154. self.services = []
  155. if not services:
  156. services = [('twisted.words', 'twisted.words', username)]
  157. for serviceType, serviceName, perspectiveName in services:
  158. self.services.append([pbFrontEnds[serviceType], serviceName,
  159. perspectiveName])
  160. def logOn(self, chatui):
  161. """
  162. @returns: this breaks with L{interfaces.IAccount}
  163. @returntype: DeferredList of L{interfaces.IClient}s
  164. """
  165. # Overriding basesupport's implementation on account of the
  166. # fact that _startLogOn tends to return a deferredList rather
  167. # than a simple Deferred, and we need to do registerAccountClient.
  168. if (not self._isConnecting) and (not self._isOnline):
  169. self._isConnecting = 1
  170. d = self._startLogOn(chatui)
  171. d.addErrback(self._loginFailed)
  172. def registerMany(results):
  173. for success, result in results:
  174. if success:
  175. chatui.registerAccountClient(result)
  176. self._cb_logOn(result)
  177. else:
  178. log.err(result)
  179. d.addCallback(registerMany)
  180. return d
  181. else:
  182. raise error.ConnectionError("Connection in progress")
  183. def _startLogOn(self, chatui):
  184. print('Connecting...', end=' ')
  185. d = pb.getObjectAt(self.host, self.port)
  186. d.addCallbacks(self._cbConnected, self._ebConnected,
  187. callbackArgs=(chatui,))
  188. return d
  189. def _cbConnected(self, root, chatui):
  190. print('Connected!')
  191. print('Identifying...', end=' ')
  192. d = pb.authIdentity(root, self.username, self.password)
  193. d.addCallbacks(self._cbIdent, self._ebConnected,
  194. callbackArgs=(chatui,))
  195. return d
  196. def _cbIdent(self, ident, chatui):
  197. if not ident:
  198. print('falsely identified.')
  199. return self._ebConnected(Failure(Exception("username or password incorrect")))
  200. print('Identified!')
  201. dl = []
  202. for handlerClass, sname, pname in self.services:
  203. d = defer.Deferred()
  204. dl.append(d)
  205. handler = handlerClass(self, sname, pname, chatui, d)
  206. ident.callRemote('attach', sname, pname, handler).addCallback(handler.connected)
  207. return defer.DeferredList(dl)
  208. def _ebConnected(self, error):
  209. print('Not connected.')
  210. return error