1
0

test_messaging.py 11 KB

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