console.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. #!/usr/bin/env python
  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. """ Starts a synapse client console. """
  16. import argparse
  17. import cmd
  18. import getpass
  19. import json
  20. import shlex
  21. import sys
  22. import time
  23. import urllib
  24. from http import TwistedHttpClient
  25. import nacl.encoding
  26. import nacl.signing
  27. import urlparse
  28. from signedjson.sign import SignatureVerifyException, verify_signed_json
  29. from twisted.internet import defer, reactor, threads
  30. CONFIG_JSON = "cmdclient_config.json"
  31. # TODO: The concept of trusted identity servers has been deprecated. This option and checks
  32. # should be removed
  33. TRUSTED_ID_SERVERS = ["localhost:8001"]
  34. class SynapseCmd(cmd.Cmd):
  35. """Basic synapse command-line processor.
  36. This processes commands from the user and calls the relevant HTTP methods.
  37. """
  38. def __init__(self, http_client, server_url, identity_server_url, username, token):
  39. cmd.Cmd.__init__(self)
  40. self.http_client = http_client
  41. self.http_client.verbose = True
  42. self.config = {
  43. "url": server_url,
  44. "identityServerUrl": identity_server_url,
  45. "user": username,
  46. "token": token,
  47. "verbose": "on",
  48. "complete_usernames": "on",
  49. "send_delivery_receipts": "on",
  50. }
  51. self.path_prefix = "/_matrix/client/api/v1"
  52. self.event_stream_token = "END"
  53. self.prompt = ">>> "
  54. def do_EOF(self, line): # allows CTRL+D quitting
  55. return True
  56. def emptyline(self):
  57. pass # else it repeats the previous command
  58. def _usr(self):
  59. return self.config["user"]
  60. def _tok(self):
  61. return self.config["token"]
  62. def _url(self):
  63. return self.config["url"] + self.path_prefix
  64. def _identityServerUrl(self):
  65. return self.config["identityServerUrl"]
  66. def _is_on(self, config_name):
  67. if config_name in self.config:
  68. return self.config[config_name] == "on"
  69. return False
  70. def _domain(self):
  71. if "user" not in self.config or not self.config["user"]:
  72. return None
  73. return self.config["user"].split(":")[1]
  74. def do_config(self, line):
  75. """ Show the config for this client: "config"
  76. Edit a key value mapping: "config key value" e.g. "config token 1234"
  77. Config variables:
  78. user: The username to auth with.
  79. token: The access token to auth with.
  80. url: The url of the server.
  81. verbose: [on|off] The verbosity of requests/responses.
  82. complete_usernames: [on|off] Auto complete partial usernames by
  83. assuming they are on the same homeserver as you.
  84. E.g. name >> @name:yourhost
  85. send_delivery_receipts: [on|off] Automatically send receipts to
  86. messages when performing a 'stream' command.
  87. Additional key/values can be added and can be substituted into requests
  88. by using $. E.g. 'config roomid room1' then 'raw get /rooms/$roomid'.
  89. """
  90. if len(line) == 0:
  91. print(json.dumps(self.config, indent=4))
  92. return
  93. try:
  94. args = self._parse(line, ["key", "val"], force_keys=True)
  95. # make sure restricted config values are checked
  96. config_rules = [ # key, valid_values
  97. ("verbose", ["on", "off"]),
  98. ("complete_usernames", ["on", "off"]),
  99. ("send_delivery_receipts", ["on", "off"]),
  100. ]
  101. for key, valid_vals in config_rules:
  102. if key == args["key"] and args["val"] not in valid_vals:
  103. print("%s value must be one of %s" % (args["key"], valid_vals))
  104. return
  105. # toggle the http client verbosity
  106. if args["key"] == "verbose":
  107. self.http_client.verbose = "on" == args["val"]
  108. # assign the new config
  109. self.config[args["key"]] = args["val"]
  110. print(json.dumps(self.config, indent=4))
  111. save_config(self.config)
  112. except Exception as e:
  113. print(e)
  114. def do_register(self, line):
  115. """Registers for a new account: "register <userid> <noupdate>"
  116. <userid> : The desired user ID
  117. <noupdate> : Do not automatically clobber config values.
  118. """
  119. args = self._parse(line, ["userid", "noupdate"])
  120. password = None
  121. pwd = None
  122. pwd2 = "_"
  123. while pwd != pwd2:
  124. pwd = getpass.getpass("Type a password for this user: ")
  125. pwd2 = getpass.getpass("Retype the password: ")
  126. if pwd != pwd2 or len(pwd) == 0:
  127. print("Password mismatch.")
  128. pwd = None
  129. else:
  130. password = pwd
  131. body = {"type": "m.login.password"}
  132. if "userid" in args:
  133. body["user"] = args["userid"]
  134. if password:
  135. body["password"] = password
  136. reactor.callFromThread(self._do_register, body, "noupdate" not in args)
  137. @defer.inlineCallbacks
  138. def _do_register(self, data, update_config):
  139. # check the registration flows
  140. url = self._url() + "/register"
  141. json_res = yield self.http_client.do_request("GET", url)
  142. print(json.dumps(json_res, indent=4))
  143. passwordFlow = None
  144. for flow in json_res["flows"]:
  145. if flow["type"] == "m.login.recaptcha" or (
  146. "stages" in flow and "m.login.recaptcha" in flow["stages"]
  147. ):
  148. print("Unable to register: Home server requires captcha.")
  149. return
  150. if flow["type"] == "m.login.password" and "stages" not in flow:
  151. passwordFlow = flow
  152. break
  153. if not passwordFlow:
  154. return
  155. json_res = yield self.http_client.do_request("POST", url, data=data)
  156. print(json.dumps(json_res, indent=4))
  157. if update_config and "user_id" in json_res:
  158. self.config["user"] = json_res["user_id"]
  159. self.config["token"] = json_res["access_token"]
  160. save_config(self.config)
  161. def do_login(self, line):
  162. """Login as a specific user: "login @bob:localhost"
  163. You MAY be prompted for a password, or instructed to visit a URL.
  164. """
  165. try:
  166. args = self._parse(line, ["user_id"], force_keys=True)
  167. can_login = threads.blockingCallFromThread(reactor, self._check_can_login)
  168. if can_login:
  169. p = getpass.getpass("Enter your password: ")
  170. user = args["user_id"]
  171. if self._is_on("complete_usernames") and not user.startswith("@"):
  172. domain = self._domain()
  173. if domain:
  174. user = "@" + user + ":" + domain
  175. reactor.callFromThread(self._do_login, user, p)
  176. # print " got %s " % p
  177. except Exception as e:
  178. print(e)
  179. @defer.inlineCallbacks
  180. def _do_login(self, user, password):
  181. path = "/login"
  182. data = {"user": user, "password": password, "type": "m.login.password"}
  183. url = self._url() + path
  184. json_res = yield self.http_client.do_request("POST", url, data=data)
  185. print(json_res)
  186. if "access_token" in json_res:
  187. self.config["user"] = user
  188. self.config["token"] = json_res["access_token"]
  189. save_config(self.config)
  190. print("Login successful.")
  191. @defer.inlineCallbacks
  192. def _check_can_login(self):
  193. path = "/login"
  194. # ALWAYS check that the home server can handle the login request before
  195. # submitting!
  196. url = self._url() + path
  197. json_res = yield self.http_client.do_request("GET", url)
  198. print(json_res)
  199. if "flows" not in json_res:
  200. print("Failed to find any login flows.")
  201. defer.returnValue(False)
  202. flow = json_res["flows"][0] # assume first is the one we want.
  203. if "type" not in flow or "m.login.password" != flow["type"] or "stages" in flow:
  204. fallback_url = self._url() + "/login/fallback"
  205. print(
  206. "Unable to login via the command line client. Please visit "
  207. "%s to login." % fallback_url
  208. )
  209. defer.returnValue(False)
  210. defer.returnValue(True)
  211. def do_emailrequest(self, line):
  212. """Requests the association of a third party identifier
  213. <address> The email address)
  214. <clientSecret> A string of characters generated when requesting an email that you'll supply in subsequent calls to identify yourself
  215. <sendAttempt> The number of times the user has requested an email. Leave this the same between requests to retry the request at the transport level. Increment it to request that the email be sent again.
  216. """
  217. args = self._parse(line, ["address", "clientSecret", "sendAttempt"])
  218. postArgs = {
  219. "email": args["address"],
  220. "clientSecret": args["clientSecret"],
  221. "sendAttempt": args["sendAttempt"],
  222. }
  223. reactor.callFromThread(self._do_emailrequest, postArgs)
  224. @defer.inlineCallbacks
  225. def _do_emailrequest(self, args):
  226. # TODO: Update to use v2 Identity Service API endpoint
  227. url = (
  228. self._identityServerUrl()
  229. + "/_matrix/identity/api/v1/validate/email/requestToken"
  230. )
  231. json_res = yield self.http_client.do_request(
  232. "POST",
  233. url,
  234. data=urllib.urlencode(args),
  235. jsonreq=False,
  236. headers={"Content-Type": ["application/x-www-form-urlencoded"]},
  237. )
  238. print(json_res)
  239. if "sid" in json_res:
  240. print("Token sent. Your session ID is %s" % (json_res["sid"]))
  241. def do_emailvalidate(self, line):
  242. """Validate and associate a third party ID
  243. <sid> The session ID (sid) given to you in the response to requestToken
  244. <token> The token sent to your third party identifier address
  245. <clientSecret> The same clientSecret you supplied in requestToken
  246. """
  247. args = self._parse(line, ["sid", "token", "clientSecret"])
  248. postArgs = {
  249. "sid": args["sid"],
  250. "token": args["token"],
  251. "clientSecret": args["clientSecret"],
  252. }
  253. reactor.callFromThread(self._do_emailvalidate, postArgs)
  254. @defer.inlineCallbacks
  255. def _do_emailvalidate(self, args):
  256. # TODO: Update to use v2 Identity Service API endpoint
  257. url = (
  258. self._identityServerUrl()
  259. + "/_matrix/identity/api/v1/validate/email/submitToken"
  260. )
  261. json_res = yield self.http_client.do_request(
  262. "POST",
  263. url,
  264. data=urllib.urlencode(args),
  265. jsonreq=False,
  266. headers={"Content-Type": ["application/x-www-form-urlencoded"]},
  267. )
  268. print(json_res)
  269. def do_3pidbind(self, line):
  270. """Validate and associate a third party ID
  271. <sid> The session ID (sid) given to you in the response to requestToken
  272. <clientSecret> The same clientSecret you supplied in requestToken
  273. """
  274. args = self._parse(line, ["sid", "clientSecret"])
  275. postArgs = {"sid": args["sid"], "clientSecret": args["clientSecret"]}
  276. postArgs["mxid"] = self.config["user"]
  277. reactor.callFromThread(self._do_3pidbind, postArgs)
  278. @defer.inlineCallbacks
  279. def _do_3pidbind(self, args):
  280. # TODO: Update to use v2 Identity Service API endpoint
  281. url = self._identityServerUrl() + "/_matrix/identity/api/v1/3pid/bind"
  282. json_res = yield self.http_client.do_request(
  283. "POST",
  284. url,
  285. data=urllib.urlencode(args),
  286. jsonreq=False,
  287. headers={"Content-Type": ["application/x-www-form-urlencoded"]},
  288. )
  289. print(json_res)
  290. def do_join(self, line):
  291. """Joins a room: "join <roomid>" """
  292. try:
  293. args = self._parse(line, ["roomid"], force_keys=True)
  294. self._do_membership_change(args["roomid"], "join", self._usr())
  295. except Exception as e:
  296. print(e)
  297. def do_joinalias(self, line):
  298. try:
  299. args = self._parse(line, ["roomname"], force_keys=True)
  300. path = "/join/%s" % urllib.quote(args["roomname"])
  301. reactor.callFromThread(self._run_and_pprint, "POST", path, {})
  302. except Exception as e:
  303. print(e)
  304. def do_topic(self, line):
  305. """"topic [set|get] <roomid> [<newtopic>]"
  306. Set the topic for a room: topic set <roomid> <newtopic>
  307. Get the topic for a room: topic get <roomid>
  308. """
  309. try:
  310. args = self._parse(line, ["action", "roomid", "topic"])
  311. if "action" not in args or "roomid" not in args:
  312. print("Must specify set|get and a room ID.")
  313. return
  314. if args["action"].lower() not in ["set", "get"]:
  315. print("Must specify set|get, not %s" % args["action"])
  316. return
  317. path = "/rooms/%s/topic" % urllib.quote(args["roomid"])
  318. if args["action"].lower() == "set":
  319. if "topic" not in args:
  320. print("Must specify a new topic.")
  321. return
  322. body = {"topic": args["topic"]}
  323. reactor.callFromThread(self._run_and_pprint, "PUT", path, body)
  324. elif args["action"].lower() == "get":
  325. reactor.callFromThread(self._run_and_pprint, "GET", path)
  326. except Exception as e:
  327. print(e)
  328. def do_invite(self, line):
  329. """Invite a user to a room: "invite <userid> <roomid>" """
  330. try:
  331. args = self._parse(line, ["userid", "roomid"], force_keys=True)
  332. user_id = args["userid"]
  333. reactor.callFromThread(self._do_invite, args["roomid"], user_id)
  334. except Exception as e:
  335. print(e)
  336. @defer.inlineCallbacks
  337. def _do_invite(self, roomid, userstring):
  338. if not userstring.startswith("@") and self._is_on("complete_usernames"):
  339. # TODO: Update to use v2 Identity Service API endpoint
  340. url = self._identityServerUrl() + "/_matrix/identity/api/v1/lookup"
  341. json_res = yield self.http_client.do_request(
  342. "GET", url, qparams={"medium": "email", "address": userstring}
  343. )
  344. mxid = None
  345. if "mxid" in json_res and "signatures" in json_res:
  346. # TODO: Update to use v2 Identity Service API endpoint
  347. url = (
  348. self._identityServerUrl()
  349. + "/_matrix/identity/api/v1/pubkey/ed25519"
  350. )
  351. pubKey = None
  352. pubKeyObj = yield self.http_client.do_request("GET", url)
  353. if "public_key" in pubKeyObj:
  354. pubKey = nacl.signing.VerifyKey(
  355. pubKeyObj["public_key"], encoder=nacl.encoding.HexEncoder
  356. )
  357. else:
  358. print("No public key found in pubkey response!")
  359. sigValid = False
  360. if pubKey:
  361. for signame in json_res["signatures"]:
  362. if signame not in TRUSTED_ID_SERVERS:
  363. print(
  364. "Ignoring signature from untrusted server %s"
  365. % (signame)
  366. )
  367. else:
  368. try:
  369. verify_signed_json(json_res, signame, pubKey)
  370. sigValid = True
  371. print(
  372. "Mapping %s -> %s correctly signed by %s"
  373. % (userstring, json_res["mxid"], signame)
  374. )
  375. break
  376. except SignatureVerifyException as e:
  377. print("Invalid signature from %s" % (signame))
  378. print(e)
  379. if sigValid:
  380. print("Resolved 3pid %s to %s" % (userstring, json_res["mxid"]))
  381. mxid = json_res["mxid"]
  382. else:
  383. print(
  384. "Got association for %s but couldn't verify signature"
  385. % (userstring)
  386. )
  387. if not mxid:
  388. mxid = "@" + userstring + ":" + self._domain()
  389. self._do_membership_change(roomid, "invite", mxid)
  390. def do_leave(self, line):
  391. """Leaves a room: "leave <roomid>" """
  392. try:
  393. args = self._parse(line, ["roomid"], force_keys=True)
  394. self._do_membership_change(args["roomid"], "leave", self._usr())
  395. except Exception as e:
  396. print(e)
  397. def do_send(self, line):
  398. """Sends a message. "send <roomid> <body>" """
  399. args = self._parse(line, ["roomid", "body"])
  400. txn_id = "txn%s" % int(time.time())
  401. path = "/rooms/%s/send/m.room.message/%s" % (
  402. urllib.quote(args["roomid"]),
  403. txn_id,
  404. )
  405. body_json = {"msgtype": "m.text", "body": args["body"]}
  406. reactor.callFromThread(self._run_and_pprint, "PUT", path, body_json)
  407. def do_list(self, line):
  408. """List data about a room.
  409. "list members <roomid> [query]" - List all the members in this room.
  410. "list messages <roomid> [query]" - List all the messages in this room.
  411. Where [query] will be directly applied as query parameters, allowing
  412. you to use the pagination API. E.g. the last 3 messages in this room:
  413. "list messages <roomid> from=END&to=START&limit=3"
  414. """
  415. args = self._parse(line, ["type", "roomid", "qp"])
  416. if "type" not in args or "roomid" not in args:
  417. print("Must specify type and room ID.")
  418. return
  419. if args["type"] not in ["members", "messages"]:
  420. print("Unrecognised type: %s" % args["type"])
  421. return
  422. room_id = args["roomid"]
  423. path = "/rooms/%s/%s" % (urllib.quote(room_id), args["type"])
  424. qp = {"access_token": self._tok()}
  425. if "qp" in args:
  426. for key_value_str in args["qp"].split("&"):
  427. try:
  428. key_value = key_value_str.split("=")
  429. qp[key_value[0]] = key_value[1]
  430. except Exception:
  431. print("Bad query param: %s" % key_value)
  432. return
  433. reactor.callFromThread(self._run_and_pprint, "GET", path, query_params=qp)
  434. def do_create(self, line):
  435. """Creates a room.
  436. "create [public|private] <roomname>" - Create a room <roomname> with the
  437. specified visibility.
  438. "create <roomname>" - Create a room <roomname> with default visibility.
  439. "create [public|private]" - Create a room with specified visibility.
  440. "create" - Create a room with default visibility.
  441. """
  442. args = self._parse(line, ["vis", "roomname"])
  443. # fixup args depending on which were set
  444. body = {}
  445. if "vis" in args and args["vis"] in ["public", "private"]:
  446. body["visibility"] = args["vis"]
  447. if "roomname" in args:
  448. room_name = args["roomname"]
  449. body["room_alias_name"] = room_name
  450. elif "vis" in args and args["vis"] not in ["public", "private"]:
  451. room_name = args["vis"]
  452. body["room_alias_name"] = room_name
  453. reactor.callFromThread(self._run_and_pprint, "POST", "/createRoom", body)
  454. def do_raw(self, line):
  455. """Directly send a JSON object: "raw <method> <path> <data> <notoken>"
  456. <method>: Required. One of "PUT", "GET", "POST", "xPUT", "xGET",
  457. "xPOST". Methods with 'x' prefixed will not automatically append the
  458. access token.
  459. <path>: Required. E.g. "/events"
  460. <data>: Optional. E.g. "{ "msgtype":"custom.text", "body":"abc123"}"
  461. """
  462. args = self._parse(line, ["method", "path", "data"])
  463. # sanity check
  464. if "method" not in args or "path" not in args:
  465. print("Must specify path and method.")
  466. return
  467. args["method"] = args["method"].upper()
  468. valid_methods = [
  469. "PUT",
  470. "GET",
  471. "POST",
  472. "DELETE",
  473. "XPUT",
  474. "XGET",
  475. "XPOST",
  476. "XDELETE",
  477. ]
  478. if args["method"] not in valid_methods:
  479. print("Unsupported method: %s" % args["method"])
  480. return
  481. if "data" not in args:
  482. args["data"] = None
  483. else:
  484. try:
  485. args["data"] = json.loads(args["data"])
  486. except Exception as e:
  487. print("Data is not valid JSON. %s" % e)
  488. return
  489. qp = {"access_token": self._tok()}
  490. if args["method"].startswith("X"):
  491. qp = {} # remove access token
  492. args["method"] = args["method"][1:] # snip the X
  493. else:
  494. # append any query params the user has set
  495. try:
  496. parsed_url = urlparse.urlparse(args["path"])
  497. qp.update(urlparse.parse_qs(parsed_url.query))
  498. args["path"] = parsed_url.path
  499. except Exception:
  500. pass
  501. reactor.callFromThread(
  502. self._run_and_pprint,
  503. args["method"],
  504. args["path"],
  505. args["data"],
  506. query_params=qp,
  507. )
  508. def do_stream(self, line):
  509. """Stream data from the server: "stream <longpoll timeout ms>" """
  510. args = self._parse(line, ["timeout"])
  511. timeout = 5000
  512. if "timeout" in args:
  513. try:
  514. timeout = int(args["timeout"])
  515. except ValueError:
  516. print("Timeout must be in milliseconds.")
  517. return
  518. reactor.callFromThread(self._do_event_stream, timeout)
  519. @defer.inlineCallbacks
  520. def _do_event_stream(self, timeout):
  521. res = yield defer.ensureDeferred(
  522. self.http_client.get_json(
  523. self._url() + "/events",
  524. {
  525. "access_token": self._tok(),
  526. "timeout": str(timeout),
  527. "from": self.event_stream_token,
  528. },
  529. )
  530. )
  531. print(json.dumps(res, indent=4))
  532. if "chunk" in res:
  533. for event in res["chunk"]:
  534. if (
  535. event["type"] == "m.room.message"
  536. and self._is_on("send_delivery_receipts")
  537. and event["user_id"] != self._usr()
  538. ): # not sent by us
  539. self._send_receipt(event, "d")
  540. # update the position in the stram
  541. if "end" in res:
  542. self.event_stream_token = res["end"]
  543. def _send_receipt(self, event, feedback_type):
  544. path = "/rooms/%s/messages/%s/%s/feedback/%s/%s" % (
  545. urllib.quote(event["room_id"]),
  546. event["user_id"],
  547. event["msg_id"],
  548. self._usr(),
  549. feedback_type,
  550. )
  551. data = {}
  552. reactor.callFromThread(
  553. self._run_and_pprint,
  554. "PUT",
  555. path,
  556. data=data,
  557. alt_text="Sent receipt for %s" % event["msg_id"],
  558. )
  559. def _do_membership_change(self, roomid, membership, userid):
  560. path = "/rooms/%s/state/m.room.member/%s" % (
  561. urllib.quote(roomid),
  562. urllib.quote(userid),
  563. )
  564. data = {"membership": membership}
  565. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  566. def do_displayname(self, line):
  567. """Get or set my displayname: "displayname [new_name]" """
  568. args = self._parse(line, ["name"])
  569. path = "/profile/%s/displayname" % (self.config["user"])
  570. if "name" in args:
  571. data = {"displayname": args["name"]}
  572. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  573. else:
  574. reactor.callFromThread(self._run_and_pprint, "GET", path)
  575. def _do_presence_state(self, state, line):
  576. args = self._parse(line, ["msgstring"])
  577. path = "/presence/%s/status" % (self.config["user"])
  578. data = {"state": state}
  579. if "msgstring" in args:
  580. data["status_msg"] = args["msgstring"]
  581. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  582. def do_offline(self, line):
  583. """Set my presence state to OFFLINE"""
  584. self._do_presence_state(0, line)
  585. def do_away(self, line):
  586. """Set my presence state to AWAY"""
  587. self._do_presence_state(1, line)
  588. def do_online(self, line):
  589. """Set my presence state to ONLINE"""
  590. self._do_presence_state(2, line)
  591. def _parse(self, line, keys, force_keys=False):
  592. """ Parses the given line.
  593. Args:
  594. line : The line to parse
  595. keys : A list of keys to map onto the args
  596. force_keys : True to enforce that the line has a value for every key
  597. Returns:
  598. A dict of key:arg
  599. """
  600. line_args = shlex.split(line)
  601. if force_keys and len(line_args) != len(keys):
  602. raise IndexError("Must specify all args: %s" % keys)
  603. # do $ substitutions
  604. for i, arg in enumerate(line_args):
  605. for config_key in self.config:
  606. if ("$" + config_key) in arg:
  607. arg = arg.replace("$" + config_key, self.config[config_key])
  608. line_args[i] = arg
  609. return dict(zip(keys, line_args))
  610. @defer.inlineCallbacks
  611. def _run_and_pprint(
  612. self,
  613. method,
  614. path,
  615. data=None,
  616. query_params={"access_token": None},
  617. alt_text=None,
  618. ):
  619. """ Runs an HTTP request and pretty prints the output.
  620. Args:
  621. method: HTTP method
  622. path: Relative path
  623. data: Raw JSON data if any
  624. query_params: dict of query parameters to add to the url
  625. """
  626. url = self._url() + path
  627. if "access_token" in query_params:
  628. query_params["access_token"] = self._tok()
  629. json_res = yield self.http_client.do_request(
  630. method, url, data=data, qparams=query_params
  631. )
  632. if alt_text:
  633. print(alt_text)
  634. else:
  635. print(json.dumps(json_res, indent=4))
  636. def save_config(config):
  637. with open(CONFIG_JSON, "w") as out:
  638. json.dump(config, out)
  639. def main(server_url, identity_server_url, username, token, config_path):
  640. print("Synapse command line client")
  641. print("===========================")
  642. print("Server: %s" % server_url)
  643. print("Type 'help' to get started.")
  644. print("Close this console with CTRL+C then CTRL+D.")
  645. if not username or not token:
  646. print("- 'register <username>' - Register an account")
  647. print("- 'stream' - Connect to the event stream")
  648. print("- 'create <roomid>' - Create a room")
  649. print("- 'send <roomid> <message>' - Send a message")
  650. http_client = TwistedHttpClient()
  651. # the command line client
  652. syn_cmd = SynapseCmd(http_client, server_url, identity_server_url, username, token)
  653. # load synapse.json config from a previous session
  654. global CONFIG_JSON
  655. CONFIG_JSON = config_path # bit cheeky, but just overwrite the global
  656. try:
  657. with open(config_path, "r") as config:
  658. syn_cmd.config = json.load(config)
  659. try:
  660. http_client.verbose = "on" == syn_cmd.config["verbose"]
  661. except Exception:
  662. pass
  663. print("Loaded config from %s" % config_path)
  664. except Exception:
  665. pass
  666. # Twisted-specific: Runs the command processor in Twisted's event loop
  667. # to maintain a single thread for both commands and event processing.
  668. # If using another HTTP client, just call syn_cmd.cmdloop()
  669. reactor.callInThread(syn_cmd.cmdloop)
  670. reactor.run()
  671. if __name__ == "__main__":
  672. parser = argparse.ArgumentParser("Starts a synapse client.")
  673. parser.add_argument(
  674. "-s",
  675. "--server",
  676. dest="server",
  677. default="http://localhost:8008",
  678. help="The URL of the home server to talk to.",
  679. )
  680. parser.add_argument(
  681. "-i",
  682. "--identity-server",
  683. dest="identityserver",
  684. default="http://localhost:8090",
  685. help="The URL of the identity server to talk to.",
  686. )
  687. parser.add_argument(
  688. "-u", "--username", dest="username", help="Your username on the server."
  689. )
  690. parser.add_argument("-t", "--token", dest="token", help="Your access token.")
  691. parser.add_argument(
  692. "-c",
  693. "--config",
  694. dest="config",
  695. default=CONFIG_JSON,
  696. help="The location of the config.json file to read from.",
  697. )
  698. args = parser.parse_args()
  699. if not args.server:
  700. print("You must supply a server URL to communicate with.")
  701. parser.print_help()
  702. sys.exit(1)
  703. server = args.server
  704. if not server.startswith("http://"):
  705. server = "http://" + args.server
  706. main(server, args.identityserver, args.username, args.token, args.config)