console.py 29 KB

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