You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

service.py 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. # -*- test-case-name: twisted.words.test.test_service -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A module that needs a better name.
  6. Implements new cred things for words.
  7. How does this thing work?
  8. - Network connection on some port expecting to speak some protocol
  9. - Protocol-specific authentication, resulting in some kind of credentials object
  10. - twisted.cred.portal login using those credentials for the interface
  11. IUser and with something implementing IChatClient as the mind
  12. - successful login results in an IUser avatar the protocol can call
  13. methods on, and state added to the realm such that the mind will have
  14. methods called on it as is necessary
  15. - protocol specific actions lead to calls onto the avatar; remote events
  16. lead to calls onto the mind
  17. - protocol specific hangup, realm is notified, user is removed from active
  18. play, the end.
  19. """
  20. from time import time, ctime
  21. from zope.interface import implementer
  22. from twisted import copyright
  23. from twisted.cred import portal, credentials, error as ecred
  24. from twisted.internet import defer, protocol
  25. from twisted.python import log, failure, reflect
  26. from twisted.python.compat import itervalues, unicode
  27. from twisted.python.components import registerAdapter
  28. from twisted.spread import pb
  29. from twisted.words import iwords, ewords
  30. from twisted.words.protocols import irc
  31. @implementer(iwords.IGroup)
  32. class Group(object):
  33. def __init__(self, name):
  34. self.name = name
  35. self.users = {}
  36. self.meta = {
  37. "topic": "",
  38. "topic_author": "",
  39. }
  40. def _ebUserCall(self, err, p):
  41. return failure.Failure(Exception(p, err))
  42. def _cbUserCall(self, results):
  43. for (success, result) in results:
  44. if not success:
  45. user, err = result.value # XXX
  46. self.remove(user, err.getErrorMessage())
  47. def add(self, user):
  48. assert iwords.IChatClient.providedBy(user), "%r is not a chat client" % (user,)
  49. if user.name not in self.users:
  50. additions = []
  51. self.users[user.name] = user
  52. for p in itervalues(self.users):
  53. if p is not user:
  54. d = defer.maybeDeferred(p.userJoined, self, user)
  55. d.addErrback(self._ebUserCall, p=p)
  56. additions.append(d)
  57. defer.DeferredList(additions).addCallback(self._cbUserCall)
  58. return defer.succeed(None)
  59. def remove(self, user, reason=None):
  60. try:
  61. del self.users[user.name]
  62. except KeyError:
  63. pass
  64. else:
  65. removals = []
  66. for p in itervalues(self.users):
  67. if p is not user:
  68. d = defer.maybeDeferred(p.userLeft, self, user, reason)
  69. d.addErrback(self._ebUserCall, p=p)
  70. removals.append(d)
  71. defer.DeferredList(removals).addCallback(self._cbUserCall)
  72. return defer.succeed(None)
  73. def size(self):
  74. return defer.succeed(len(self.users))
  75. def receive(self, sender, recipient, message):
  76. assert recipient is self
  77. receives = []
  78. for p in itervalues(self.users):
  79. if p is not sender:
  80. d = defer.maybeDeferred(p.receive, sender, self, message)
  81. d.addErrback(self._ebUserCall, p=p)
  82. receives.append(d)
  83. defer.DeferredList(receives).addCallback(self._cbUserCall)
  84. return defer.succeed(None)
  85. def setMetadata(self, meta):
  86. self.meta = meta
  87. sets = []
  88. for p in itervalues(self.users):
  89. d = defer.maybeDeferred(p.groupMetaUpdate, self, meta)
  90. d.addErrback(self._ebUserCall, p=p)
  91. sets.append(d)
  92. defer.DeferredList(sets).addCallback(self._cbUserCall)
  93. return defer.succeed(None)
  94. def iterusers(self):
  95. # XXX Deferred?
  96. return iter(self.users.values())
  97. @implementer(iwords.IUser)
  98. class User(object):
  99. realm = None
  100. mind = None
  101. def __init__(self, name):
  102. self.name = name
  103. self.groups = []
  104. self.lastMessage = time()
  105. def loggedIn(self, realm, mind):
  106. self.realm = realm
  107. self.mind = mind
  108. self.signOn = time()
  109. def join(self, group):
  110. def cbJoin(result):
  111. self.groups.append(group)
  112. return result
  113. return group.add(self.mind).addCallback(cbJoin)
  114. def leave(self, group, reason=None):
  115. def cbLeave(result):
  116. self.groups.remove(group)
  117. return result
  118. return group.remove(self.mind, reason).addCallback(cbLeave)
  119. def send(self, recipient, message):
  120. self.lastMessage = time()
  121. return recipient.receive(self.mind, recipient, message)
  122. def itergroups(self):
  123. return iter(self.groups)
  124. def logout(self):
  125. for g in self.groups[:]:
  126. self.leave(g)
  127. NICKSERV = 'NickServ!NickServ@services'
  128. @implementer(iwords.IChatClient)
  129. class IRCUser(irc.IRC):
  130. """
  131. Protocol instance representing an IRC user connected to the server.
  132. """
  133. # A list of IGroups in which I am participating
  134. groups = None
  135. # A no-argument callable I should invoke when I go away
  136. logout = None
  137. # An IUser we use to interact with the chat service
  138. avatar = None
  139. # To whence I belong
  140. realm = None
  141. # How to handle unicode (TODO: Make this customizable on a per-user basis)
  142. encoding = 'utf-8'
  143. # Twisted callbacks
  144. def connectionMade(self):
  145. self.irc_PRIVMSG = self.irc_NICKSERV_PRIVMSG
  146. self.realm = self.factory.realm
  147. self.hostname = self.realm.name
  148. def connectionLost(self, reason):
  149. if self.logout is not None:
  150. self.logout()
  151. self.avatar = None
  152. # Make sendMessage a bit more useful to us
  153. def sendMessage(self, command, *parameter_list, **kw):
  154. if 'prefix' not in kw:
  155. kw['prefix'] = self.hostname
  156. if 'to' not in kw:
  157. kw['to'] = self.name.encode(self.encoding)
  158. arglist = [self, command, kw['to']] + list(parameter_list)
  159. arglistUnicode = []
  160. for arg in arglist:
  161. if isinstance(arg, bytes):
  162. arg = arg.decode("utf-8")
  163. arglistUnicode.append(arg)
  164. irc.IRC.sendMessage(*arglistUnicode, **kw)
  165. # IChatClient implementation
  166. def userJoined(self, group, user):
  167. self.join(
  168. "%s!%s@%s" % (user.name, user.name, self.hostname),
  169. '#' + group.name)
  170. def userLeft(self, group, user, reason=None):
  171. self.part(
  172. "%s!%s@%s" % (user.name, user.name, self.hostname),
  173. '#' + group.name,
  174. (reason or u"leaving"))
  175. def receive(self, sender, recipient, message):
  176. #>> :glyph!glyph@adsl-64-123-27-108.dsl.austtx.swbell.net PRIVMSG glyph_ :hello
  177. # omg???????????
  178. if iwords.IGroup.providedBy(recipient):
  179. recipientName = '#' + recipient.name
  180. else:
  181. recipientName = recipient.name
  182. text = message.get('text', '<an unrepresentable message>')
  183. for L in text.splitlines():
  184. self.privmsg(
  185. '%s!%s@%s' % (sender.name, sender.name, self.hostname),
  186. recipientName,
  187. L)
  188. def groupMetaUpdate(self, group, meta):
  189. if 'topic' in meta:
  190. topic = meta['topic']
  191. author = meta.get('topic_author', '')
  192. self.topic(
  193. self.name,
  194. '#' + group.name,
  195. topic,
  196. '%s!%s@%s' % (author, author, self.hostname)
  197. )
  198. # irc.IRC callbacks - starting with login related stuff.
  199. nickname = None
  200. password = None
  201. def irc_PASS(self, prefix, params):
  202. """
  203. Password message -- Register a password.
  204. Parameters: <password>
  205. [REQUIRED]
  206. Note that IRC requires the client send this *before* NICK
  207. and USER.
  208. """
  209. self.password = params[-1]
  210. def irc_NICK(self, prefix, params):
  211. """
  212. Nick message -- Set your nickname.
  213. Parameters: <nickname>
  214. [REQUIRED]
  215. """
  216. nickname = params[0]
  217. try:
  218. if isinstance(nickname, bytes):
  219. nickname = nickname.decode(self.encoding)
  220. except UnicodeDecodeError:
  221. self.privmsg(
  222. NICKSERV,
  223. repr(nickname),
  224. 'Your nickname cannot be decoded. Please use ASCII or UTF-8.')
  225. self.transport.loseConnection()
  226. return
  227. self.nickname = nickname
  228. self.name = nickname
  229. for code, text in self._motdMessages:
  230. self.sendMessage(code, text % self.factory._serverInfo)
  231. if self.password is None:
  232. self.privmsg(
  233. NICKSERV,
  234. nickname,
  235. 'Password?')
  236. else:
  237. password = self.password
  238. self.password = None
  239. self.logInAs(nickname, password)
  240. def irc_USER(self, prefix, params):
  241. """
  242. User message -- Set your realname.
  243. Parameters: <user> <mode> <unused> <realname>
  244. """
  245. # Note: who gives a crap about this? The IUser has the real
  246. # information we care about. Save it anyway, I guess, just
  247. # for fun.
  248. self.realname = params[-1]
  249. def irc_NICKSERV_PRIVMSG(self, prefix, params):
  250. """
  251. Send a (private) message.
  252. Parameters: <msgtarget> <text to be sent>
  253. """
  254. target = params[0]
  255. password = params[-1]
  256. if self.nickname is None:
  257. # XXX Send an error response here
  258. self.transport.loseConnection()
  259. elif target.lower() != "nickserv":
  260. self.privmsg(
  261. NICKSERV,
  262. self.nickname,
  263. "Denied. Please send me (NickServ) your password.")
  264. else:
  265. nickname = self.nickname
  266. self.nickname = None
  267. self.logInAs(nickname, password)
  268. def logInAs(self, nickname, password):
  269. d = self.factory.portal.login(
  270. credentials.UsernamePassword(nickname, password),
  271. self,
  272. iwords.IUser)
  273. d.addCallbacks(self._cbLogin, self._ebLogin, errbackArgs=(nickname,))
  274. _welcomeMessages = [
  275. (irc.RPL_WELCOME,
  276. ":connected to Twisted IRC"),
  277. (irc.RPL_YOURHOST,
  278. ":Your host is %(serviceName)s, running version %(serviceVersion)s"),
  279. (irc.RPL_CREATED,
  280. ":This server was created on %(creationDate)s"),
  281. # "Bummer. This server returned a worthless 004 numeric.
  282. # I'll have to guess at all the values"
  283. # -- epic
  284. (irc.RPL_MYINFO,
  285. # w and n are the currently supported channel and user modes
  286. # -- specify this better
  287. "%(serviceName)s %(serviceVersion)s w n")
  288. ]
  289. _motdMessages = [
  290. (irc.RPL_MOTDSTART,
  291. ":- %(serviceName)s Message of the Day - "),
  292. (irc.RPL_ENDOFMOTD,
  293. ":End of /MOTD command.")
  294. ]
  295. def _cbLogin(self, result):
  296. (iface, avatar, logout) = result
  297. assert iface is iwords.IUser, "Realm is buggy, got %r" % (iface,)
  298. # Let them send messages to the world
  299. del self.irc_PRIVMSG
  300. self.avatar = avatar
  301. self.logout = logout
  302. for code, text in self._welcomeMessages:
  303. self.sendMessage(code, text % self.factory._serverInfo)
  304. def _ebLogin(self, err, nickname):
  305. if err.check(ewords.AlreadyLoggedIn):
  306. self.privmsg(
  307. NICKSERV,
  308. nickname,
  309. "Already logged in. No pod people allowed!")
  310. elif err.check(ecred.UnauthorizedLogin):
  311. self.privmsg(
  312. NICKSERV,
  313. nickname,
  314. "Login failed. Goodbye.")
  315. else:
  316. log.msg("Unhandled error during login:")
  317. log.err(err)
  318. self.privmsg(
  319. NICKSERV,
  320. nickname,
  321. "Server error during login. Sorry.")
  322. self.transport.loseConnection()
  323. # Great, now that's out of the way, here's some of the interesting
  324. # bits
  325. def irc_PING(self, prefix, params):
  326. """
  327. Ping message
  328. Parameters: <server1> [ <server2> ]
  329. """
  330. if self.realm is not None:
  331. self.sendMessage('PONG', self.hostname)
  332. def irc_QUIT(self, prefix, params):
  333. """
  334. Quit
  335. Parameters: [ <Quit Message> ]
  336. """
  337. self.transport.loseConnection()
  338. def _channelMode(self, group, modes=None, *args):
  339. if modes:
  340. self.sendMessage(
  341. irc.ERR_UNKNOWNMODE,
  342. ":Unknown MODE flag.")
  343. else:
  344. self.channelMode(self.name, '#' + group.name, '+')
  345. def _userMode(self, user, modes=None):
  346. if modes:
  347. self.sendMessage(
  348. irc.ERR_UNKNOWNMODE,
  349. ":Unknown MODE flag.")
  350. elif user is self.avatar:
  351. self.sendMessage(
  352. irc.RPL_UMODEIS,
  353. "+")
  354. else:
  355. self.sendMessage(
  356. irc.ERR_USERSDONTMATCH,
  357. ":You can't look at someone else's modes.")
  358. def irc_MODE(self, prefix, params):
  359. """
  360. User mode message
  361. Parameters: <nickname>
  362. *( ( "+" / "-" ) *( "i" / "w" / "o" / "O" / "r" ) )
  363. """
  364. try:
  365. channelOrUser = params[0]
  366. if isinstance(channelOrUser, bytes):
  367. channelOrUser = channelOrUser.decode(self.encoding)
  368. except UnicodeDecodeError:
  369. self.sendMessage(
  370. irc.ERR_NOSUCHNICK, params[0],
  371. ":No such nickname (could not decode your unicode!)")
  372. return
  373. if channelOrUser.startswith('#'):
  374. def ebGroup(err):
  375. err.trap(ewords.NoSuchGroup)
  376. self.sendMessage(
  377. irc.ERR_NOSUCHCHANNEL, params[0],
  378. ":That channel doesn't exist.")
  379. d = self.realm.lookupGroup(channelOrUser[1:])
  380. d.addCallbacks(
  381. self._channelMode,
  382. ebGroup,
  383. callbackArgs=tuple(params[1:]))
  384. else:
  385. def ebUser(err):
  386. self.sendMessage(
  387. irc.ERR_NOSUCHNICK,
  388. ":No such nickname.")
  389. d = self.realm.lookupUser(channelOrUser)
  390. d.addCallbacks(
  391. self._userMode,
  392. ebUser,
  393. callbackArgs=tuple(params[1:]))
  394. def irc_USERHOST(self, prefix, params):
  395. """
  396. Userhost message
  397. Parameters: <nickname> *( SPACE <nickname> )
  398. [Optional]
  399. """
  400. pass
  401. def irc_PRIVMSG(self, prefix, params):
  402. """
  403. Send a (private) message.
  404. Parameters: <msgtarget> <text to be sent>
  405. """
  406. try:
  407. targetName = params[0]
  408. if isinstance(targetName, bytes):
  409. targetName = targetName.decode(self.encoding)
  410. except UnicodeDecodeError:
  411. self.sendMessage(
  412. irc.ERR_NOSUCHNICK, params[0],
  413. ":No such nick/channel (could not decode your unicode!)")
  414. return
  415. messageText = params[-1]
  416. if targetName.startswith('#'):
  417. target = self.realm.lookupGroup(targetName[1:])
  418. else:
  419. target = self.realm.lookupUser(targetName).addCallback(lambda user: user.mind)
  420. def cbTarget(targ):
  421. if targ is not None:
  422. return self.avatar.send(targ, {"text": messageText})
  423. def ebTarget(err):
  424. self.sendMessage(
  425. irc.ERR_NOSUCHNICK, targetName,
  426. ":No such nick/channel.")
  427. target.addCallbacks(cbTarget, ebTarget)
  428. def irc_JOIN(self, prefix, params):
  429. """
  430. Join message
  431. Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] )
  432. """
  433. try:
  434. groupName = params[0]
  435. if isinstance(groupName, bytes):
  436. groupName = groupName.decode(self.encoding)
  437. except UnicodeDecodeError:
  438. self.sendMessage(
  439. irc.ERR_NOSUCHCHANNEL, params[0],
  440. ":No such channel (could not decode your unicode!)")
  441. return
  442. if groupName.startswith('#'):
  443. groupName = groupName[1:]
  444. def cbGroup(group):
  445. def cbJoin(ign):
  446. self.userJoined(group, self)
  447. self.names(
  448. self.name,
  449. '#' + group.name,
  450. [user.name for user in group.iterusers()])
  451. self._sendTopic(group)
  452. return self.avatar.join(group).addCallback(cbJoin)
  453. def ebGroup(err):
  454. self.sendMessage(
  455. irc.ERR_NOSUCHCHANNEL, '#' + groupName,
  456. ":No such channel.")
  457. self.realm.getGroup(groupName).addCallbacks(cbGroup, ebGroup)
  458. def irc_PART(self, prefix, params):
  459. """
  460. Part message
  461. Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
  462. """
  463. try:
  464. groupName = params[0]
  465. if isinstance(params[0], bytes):
  466. groupName = params[0].decode(self.encoding)
  467. except UnicodeDecodeError:
  468. self.sendMessage(
  469. irc.ERR_NOTONCHANNEL, params[0],
  470. ":Could not decode your unicode!")
  471. return
  472. if groupName.startswith('#'):
  473. groupName = groupName[1:]
  474. if len(params) > 1:
  475. reason = params[1]
  476. if isinstance(reason, bytes):
  477. reason = reason.decode('utf-8')
  478. else:
  479. reason = None
  480. def cbGroup(group):
  481. def cbLeave(result):
  482. self.userLeft(group, self, reason)
  483. return self.avatar.leave(group, reason).addCallback(cbLeave)
  484. def ebGroup(err):
  485. err.trap(ewords.NoSuchGroup)
  486. self.sendMessage(
  487. irc.ERR_NOTONCHANNEL,
  488. '#' + groupName,
  489. ":" + err.getErrorMessage())
  490. self.realm.lookupGroup(groupName).addCallbacks(cbGroup, ebGroup)
  491. def irc_NAMES(self, prefix, params):
  492. """
  493. Names message
  494. Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
  495. """
  496. #<< NAMES #python
  497. #>> :benford.openprojects.net 353 glyph = #python :Orban ... @glyph ... Zymurgy skreech
  498. #>> :benford.openprojects.net 366 glyph #python :End of /NAMES list.
  499. try:
  500. channel = params[-1]
  501. if isinstance(channel, bytes):
  502. channel = channel.decode(self.encoding)
  503. except UnicodeDecodeError:
  504. self.sendMessage(
  505. irc.ERR_NOSUCHCHANNEL, params[-1],
  506. ":No such channel (could not decode your unicode!)")
  507. return
  508. if channel.startswith('#'):
  509. channel = channel[1:]
  510. def cbGroup(group):
  511. self.names(
  512. self.name,
  513. '#' + group.name,
  514. [user.name for user in group.iterusers()])
  515. def ebGroup(err):
  516. err.trap(ewords.NoSuchGroup)
  517. # No group? Fine, no names!
  518. self.names(
  519. self.name,
  520. '#' + channel,
  521. [])
  522. self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup)
  523. def irc_TOPIC(self, prefix, params):
  524. """
  525. Topic message
  526. Parameters: <channel> [ <topic> ]
  527. """
  528. try:
  529. channel = params[0]
  530. if isinstance(params[0], bytes):
  531. channel = channel.decode(self.encoding)
  532. except UnicodeDecodeError:
  533. self.sendMessage(
  534. irc.ERR_NOSUCHCHANNEL,
  535. ":That channel doesn't exist (could not decode your unicode!)")
  536. return
  537. if channel.startswith('#'):
  538. channel = channel[1:]
  539. if len(params) > 1:
  540. self._setTopic(channel, params[1])
  541. else:
  542. self._getTopic(channel)
  543. def _sendTopic(self, group):
  544. """
  545. Send the topic of the given group to this user, if it has one.
  546. """
  547. topic = group.meta.get("topic")
  548. if topic:
  549. author = group.meta.get("topic_author") or "<noone>"
  550. date = group.meta.get("topic_date", 0)
  551. self.topic(self.name, '#' + group.name, topic)
  552. self.topicAuthor(self.name, '#' + group.name, author, date)
  553. def _getTopic(self, channel):
  554. #<< TOPIC #python
  555. #>> :benford.openprojects.net 332 glyph #python :<churchr> I really did. I sprained all my toes.
  556. #>> :benford.openprojects.net 333 glyph #python itamar|nyc 994713482
  557. def ebGroup(err):
  558. err.trap(ewords.NoSuchGroup)
  559. self.sendMessage(
  560. irc.ERR_NOSUCHCHANNEL, '=', channel,
  561. ":That channel doesn't exist.")
  562. self.realm.lookupGroup(channel).addCallbacks(self._sendTopic, ebGroup)
  563. def _setTopic(self, channel, topic):
  564. #<< TOPIC #divunal :foo
  565. #>> :glyph!glyph@adsl-64-123-27-108.dsl.austtx.swbell.net TOPIC #divunal :foo
  566. def cbGroup(group):
  567. newMeta = group.meta.copy()
  568. newMeta['topic'] = topic
  569. newMeta['topic_author'] = self.name
  570. newMeta['topic_date'] = int(time())
  571. def ebSet(err):
  572. self.sendMessage(
  573. irc.ERR_CHANOPRIVSNEEDED,
  574. "#" + group.name,
  575. ":You need to be a channel operator to do that.")
  576. return group.setMetadata(newMeta).addErrback(ebSet)
  577. def ebGroup(err):
  578. err.trap(ewords.NoSuchGroup)
  579. self.sendMessage(
  580. irc.ERR_NOSUCHCHANNEL, '=', channel,
  581. ":That channel doesn't exist.")
  582. self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup)
  583. def list(self, channels):
  584. """
  585. Send a group of LIST response lines
  586. @type channel: C{list} of C{(str, int, str)}
  587. @param channel: Information about the channels being sent:
  588. their name, the number of participants, and their topic.
  589. """
  590. for (name, size, topic) in channels:
  591. self.sendMessage(irc.RPL_LIST, name, str(size), ":" + topic)
  592. self.sendMessage(irc.RPL_LISTEND, ":End of /LIST")
  593. def irc_LIST(self, prefix, params):
  594. """
  595. List query
  596. Return information about the indicated channels, or about all
  597. channels if none are specified.
  598. Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
  599. """
  600. #<< list #python
  601. #>> :orwell.freenode.net 321 exarkun Channel :Users Name
  602. #>> :orwell.freenode.net 322 exarkun #python 358 :The Python programming language
  603. #>> :orwell.freenode.net 323 exarkun :End of /LIST
  604. if params:
  605. # Return information about indicated channels
  606. try:
  607. allChannels = params[0]
  608. if isinstance(allChannels, bytes):
  609. allChannels = allChannels.decode(self.encoding)
  610. channels = allChannels.split(',')
  611. except UnicodeDecodeError:
  612. self.sendMessage(
  613. irc.ERR_NOSUCHCHANNEL, params[0],
  614. ":No such channel (could not decode your unicode!)")
  615. return
  616. groups = []
  617. for ch in channels:
  618. if ch.startswith('#'):
  619. ch = ch[1:]
  620. groups.append(self.realm.lookupGroup(ch))
  621. groups = defer.DeferredList(groups, consumeErrors=True)
  622. groups.addCallback(lambda gs: [r for (s, r) in gs if s])
  623. else:
  624. # Return information about all channels
  625. groups = self.realm.itergroups()
  626. def cbGroups(groups):
  627. def gotSize(size, group):
  628. return group.name, size, group.meta.get('topic')
  629. d = defer.DeferredList([
  630. group.size().addCallback(gotSize, group) for group in groups])
  631. d.addCallback(lambda results: self.list([r for (s, r) in results if s]))
  632. return d
  633. groups.addCallback(cbGroups)
  634. def _channelWho(self, group):
  635. self.who(self.name, '#' + group.name,
  636. [(m.name, self.hostname, self.realm.name, m.name, "H", 0, m.name) for m in group.iterusers()])
  637. def _userWho(self, user):
  638. self.sendMessage(irc.RPL_ENDOFWHO,
  639. ":User /WHO not implemented")
  640. def irc_WHO(self, prefix, params):
  641. """
  642. Who query
  643. Parameters: [ <mask> [ "o" ] ]
  644. """
  645. #<< who #python
  646. #>> :x.opn 352 glyph #python aquarius pc-62-31-193-114-du.blueyonder.co.uk y.opn Aquarius H :3 Aquarius
  647. # ...
  648. #>> :x.opn 352 glyph #python foobar europa.tranquility.net z.opn skreech H :0 skreech
  649. #>> :x.opn 315 glyph #python :End of /WHO list.
  650. ### also
  651. #<< who glyph
  652. #>> :x.opn 352 glyph #python glyph adsl-64-123-27-108.dsl.austtx.swbell.net x.opn glyph H :0 glyph
  653. #>> :x.opn 315 glyph glyph :End of /WHO list.
  654. if not params:
  655. self.sendMessage(irc.RPL_ENDOFWHO, ":/WHO not supported.")
  656. return
  657. try:
  658. channelOrUser = params[0]
  659. if isinstance(channelOrUser, bytes):
  660. channelOrUser = channelOrUser.decode(self.encoding)
  661. except UnicodeDecodeError:
  662. self.sendMessage(
  663. irc.RPL_ENDOFWHO, params[0],
  664. ":End of /WHO list (could not decode your unicode!)")
  665. return
  666. if channelOrUser.startswith('#'):
  667. def ebGroup(err):
  668. err.trap(ewords.NoSuchGroup)
  669. self.sendMessage(
  670. irc.RPL_ENDOFWHO, channelOrUser,
  671. ":End of /WHO list.")
  672. d = self.realm.lookupGroup(channelOrUser[1:])
  673. d.addCallbacks(self._channelWho, ebGroup)
  674. else:
  675. def ebUser(err):
  676. err.trap(ewords.NoSuchUser)
  677. self.sendMessage(
  678. irc.RPL_ENDOFWHO, channelOrUser,
  679. ":End of /WHO list.")
  680. d = self.realm.lookupUser(channelOrUser)
  681. d.addCallbacks(self._userWho, ebUser)
  682. def irc_WHOIS(self, prefix, params):
  683. """
  684. Whois query
  685. Parameters: [ <target> ] <mask> *( "," <mask> )
  686. """
  687. def cbUser(user):
  688. self.whois(
  689. self.name,
  690. user.name, user.name, self.realm.name,
  691. user.name, self.realm.name, 'Hi mom!', False,
  692. int(time() - user.lastMessage), user.signOn,
  693. ['#' + group.name for group in user.itergroups()])
  694. def ebUser(err):
  695. err.trap(ewords.NoSuchUser)
  696. self.sendMessage(
  697. irc.ERR_NOSUCHNICK,
  698. params[0],
  699. ":No such nick/channel")
  700. try:
  701. user = params[0]
  702. if isinstance(user, bytes):
  703. user = user.decode(self.encoding)
  704. except UnicodeDecodeError:
  705. self.sendMessage(
  706. irc.ERR_NOSUCHNICK,
  707. params[0],
  708. ":No such nick/channel")
  709. return
  710. self.realm.lookupUser(user).addCallbacks(cbUser, ebUser)
  711. # Unsupported commands, here for legacy compatibility
  712. def irc_OPER(self, prefix, params):
  713. """
  714. Oper message
  715. Parameters: <name> <password>
  716. """
  717. self.sendMessage(irc.ERR_NOOPERHOST, ":O-lines not applicable")
  718. class IRCFactory(protocol.ServerFactory):
  719. """
  720. IRC server that creates instances of the L{IRCUser} protocol.
  721. @ivar _serverInfo: A dictionary mapping:
  722. "serviceName" to the name of the server,
  723. "serviceVersion" to the copyright version,
  724. "creationDate" to the time that the server was started.
  725. """
  726. protocol = IRCUser
  727. def __init__(self, realm, portal):
  728. self.realm = realm
  729. self.portal = portal
  730. self._serverInfo = {
  731. "serviceName": self.realm.name,
  732. "serviceVersion": copyright.version,
  733. "creationDate": ctime()
  734. }
  735. class PBMind(pb.Referenceable):
  736. def __init__(self):
  737. pass
  738. def jellyFor(self, jellier):
  739. qual = reflect.qual(PBMind)
  740. if isinstance(qual, unicode):
  741. qual = qual.encode("utf-8")
  742. return qual, jellier.invoker.registerReference(self)
  743. def remote_userJoined(self, user, group):
  744. pass
  745. def remote_userLeft(self, user, group, reason):
  746. pass
  747. def remote_receive(self, sender, recipient, message):
  748. pass
  749. def remote_groupMetaUpdate(self, group, meta):
  750. pass
  751. @implementer(iwords.IChatClient)
  752. class PBMindReference(pb.RemoteReference):
  753. def receive(self, sender, recipient, message):
  754. if iwords.IGroup.providedBy(recipient):
  755. rec = PBGroup(self.realm, self.avatar, recipient)
  756. else:
  757. rec = PBUser(self.realm, self.avatar, recipient)
  758. return self.callRemote(
  759. 'receive',
  760. PBUser(self.realm, self.avatar, sender),
  761. rec,
  762. message)
  763. def groupMetaUpdate(self, group, meta):
  764. return self.callRemote(
  765. 'groupMetaUpdate',
  766. PBGroup(self.realm, self.avatar, group),
  767. meta)
  768. def userJoined(self, group, user):
  769. return self.callRemote(
  770. 'userJoined',
  771. PBGroup(self.realm, self.avatar, group),
  772. PBUser(self.realm, self.avatar, user))
  773. def userLeft(self, group, user, reason=None):
  774. return self.callRemote(
  775. 'userLeft',
  776. PBGroup(self.realm, self.avatar, group),
  777. PBUser(self.realm, self.avatar, user),
  778. reason)
  779. pb.setUnjellyableForClass(PBMind, PBMindReference)
  780. class PBGroup(pb.Referenceable):
  781. def __init__(self, realm, avatar, group):
  782. self.realm = realm
  783. self.avatar = avatar
  784. self.group = group
  785. def processUniqueID(self):
  786. return hash((self.realm.name, self.avatar.name, self.group.name))
  787. def jellyFor(self, jellier):
  788. qual = reflect.qual(self.__class__)
  789. if isinstance(qual, unicode):
  790. qual = qual.encode("utf-8")
  791. group = self.group.name
  792. if isinstance(group, unicode):
  793. group = group.encode("utf-8")
  794. return qual, group, jellier.invoker.registerReference(self)
  795. def remote_leave(self, reason=None):
  796. return self.avatar.leave(self.group, reason)
  797. def remote_send(self, message):
  798. return self.avatar.send(self.group, message)
  799. @implementer(iwords.IGroup)
  800. class PBGroupReference(pb.RemoteReference):
  801. def unjellyFor(self, unjellier, unjellyList):
  802. clsName, name, ref = unjellyList
  803. self.name = name
  804. if bytes != str and isinstance(self.name, bytes):
  805. self.name = self.name.decode('utf-8')
  806. return pb.RemoteReference.unjellyFor(self, unjellier, [clsName, ref])
  807. def leave(self, reason=None):
  808. return self.callRemote("leave", reason)
  809. def send(self, message):
  810. return self.callRemote("send", message)
  811. pb.setUnjellyableForClass(PBGroup, PBGroupReference)
  812. class PBUser(pb.Referenceable):
  813. def __init__(self, realm, avatar, user):
  814. self.realm = realm
  815. self.avatar = avatar
  816. self.user = user
  817. def processUniqueID(self):
  818. return hash((self.realm.name, self.avatar.name, self.user.name))
  819. @implementer(iwords.IChatClient)
  820. class ChatAvatar(pb.Referenceable):
  821. def __init__(self, avatar):
  822. self.avatar = avatar
  823. def jellyFor(self, jellier):
  824. qual = reflect.qual(self.__class__)
  825. if isinstance(qual, unicode):
  826. qual = qual.encode("utf-8")
  827. return qual, jellier.invoker.registerReference(self)
  828. def remote_join(self, groupName):
  829. def cbGroup(group):
  830. def cbJoin(ignored):
  831. return PBGroup(self.avatar.realm, self.avatar, group)
  832. d = self.avatar.join(group)
  833. d.addCallback(cbJoin)
  834. return d
  835. d = self.avatar.realm.getGroup(groupName)
  836. d.addCallback(cbGroup)
  837. return d
  838. registerAdapter(ChatAvatar, iwords.IUser, pb.IPerspective)
  839. class AvatarReference(pb.RemoteReference):
  840. def join(self, groupName):
  841. return self.callRemote('join', groupName)
  842. def quit(self):
  843. d = defer.Deferred()
  844. self.broker.notifyOnDisconnect(lambda: d.callback(None))
  845. self.broker.transport.loseConnection()
  846. return d
  847. pb.setUnjellyableForClass(ChatAvatar, AvatarReference)
  848. @implementer(portal.IRealm, iwords.IChatService)
  849. class WordsRealm(object):
  850. _encoding = 'utf-8'
  851. def __init__(self, name):
  852. self.name = name
  853. def userFactory(self, name):
  854. return User(name)
  855. def groupFactory(self, name):
  856. return Group(name)
  857. def logoutFactory(self, avatar, facet):
  858. def logout():
  859. # XXX Deferred support here
  860. getattr(facet, 'logout', lambda: None)()
  861. avatar.realm = avatar.mind = None
  862. return logout
  863. def requestAvatar(self, avatarId, mind, *interfaces):
  864. if isinstance(avatarId, bytes):
  865. avatarId = avatarId.decode(self._encoding)
  866. def gotAvatar(avatar):
  867. if avatar.realm is not None:
  868. raise ewords.AlreadyLoggedIn()
  869. for iface in interfaces:
  870. facet = iface(avatar, None)
  871. if facet is not None:
  872. avatar.loggedIn(self, mind)
  873. mind.name = avatarId
  874. mind.realm = self
  875. mind.avatar = avatar
  876. return iface, facet, self.logoutFactory(avatar, facet)
  877. raise NotImplementedError(self, interfaces)
  878. return self.getUser(avatarId).addCallback(gotAvatar)
  879. # IChatService, mostly.
  880. createGroupOnRequest = False
  881. createUserOnRequest = True
  882. def lookupUser(self, name):
  883. raise NotImplementedError
  884. def lookupGroup(self, group):
  885. raise NotImplementedError
  886. def addUser(self, user):
  887. """
  888. Add the given user to this service.
  889. This is an internal method intended to be overridden by
  890. L{WordsRealm} subclasses, not called by external code.
  891. @type user: L{IUser}
  892. @rtype: L{twisted.internet.defer.Deferred}
  893. @return: A Deferred which fires with L{None} when the user is
  894. added, or which fails with
  895. L{twisted.words.ewords.DuplicateUser} if a user with the
  896. same name exists already.
  897. """
  898. raise NotImplementedError
  899. def addGroup(self, group):
  900. """
  901. Add the given group to this service.
  902. @type group: L{IGroup}
  903. @rtype: L{twisted.internet.defer.Deferred}
  904. @return: A Deferred which fires with L{None} when the group is
  905. added, or which fails with
  906. L{twisted.words.ewords.DuplicateGroup} if a group with the
  907. same name exists already.
  908. """
  909. raise NotImplementedError
  910. def getGroup(self, name):
  911. if self.createGroupOnRequest:
  912. def ebGroup(err):
  913. err.trap(ewords.DuplicateGroup)
  914. return self.lookupGroup(name)
  915. return self.createGroup(name).addErrback(ebGroup)
  916. return self.lookupGroup(name)
  917. def getUser(self, name):
  918. if self.createUserOnRequest:
  919. def ebUser(err):
  920. err.trap(ewords.DuplicateUser)
  921. return self.lookupUser(name)
  922. return self.createUser(name).addErrback(ebUser)
  923. return self.lookupUser(name)
  924. def createUser(self, name):
  925. def cbLookup(user):
  926. return failure.Failure(ewords.DuplicateUser(name))
  927. def ebLookup(err):
  928. err.trap(ewords.NoSuchUser)
  929. return self.userFactory(name)
  930. name = name.lower()
  931. d = self.lookupUser(name)
  932. d.addCallbacks(cbLookup, ebLookup)
  933. d.addCallback(self.addUser)
  934. return d
  935. def createGroup(self, name):
  936. def cbLookup(group):
  937. return failure.Failure(ewords.DuplicateGroup(name))
  938. def ebLookup(err):
  939. err.trap(ewords.NoSuchGroup)
  940. return self.groupFactory(name)
  941. name = name.lower()
  942. d = self.lookupGroup(name)
  943. d.addCallbacks(cbLookup, ebLookup)
  944. d.addCallback(self.addGroup)
  945. return d
  946. class InMemoryWordsRealm(WordsRealm):
  947. def __init__(self, *a, **kw):
  948. super(InMemoryWordsRealm, self).__init__(*a, **kw)
  949. self.users = {}
  950. self.groups = {}
  951. def itergroups(self):
  952. return defer.succeed(itervalues(self.groups))
  953. def addUser(self, user):
  954. if user.name in self.users:
  955. return defer.fail(failure.Failure(ewords.DuplicateUser()))
  956. self.users[user.name] = user
  957. return defer.succeed(user)
  958. def addGroup(self, group):
  959. if group.name in self.groups:
  960. return defer.fail(failure.Failure(ewords.DuplicateGroup()))
  961. self.groups[group.name] = group
  962. return defer.succeed(group)
  963. def lookupUser(self, name):
  964. name = name.lower()
  965. try:
  966. user = self.users[name]
  967. except KeyError:
  968. return defer.fail(failure.Failure(ewords.NoSuchUser(name)))
  969. else:
  970. return defer.succeed(user)
  971. def lookupGroup(self, name):
  972. name = name.lower()
  973. try:
  974. group = self.groups[name]
  975. except KeyError:
  976. return defer.fail(failure.Failure(ewords.NoSuchGroup(name)))
  977. else:
  978. return defer.succeed(group)
  979. __all__ = [
  980. 'Group', 'User',
  981. 'WordsRealm', 'InMemoryWordsRealm',
  982. ]