console.py 29 KB

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