1
0

console.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. #!/usr/bin/env python
  2. # Copyright 2014 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 twisted.internet import reactor, defer, threads
  17. from http import TwistedHttpClient
  18. import argparse
  19. import cmd
  20. import getpass
  21. import json
  22. import shlex
  23. import sys
  24. import time
  25. import urllib
  26. import urlparse
  27. import nacl.signing
  28. import nacl.encoding
  29. from syutil.crypto.jsonsign import verify_signed_json, SignatureVerifyException
  30. CONFIG_JSON = "cmdclient_config.json"
  31. TRUSTED_ID_SERVERS = [
  32. 'localhost:8001'
  33. ]
  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"],
  104. 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 = {
  133. "type": "m.login.password"
  134. }
  135. if "userid" in args:
  136. body["user"] = args["userid"]
  137. if password:
  138. body["password"] = password
  139. reactor.callFromThread(self._do_register, body,
  140. "noupdate" not in args)
  141. @defer.inlineCallbacks
  142. def _do_register(self, data, update_config):
  143. # check the registration flows
  144. url = self._url() + "/register"
  145. json_res = yield self.http_client.do_request("GET", url)
  146. print json.dumps(json_res, indent=4)
  147. passwordFlow = None
  148. for flow in json_res["flows"]:
  149. if flow["type"] == "m.login.recaptcha" or ("stages" in flow and "m.login.recaptcha" in flow["stages"]):
  150. print "Unable to register: Home server requires captcha."
  151. return
  152. if flow["type"] == "m.login.password" and "stages" not in flow:
  153. passwordFlow = flow
  154. break
  155. if not passwordFlow:
  156. return
  157. json_res = yield self.http_client.do_request("POST", url, data=data)
  158. print json.dumps(json_res, indent=4)
  159. if update_config and "user_id" in json_res:
  160. self.config["user"] = json_res["user_id"]
  161. self.config["token"] = json_res["access_token"]
  162. save_config(self.config)
  163. def do_login(self, line):
  164. """Login as a specific user: "login @bob:localhost"
  165. You MAY be prompted for a password, or instructed to visit a URL.
  166. """
  167. try:
  168. args = self._parse(line, ["user_id"], force_keys=True)
  169. can_login = threads.blockingCallFromThread(
  170. reactor,
  171. self._check_can_login)
  172. if can_login:
  173. p = getpass.getpass("Enter your password: ")
  174. user = args["user_id"]
  175. if self._is_on("complete_usernames") and not user.startswith("@"):
  176. domain = self._domain()
  177. if domain:
  178. user = "@" + user + ":" + domain
  179. reactor.callFromThread(self._do_login, user, p)
  180. #print " got %s " % p
  181. except Exception as e:
  182. print e
  183. @defer.inlineCallbacks
  184. def _do_login(self, user, password):
  185. path = "/login"
  186. data = {
  187. "user": user,
  188. "password": password,
  189. "type": "m.login.password"
  190. }
  191. url = self._url() + path
  192. json_res = yield self.http_client.do_request("POST", url, data=data)
  193. print json_res
  194. if "access_token" in json_res:
  195. self.config["user"] = user
  196. self.config["token"] = json_res["access_token"]
  197. save_config(self.config)
  198. print "Login successful."
  199. @defer.inlineCallbacks
  200. def _check_can_login(self):
  201. path = "/login"
  202. # ALWAYS check that the home server can handle the login request before
  203. # submitting!
  204. url = self._url() + path
  205. json_res = yield self.http_client.do_request("GET", url)
  206. print json_res
  207. if "flows" not in json_res:
  208. print "Failed to find any login flows."
  209. defer.returnValue(False)
  210. flow = json_res["flows"][0] # assume first is the one we want.
  211. if ("type" not in flow or "m.login.password" != flow["type"] or
  212. "stages" in flow):
  213. fallback_url = self._url() + "/login/fallback"
  214. print ("Unable to login via the command line client. Please visit "
  215. "%s to login." % fallback_url)
  216. defer.returnValue(False)
  217. defer.returnValue(True)
  218. def do_emailrequest(self, line):
  219. """Requests the association of a third party identifier
  220. <address> The email address)
  221. <clientSecret> A string of characters generated when requesting an email that you'll supply in subsequent calls to identify yourself
  222. <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.
  223. """
  224. args = self._parse(line, ['address', 'clientSecret', 'sendAttempt'])
  225. postArgs = {'email': args['address'], 'clientSecret': args['clientSecret'], 'sendAttempt': args['sendAttempt']}
  226. reactor.callFromThread(self._do_emailrequest, postArgs)
  227. @defer.inlineCallbacks
  228. def _do_emailrequest(self, args):
  229. url = self._identityServerUrl()+"/_matrix/identity/api/v1/validate/email/requestToken"
  230. json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False,
  231. headers={'Content-Type': ['application/x-www-form-urlencoded']})
  232. print json_res
  233. if 'sid' in json_res:
  234. print "Token sent. Your session ID is %s" % (json_res['sid'])
  235. def do_emailvalidate(self, line):
  236. """Validate and associate a third party ID
  237. <sid> The session ID (sid) given to you in the response to requestToken
  238. <token> The token sent to your third party identifier address
  239. <clientSecret> The same clientSecret you supplied in requestToken
  240. """
  241. args = self._parse(line, ['sid', 'token', 'clientSecret'])
  242. postArgs = { 'sid' : args['sid'], 'token' : args['token'], 'clientSecret': args['clientSecret'] }
  243. reactor.callFromThread(self._do_emailvalidate, postArgs)
  244. @defer.inlineCallbacks
  245. def _do_emailvalidate(self, args):
  246. url = self._identityServerUrl()+"/_matrix/identity/api/v1/validate/email/submitToken"
  247. json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False,
  248. headers={'Content-Type': ['application/x-www-form-urlencoded']})
  249. print json_res
  250. def do_3pidbind(self, line):
  251. """Validate and associate a third party ID
  252. <sid> The session ID (sid) given to you in the response to requestToken
  253. <clientSecret> The same clientSecret you supplied in requestToken
  254. """
  255. args = self._parse(line, ['sid', 'clientSecret'])
  256. postArgs = { 'sid' : args['sid'], 'clientSecret': args['clientSecret'] }
  257. postArgs['mxid'] = self.config["user"]
  258. reactor.callFromThread(self._do_3pidbind, postArgs)
  259. @defer.inlineCallbacks
  260. def _do_3pidbind(self, args):
  261. url = self._identityServerUrl()+"/_matrix/identity/api/v1/3pid/bind"
  262. json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False,
  263. headers={'Content-Type': ['application/x-www-form-urlencoded']})
  264. print json_res
  265. def do_join(self, line):
  266. """Joins a room: "join <roomid>" """
  267. try:
  268. args = self._parse(line, ["roomid"], force_keys=True)
  269. self._do_membership_change(args["roomid"], "join", self._usr())
  270. except Exception as e:
  271. print e
  272. def do_joinalias(self, line):
  273. try:
  274. args = self._parse(line, ["roomname"], force_keys=True)
  275. path = "/join/%s" % urllib.quote(args["roomname"])
  276. reactor.callFromThread(self._run_and_pprint, "POST", path, {})
  277. except Exception as e:
  278. print e
  279. def do_topic(self, line):
  280. """"topic [set|get] <roomid> [<newtopic>]"
  281. Set the topic for a room: topic set <roomid> <newtopic>
  282. Get the topic for a room: topic get <roomid>
  283. """
  284. try:
  285. args = self._parse(line, ["action", "roomid", "topic"])
  286. if "action" not in args or "roomid" not in args:
  287. print "Must specify set|get and a room ID."
  288. return
  289. if args["action"].lower() not in ["set", "get"]:
  290. print "Must specify set|get, not %s" % args["action"]
  291. return
  292. path = "/rooms/%s/topic" % urllib.quote(args["roomid"])
  293. if args["action"].lower() == "set":
  294. if "topic" not in args:
  295. print "Must specify a new topic."
  296. return
  297. body = {
  298. "topic": args["topic"]
  299. }
  300. reactor.callFromThread(self._run_and_pprint, "PUT", path, body)
  301. elif args["action"].lower() == "get":
  302. reactor.callFromThread(self._run_and_pprint, "GET", path)
  303. except Exception as e:
  304. print e
  305. def do_invite(self, line):
  306. """Invite a user to a room: "invite <userid> <roomid>" """
  307. try:
  308. args = self._parse(line, ["userid", "roomid"], force_keys=True)
  309. user_id = args["userid"]
  310. reactor.callFromThread(self._do_invite, args["roomid"], user_id)
  311. except Exception as e:
  312. print e
  313. @defer.inlineCallbacks
  314. def _do_invite(self, roomid, userstring):
  315. if (not userstring.startswith('@') and
  316. self._is_on("complete_usernames")):
  317. url = self._identityServerUrl()+"/_matrix/identity/api/v1/lookup"
  318. json_res = yield self.http_client.do_request("GET", url, qparams={'medium':'email','address':userstring})
  319. mxid = None
  320. if 'mxid' in json_res and 'signatures' in json_res:
  321. url = self._identityServerUrl()+"/_matrix/identity/api/v1/pubkey/ed25519"
  322. pubKey = None
  323. pubKeyObj = yield self.http_client.do_request("GET", url)
  324. if 'public_key' in pubKeyObj:
  325. pubKey = nacl.signing.VerifyKey(pubKeyObj['public_key'], encoder=nacl.encoding.HexEncoder)
  326. else:
  327. print "No public key found in pubkey response!"
  328. sigValid = False
  329. if pubKey:
  330. for signame in json_res['signatures']:
  331. if signame not in TRUSTED_ID_SERVERS:
  332. print "Ignoring signature from untrusted server %s" % (signame)
  333. else:
  334. try:
  335. verify_signed_json(json_res, signame, pubKey)
  336. sigValid = True
  337. print "Mapping %s -> %s correctly signed by %s" % (userstring, json_res['mxid'], signame)
  338. break
  339. except SignatureVerifyException as e:
  340. print "Invalid signature from %s" % (signame)
  341. print e
  342. if sigValid:
  343. print "Resolved 3pid %s to %s" % (userstring, json_res['mxid'])
  344. mxid = json_res['mxid']
  345. else:
  346. print "Got association for %s but couldn't verify signature" % (userstring)
  347. if not mxid:
  348. mxid = "@" + userstring + ":" + self._domain()
  349. self._do_membership_change(roomid, "invite", mxid)
  350. def do_leave(self, line):
  351. """Leaves a room: "leave <roomid>" """
  352. try:
  353. args = self._parse(line, ["roomid"], force_keys=True)
  354. self._do_membership_change(args["roomid"], "leave", self._usr())
  355. except Exception as e:
  356. print e
  357. def do_send(self, line):
  358. """Sends a message. "send <roomid> <body>" """
  359. args = self._parse(line, ["roomid", "body"])
  360. txn_id = "txn%s" % int(time.time())
  361. path = "/rooms/%s/send/m.room.message/%s" % (urllib.quote(args["roomid"]),
  362. txn_id)
  363. body_json = {
  364. "msgtype": "m.text",
  365. "body": args["body"]
  366. }
  367. reactor.callFromThread(self._run_and_pprint, "PUT", path, body_json)
  368. def do_list(self, line):
  369. """List data about a room.
  370. "list members <roomid> [query]" - List all the members in this room.
  371. "list messages <roomid> [query]" - List all the messages in this room.
  372. Where [query] will be directly applied as query parameters, allowing
  373. you to use the pagination API. E.g. the last 3 messages in this room:
  374. "list messages <roomid> from=END&to=START&limit=3"
  375. """
  376. args = self._parse(line, ["type", "roomid", "qp"])
  377. if not "type" in args or not "roomid" in args:
  378. print "Must specify type and room ID."
  379. return
  380. if args["type"] not in ["members", "messages"]:
  381. print "Unrecognised type: %s" % args["type"]
  382. return
  383. room_id = args["roomid"]
  384. path = "/rooms/%s/%s" % (urllib.quote(room_id), args["type"])
  385. qp = {"access_token": self._tok()}
  386. if "qp" in args:
  387. for key_value_str in args["qp"].split("&"):
  388. try:
  389. key_value = key_value_str.split("=")
  390. qp[key_value[0]] = key_value[1]
  391. except:
  392. print "Bad query param: %s" % key_value
  393. return
  394. reactor.callFromThread(self._run_and_pprint, "GET", path,
  395. query_params=qp)
  396. def do_create(self, line):
  397. """Creates a room.
  398. "create [public|private] <roomname>" - Create a room <roomname> with the
  399. specified visibility.
  400. "create <roomname>" - Create a room <roomname> with default visibility.
  401. "create [public|private]" - Create a room with specified visibility.
  402. "create" - Create a room with default visibility.
  403. """
  404. args = self._parse(line, ["vis", "roomname"])
  405. # fixup args depending on which were set
  406. body = {}
  407. if "vis" in args and args["vis"] in ["public", "private"]:
  408. body["visibility"] = args["vis"]
  409. if "roomname" in args:
  410. room_name = args["roomname"]
  411. body["room_alias_name"] = room_name
  412. elif "vis" in args and args["vis"] not in ["public", "private"]:
  413. room_name = args["vis"]
  414. body["room_alias_name"] = room_name
  415. reactor.callFromThread(self._run_and_pprint, "POST", "/createRoom", body)
  416. def do_raw(self, line):
  417. """Directly send a JSON object: "raw <method> <path> <data> <notoken>"
  418. <method>: Required. One of "PUT", "GET", "POST", "xPUT", "xGET",
  419. "xPOST". Methods with 'x' prefixed will not automatically append the
  420. access token.
  421. <path>: Required. E.g. "/events"
  422. <data>: Optional. E.g. "{ "msgtype":"custom.text", "body":"abc123"}"
  423. """
  424. args = self._parse(line, ["method", "path", "data"])
  425. # sanity check
  426. if "method" not in args or "path" not in args:
  427. print "Must specify path and method."
  428. return
  429. args["method"] = args["method"].upper()
  430. valid_methods = ["PUT", "GET", "POST", "DELETE",
  431. "XPUT", "XGET", "XPOST", "XDELETE"]
  432. if args["method"] not in valid_methods:
  433. print "Unsupported method: %s" % args["method"]
  434. return
  435. if "data" not in args:
  436. args["data"] = None
  437. else:
  438. try:
  439. args["data"] = json.loads(args["data"])
  440. except Exception as e:
  441. print "Data is not valid JSON. %s" % e
  442. return
  443. qp = {"access_token": self._tok()}
  444. if args["method"].startswith("X"):
  445. qp = {} # remove access token
  446. args["method"] = args["method"][1:] # snip the X
  447. else:
  448. # append any query params the user has set
  449. try:
  450. parsed_url = urlparse.urlparse(args["path"])
  451. qp.update(urlparse.parse_qs(parsed_url.query))
  452. args["path"] = parsed_url.path
  453. except:
  454. pass
  455. reactor.callFromThread(self._run_and_pprint, args["method"],
  456. args["path"],
  457. args["data"],
  458. query_params=qp)
  459. def do_stream(self, line):
  460. """Stream data from the server: "stream <longpoll timeout ms>" """
  461. args = self._parse(line, ["timeout"])
  462. timeout = 5000
  463. if "timeout" in args:
  464. try:
  465. timeout = int(args["timeout"])
  466. except ValueError:
  467. print "Timeout must be in milliseconds."
  468. return
  469. reactor.callFromThread(self._do_event_stream, timeout)
  470. @defer.inlineCallbacks
  471. def _do_event_stream(self, timeout):
  472. res = yield self.http_client.get_json(
  473. self._url() + "/events",
  474. {
  475. "access_token": self._tok(),
  476. "timeout": str(timeout),
  477. "from": self.event_stream_token
  478. })
  479. print json.dumps(res, indent=4)
  480. if "chunk" in res:
  481. for event in res["chunk"]:
  482. if (event["type"] == "m.room.message" and
  483. self._is_on("send_delivery_receipts") and
  484. event["user_id"] != self._usr()): # not sent by us
  485. self._send_receipt(event, "d")
  486. # update the position in the stram
  487. if "end" in res:
  488. self.event_stream_token = res["end"]
  489. def _send_receipt(self, event, feedback_type):
  490. path = ("/rooms/%s/messages/%s/%s/feedback/%s/%s" %
  491. (urllib.quote(event["room_id"]), event["user_id"], event["msg_id"],
  492. self._usr(), feedback_type))
  493. data = {}
  494. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data,
  495. alt_text="Sent receipt for %s" % event["msg_id"])
  496. def _do_membership_change(self, roomid, membership, userid):
  497. path = "/rooms/%s/state/m.room.member/%s" % (urllib.quote(roomid), urllib.quote(userid))
  498. data = {
  499. "membership": membership
  500. }
  501. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  502. def do_displayname(self, line):
  503. """Get or set my displayname: "displayname [new_name]" """
  504. args = self._parse(line, ["name"])
  505. path = "/profile/%s/displayname" % (self.config["user"])
  506. if "name" in args:
  507. data = {"displayname": args["name"]}
  508. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  509. else:
  510. reactor.callFromThread(self._run_and_pprint, "GET", path)
  511. def _do_presence_state(self, state, line):
  512. args = self._parse(line, ["msgstring"])
  513. path = "/presence/%s/status" % (self.config["user"])
  514. data = {"state": state}
  515. if "msgstring" in args:
  516. data["status_msg"] = args["msgstring"]
  517. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  518. def do_offline(self, line):
  519. """Set my presence state to OFFLINE"""
  520. self._do_presence_state(0, line)
  521. def do_away(self, line):
  522. """Set my presence state to AWAY"""
  523. self._do_presence_state(1, line)
  524. def do_online(self, line):
  525. """Set my presence state to ONLINE"""
  526. self._do_presence_state(2, line)
  527. def _parse(self, line, keys, force_keys=False):
  528. """ Parses the given line.
  529. Args:
  530. line : The line to parse
  531. keys : A list of keys to map onto the args
  532. force_keys : True to enforce that the line has a value for every key
  533. Returns:
  534. A dict of key:arg
  535. """
  536. line_args = shlex.split(line)
  537. if force_keys and len(line_args) != len(keys):
  538. raise IndexError("Must specify all args: %s" % keys)
  539. # do $ substitutions
  540. for i, arg in enumerate(line_args):
  541. for config_key in self.config:
  542. if ("$" + config_key) in arg:
  543. arg = arg.replace("$" + config_key,
  544. self.config[config_key])
  545. line_args[i] = arg
  546. return dict(zip(keys, line_args))
  547. @defer.inlineCallbacks
  548. def _run_and_pprint(self, method, path, data=None,
  549. query_params={"access_token": None}, alt_text=None):
  550. """ Runs an HTTP request and pretty prints the output.
  551. Args:
  552. method: HTTP method
  553. path: Relative path
  554. data: Raw JSON data if any
  555. query_params: dict of query parameters to add to the url
  556. """
  557. url = self._url() + path
  558. if "access_token" in query_params:
  559. query_params["access_token"] = self._tok()
  560. json_res = yield self.http_client.do_request(method, url,
  561. data=data,
  562. qparams=query_params)
  563. if alt_text:
  564. print alt_text
  565. else:
  566. print json.dumps(json_res, indent=4)
  567. def save_config(config):
  568. with open(CONFIG_JSON, 'w') as out:
  569. json.dump(config, out)
  570. def main(server_url, identity_server_url, username, token, config_path):
  571. print "Synapse command line client"
  572. print "==========================="
  573. print "Server: %s" % server_url
  574. print "Type 'help' to get started."
  575. print "Close this console with CTRL+C then CTRL+D."
  576. if not username or not token:
  577. print "- 'register <username>' - Register an account"
  578. print "- 'stream' - Connect to the event stream"
  579. print "- 'create <roomid>' - Create a room"
  580. print "- 'send <roomid> <message>' - Send a message"
  581. http_client = TwistedHttpClient()
  582. # the command line client
  583. syn_cmd = SynapseCmd(http_client, server_url, identity_server_url, username, token)
  584. # load synapse.json config from a previous session
  585. global CONFIG_JSON
  586. CONFIG_JSON = config_path # bit cheeky, but just overwrite the global
  587. try:
  588. with open(config_path, 'r') as config:
  589. syn_cmd.config = json.load(config)
  590. try:
  591. http_client.verbose = "on" == syn_cmd.config["verbose"]
  592. except:
  593. pass
  594. print "Loaded config from %s" % config_path
  595. except:
  596. pass
  597. # Twisted-specific: Runs the command processor in Twisted's event loop
  598. # to maintain a single thread for both commands and event processing.
  599. # If using another HTTP client, just call syn_cmd.cmdloop()
  600. reactor.callInThread(syn_cmd.cmdloop)
  601. reactor.run()
  602. if __name__ == '__main__':
  603. parser = argparse.ArgumentParser("Starts a synapse client.")
  604. parser.add_argument(
  605. "-s", "--server", dest="server", default="http://localhost:8008",
  606. help="The URL of the home server to talk to.")
  607. parser.add_argument(
  608. "-i", "--identity-server", dest="identityserver", default="http://localhost:8090",
  609. help="The URL of the identity server to talk to.")
  610. parser.add_argument(
  611. "-u", "--username", dest="username",
  612. help="Your username on the server.")
  613. parser.add_argument(
  614. "-t", "--token", dest="token",
  615. help="Your access token.")
  616. parser.add_argument(
  617. "-c", "--config", dest="config", default=CONFIG_JSON,
  618. help="The location of the config.json file to read from.")
  619. args = parser.parse_args()
  620. if not args.server:
  621. print "You must supply a server URL to communicate with."
  622. parser.print_help()
  623. sys.exit(1)
  624. server = args.server
  625. if not server.startswith("http://"):
  626. server = "http://" + args.server
  627. main(server, args.identityserver, args.username, args.token, args.config)