test_messaging.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. from synapse.federation import ReplicationHandler
  24. from synapse.federation.units import Pdu
  25. from synapse.util import origin_from_ucid
  26. from synapse.app.homeserver import SynapseHomeServer
  27. # from synapse.logging.utils import log_function
  28. from twisted.internet import reactor, defer
  29. from twisted.python import log
  30. import argparse
  31. import json
  32. import logging
  33. import os
  34. import re
  35. import cursesio
  36. import curses.wrapper
  37. logger = logging.getLogger("example")
  38. def excpetion_errback(failure):
  39. logging.exception(failure)
  40. class InputOutput(object):
  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("^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("^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("^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("^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(object):
  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_state_change(self, pdu):
  152. ##self.output.print_line("#%s (state) %s *** %s" %
  153. ##(pdu.context, pdu.state_key, pdu.pdu_type)
  154. ##)
  155. # if "joinee" in pdu.content:
  156. # self._on_join(pdu.context, pdu.content["joinee"])
  157. # elif "invitee" in pdu.content:
  158. # self._on_invite(pdu.origin, pdu.context, pdu.content["invitee"])
  159. def _on_message(self, pdu):
  160. """ We received a message
  161. """
  162. self.output.print_line(
  163. "#%s %s %s" % (pdu.context, pdu.content["sender"], pdu.content["body"])
  164. )
  165. def _on_join(self, context, joinee):
  166. """ Someone has joined a room, either a remote user or a local user
  167. """
  168. room = self._get_or_create_room(context)
  169. room.add_participant(joinee)
  170. self.output.print_line("#%s %s %s" % (context, joinee, "*** JOINED"))
  171. def _on_invite(self, origin, context, invitee):
  172. """ Someone has been invited
  173. """
  174. room = self._get_or_create_room(context)
  175. room.add_invited(invitee)
  176. self.output.print_line("#%s %s %s" % (context, invitee, "*** INVITED"))
  177. if not room.have_got_metadata and origin is not self.server_name:
  178. logger.debug("Get room state")
  179. self.replication_layer.get_state_for_context(origin, context)
  180. room.have_got_metadata = True
  181. @defer.inlineCallbacks
  182. def send_message(self, room_name, sender, body):
  183. """ Send a message to a room!
  184. """
  185. destinations = yield self.get_servers_for_context(room_name)
  186. try:
  187. yield self.replication_layer.send_pdu(
  188. Pdu.create_new(
  189. context=room_name,
  190. pdu_type="sy.room.message",
  191. content={"sender": sender, "body": body},
  192. origin=self.server_name,
  193. destinations=destinations,
  194. )
  195. )
  196. except Exception as e:
  197. logger.exception(e)
  198. @defer.inlineCallbacks
  199. def join_room(self, room_name, sender, joinee):
  200. """ Join a room!
  201. """
  202. self._on_join(room_name, joinee)
  203. destinations = yield self.get_servers_for_context(room_name)
  204. try:
  205. pdu = Pdu.create_new(
  206. context=room_name,
  207. pdu_type="sy.room.member",
  208. is_state=True,
  209. state_key=joinee,
  210. content={"membership": "join"},
  211. origin=self.server_name,
  212. destinations=destinations,
  213. )
  214. yield self.replication_layer.send_pdu(pdu)
  215. except Exception as e:
  216. logger.exception(e)
  217. @defer.inlineCallbacks
  218. def invite_to_room(self, room_name, sender, invitee):
  219. """ Invite someone to a room!
  220. """
  221. self._on_invite(self.server_name, room_name, invitee)
  222. destinations = yield self.get_servers_for_context(room_name)
  223. try:
  224. yield self.replication_layer.send_pdu(
  225. Pdu.create_new(
  226. context=room_name,
  227. is_state=True,
  228. pdu_type="sy.room.member",
  229. state_key=invitee,
  230. content={"membership": "invite"},
  231. origin=self.server_name,
  232. destinations=destinations,
  233. )
  234. )
  235. except Exception as e:
  236. logger.exception(e)
  237. def backfill(self, room_name, limit=5):
  238. room = self.joined_rooms.get(room_name)
  239. if not room:
  240. return
  241. dest = room.oldest_server
  242. return self.replication_layer.backfill(dest, room_name, limit)
  243. def _get_room_remote_servers(self, room_name):
  244. return [i for i in self.joined_rooms.setdefault(room_name).servers]
  245. def _get_or_create_room(self, room_name):
  246. return self.joined_rooms.setdefault(room_name, Room(room_name))
  247. def get_servers_for_context(self, context):
  248. return defer.succeed(
  249. self.joined_rooms.setdefault(context, Room(context)).servers
  250. )
  251. def main(stdscr):
  252. parser = argparse.ArgumentParser()
  253. parser.add_argument("user", type=str)
  254. parser.add_argument("-v", "--verbose", action="count")
  255. args = parser.parse_args()
  256. user = args.user
  257. server_name = origin_from_ucid(user)
  258. ## Set up logging ##
  259. root_logger = logging.getLogger()
  260. formatter = logging.Formatter(
  261. "%(asctime)s - %(name)s - %(lineno)d - " "%(levelname)s - %(message)s"
  262. )
  263. if not os.path.exists("logs"):
  264. os.makedirs("logs")
  265. fh = logging.FileHandler("logs/%s" % user)
  266. fh.setFormatter(formatter)
  267. root_logger.addHandler(fh)
  268. root_logger.setLevel(logging.DEBUG)
  269. # Hack: The only way to get it to stop logging to sys.stderr :(
  270. log.theLogPublisher.observers = []
  271. observer = log.PythonLoggingObserver()
  272. observer.start()
  273. ## Set up synapse server
  274. curses_stdio = cursesio.CursesStdIO(stdscr)
  275. input_output = InputOutput(curses_stdio, user)
  276. curses_stdio.set_callback(input_output)
  277. app_hs = SynapseHomeServer(server_name, db_name="dbs/%s" % user)
  278. replication = app_hs.get_replication_layer()
  279. hs = HomeServer(server_name, replication, curses_stdio)
  280. input_output.set_home_server(hs)
  281. ## Add input_output logger
  282. io_logger = IOLoggerHandler(input_output)
  283. io_logger.setFormatter(formatter)
  284. root_logger.addHandler(io_logger)
  285. ## Start! ##
  286. try:
  287. port = int(server_name.split(":")[1])
  288. except:
  289. port = 12345
  290. app_hs.get_http_server().start_listening(port)
  291. reactor.addReader(curses_stdio)
  292. reactor.run()
  293. if __name__ == "__main__":
  294. curses.wrapper(main)