Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 38KB

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