1
0

test_messaging.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ This is an example of using the server to server implementation to do a
  16. basic chat style thing. It accepts commands from stdin and outputs to stdout.
  17. It assumes that ucids are of the form <user>@<domain>, and uses <domain> as
  18. the address of the remote home server to hit.
  19. Usage:
  20. python test_messaging.py <port>
  21. Currently assumes the local address is localhost:<port>
  22. """
  23. import argparse
  24. import curses.wrapper
  25. import json
  26. import logging
  27. import os
  28. import re
  29. import cursesio
  30. from twisted.internet import defer, reactor
  31. from twisted.python import log
  32. from synapse.app.homeserver import SynapseHomeServer
  33. from synapse.federation import ReplicationHandler
  34. from synapse.federation.units import Pdu
  35. from synapse.util import origin_from_ucid
  36. # from synapse.logging.utils import log_function
  37. logger = logging.getLogger("example")
  38. def excpetion_errback(failure):
  39. logging.exception(failure)
  40. class InputOutput:
  41. """ This is responsible for basic I/O so that a user can interact with
  42. the example app.
  43. """
  44. def __init__(self, screen, user):
  45. self.screen = screen
  46. self.user = user
  47. def set_home_server(self, server):
  48. self.server = server
  49. def on_line(self, line):
  50. """ This is where we process commands.
  51. """
  52. try:
  53. m = re.match(r"^join (\S+)$", line)
  54. if m:
  55. # The `sender` wants to join a room.
  56. (room_name,) = m.groups()
  57. self.print_line("%s joining %s" % (self.user, room_name))
  58. self.server.join_room(room_name, self.user, self.user)
  59. # self.print_line("OK.")
  60. return
  61. m = re.match(r"^invite (\S+) (\S+)$", line)
  62. if m:
  63. # `sender` wants to invite someone to a room
  64. room_name, invitee = m.groups()
  65. self.print_line("%s invited to %s" % (invitee, room_name))
  66. self.server.invite_to_room(room_name, self.user, invitee)
  67. # self.print_line("OK.")
  68. return
  69. m = re.match(r"^send (\S+) (.*)$", line)
  70. if m:
  71. # `sender` wants to message a room
  72. room_name, body = m.groups()
  73. self.print_line("%s send to %s" % (self.user, room_name))
  74. self.server.send_message(room_name, self.user, body)
  75. # self.print_line("OK.")
  76. return
  77. m = re.match(r"^backfill (\S+)$", line)
  78. if m:
  79. # we want to backfill a room
  80. (room_name,) = m.groups()
  81. self.print_line("backfill %s" % room_name)
  82. self.server.backfill(room_name)
  83. return
  84. self.print_line("Unrecognized command")
  85. except Exception as e:
  86. logger.exception(e)
  87. def print_line(self, text):
  88. self.screen.print_line(text)
  89. def print_log(self, text):
  90. self.screen.print_log(text)
  91. class IOLoggerHandler(logging.Handler):
  92. def __init__(self, io):
  93. logging.Handler.__init__(self)
  94. self.io = io
  95. def emit(self, record):
  96. if record.levelno < logging.WARN:
  97. return
  98. msg = self.format(record)
  99. self.io.print_log(msg)
  100. class Room:
  101. """ Used to store (in memory) the current membership state of a room, and
  102. which home servers we should send PDUs associated with the room to.
  103. """
  104. def __init__(self, room_name):
  105. self.room_name = room_name
  106. self.invited = set()
  107. self.participants = set()
  108. self.servers = set()
  109. self.oldest_server = None
  110. self.have_got_metadata = False
  111. def add_participant(self, participant):
  112. """ Someone has joined the room
  113. """
  114. self.participants.add(participant)
  115. self.invited.discard(participant)
  116. server = origin_from_ucid(participant)
  117. self.servers.add(server)
  118. if not self.oldest_server:
  119. self.oldest_server = server
  120. def add_invited(self, invitee):
  121. """ Someone has been invited to the room
  122. """
  123. self.invited.add(invitee)
  124. self.servers.add(origin_from_ucid(invitee))
  125. class HomeServer(ReplicationHandler):
  126. """ A very basic home server implentation that allows people to join a
  127. room and then invite other people.
  128. """
  129. def __init__(self, server_name, replication_layer, output):
  130. self.server_name = server_name
  131. self.replication_layer = replication_layer
  132. self.replication_layer.set_handler(self)
  133. self.joined_rooms = {}
  134. self.output = output
  135. def on_receive_pdu(self, pdu):
  136. """ We just received a PDU
  137. """
  138. pdu_type = pdu.pdu_type
  139. if pdu_type == "sy.room.message":
  140. self._on_message(pdu)
  141. elif pdu_type == "sy.room.member" and "membership" in pdu.content:
  142. if pdu.content["membership"] == "join":
  143. self._on_join(pdu.context, pdu.state_key)
  144. elif pdu.content["membership"] == "invite":
  145. self._on_invite(pdu.origin, pdu.context, pdu.state_key)
  146. else:
  147. self.output.print_line(
  148. "#%s (unrec) %s = %s"
  149. % (pdu.context, pdu.pdu_type, json.dumps(pdu.content))
  150. )
  151. def _on_message(self, pdu):
  152. """ We received a message
  153. """
  154. self.output.print_line(
  155. "#%s %s %s" % (pdu.context, pdu.content["sender"], pdu.content["body"])
  156. )
  157. def _on_join(self, context, joinee):
  158. """ Someone has joined a room, either a remote user or a local user
  159. """
  160. room = self._get_or_create_room(context)
  161. room.add_participant(joinee)
  162. self.output.print_line("#%s %s %s" % (context, joinee, "*** JOINED"))
  163. def _on_invite(self, origin, context, invitee):
  164. """ Someone has been invited
  165. """
  166. room = self._get_or_create_room(context)
  167. room.add_invited(invitee)
  168. self.output.print_line("#%s %s %s" % (context, invitee, "*** INVITED"))
  169. if not room.have_got_metadata and origin is not self.server_name:
  170. logger.debug("Get room state")
  171. self.replication_layer.get_state_for_context(origin, context)
  172. room.have_got_metadata = True
  173. @defer.inlineCallbacks
  174. def send_message(self, room_name, sender, body):
  175. """ Send a message to a room!
  176. """
  177. destinations = yield self.get_servers_for_context(room_name)
  178. try:
  179. yield self.replication_layer.send_pdu(
  180. Pdu.create_new(
  181. context=room_name,
  182. pdu_type="sy.room.message",
  183. content={"sender": sender, "body": body},
  184. origin=self.server_name,
  185. destinations=destinations,
  186. )
  187. )
  188. except Exception as e:
  189. logger.exception(e)
  190. @defer.inlineCallbacks
  191. def join_room(self, room_name, sender, joinee):
  192. """ Join a room!
  193. """
  194. self._on_join(room_name, joinee)
  195. destinations = yield self.get_servers_for_context(room_name)
  196. try:
  197. pdu = Pdu.create_new(
  198. context=room_name,
  199. pdu_type="sy.room.member",
  200. is_state=True,
  201. state_key=joinee,
  202. content={"membership": "join"},
  203. origin=self.server_name,
  204. destinations=destinations,
  205. )
  206. yield self.replication_layer.send_pdu(pdu)
  207. except Exception as e:
  208. logger.exception(e)
  209. @defer.inlineCallbacks
  210. def invite_to_room(self, room_name, sender, invitee):
  211. """ Invite someone to a room!
  212. """
  213. self._on_invite(self.server_name, room_name, invitee)
  214. destinations = yield self.get_servers_for_context(room_name)
  215. try:
  216. yield self.replication_layer.send_pdu(
  217. Pdu.create_new(
  218. context=room_name,
  219. is_state=True,
  220. pdu_type="sy.room.member",
  221. state_key=invitee,
  222. content={"membership": "invite"},
  223. origin=self.server_name,
  224. destinations=destinations,
  225. )
  226. )
  227. except Exception as e:
  228. logger.exception(e)
  229. def backfill(self, room_name, limit=5):
  230. room = self.joined_rooms.get(room_name)
  231. if not room:
  232. return
  233. dest = room.oldest_server
  234. return self.replication_layer.backfill(dest, room_name, limit)
  235. def _get_room_remote_servers(self, room_name):
  236. return list(self.joined_rooms.setdefault(room_name).servers)
  237. def _get_or_create_room(self, room_name):
  238. return self.joined_rooms.setdefault(room_name, Room(room_name))
  239. def get_servers_for_context(self, context):
  240. return defer.succeed(
  241. self.joined_rooms.setdefault(context, Room(context)).servers
  242. )
  243. def main(stdscr):
  244. parser = argparse.ArgumentParser()
  245. parser.add_argument("user", type=str)
  246. parser.add_argument("-v", "--verbose", action="count")
  247. args = parser.parse_args()
  248. user = args.user
  249. server_name = origin_from_ucid(user)
  250. # Set up logging
  251. root_logger = logging.getLogger()
  252. formatter = logging.Formatter(
  253. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
  254. )
  255. if not os.path.exists("logs"):
  256. os.makedirs("logs")
  257. fh = logging.FileHandler("logs/%s" % user)
  258. fh.setFormatter(formatter)
  259. root_logger.addHandler(fh)
  260. root_logger.setLevel(logging.DEBUG)
  261. # Hack: The only way to get it to stop logging to sys.stderr :(
  262. log.theLogPublisher.observers = []
  263. observer = log.PythonLoggingObserver()
  264. observer.start()
  265. # Set up synapse server
  266. curses_stdio = cursesio.CursesStdIO(stdscr)
  267. input_output = InputOutput(curses_stdio, user)
  268. curses_stdio.set_callback(input_output)
  269. app_hs = SynapseHomeServer(server_name, db_name="dbs/%s" % user)
  270. replication = app_hs.get_replication_layer()
  271. hs = HomeServer(server_name, replication, curses_stdio)
  272. input_output.set_home_server(hs)
  273. # Add input_output logger
  274. io_logger = IOLoggerHandler(input_output)
  275. io_logger.setFormatter(formatter)
  276. root_logger.addHandler(io_logger)
  277. # Start!
  278. try:
  279. port = int(server_name.split(":")[1])
  280. except Exception:
  281. port = 12345
  282. app_hs.get_http_server().start_listening(port)
  283. reactor.addReader(curses_stdio)
  284. reactor.run()
  285. if __name__ == "__main__":
  286. curses.wrapper(main)