magic-wormhole/src/wormhole/twisted/demo.py

42 lines
1.3 KiB
Python
Raw Normal View History

from __future__ import print_function
2015-07-25 01:04:15 +00:00
import sys, json
from twisted.internet import reactor
2015-07-25 01:04:15 +00:00
from .transcribe import Wormhole
from .. import public_relay
APPID = "lothar.com/wormhole/text-xfer"
2015-07-25 01:04:15 +00:00
w = Wormhole(APPID, public_relay.RENDEZVOUS_RELAY)
if sys.argv[1] == "send-text":
message = sys.argv[2]
2015-07-25 01:04:15 +00:00
data = json.dumps({"message": message}).encode("utf-8")
d = w.get_code()
def _got_code(code):
print("code is:", code)
2015-07-25 01:04:15 +00:00
return w.get_data(data)
d.addCallback(_got_code)
2015-07-25 01:04:15 +00:00
def _got_data(them_bytes):
them_d = json.loads(them_bytes.decode("utf-8"))
if them_d["message"] == "ok":
print("text sent")
2015-07-25 01:04:15 +00:00
else:
print("error sending text: %r" % (them_d,))
d.addCallback(_got_data)
elif sys.argv[1] == "receive-text":
code = sys.argv[2]
w.set_code(code)
2015-07-25 01:04:15 +00:00
data = json.dumps({"message": "ok"}).encode("utf-8")
d = w.get_data(data)
def _got_data(them_bytes):
them_d = json.loads(them_bytes.decode("utf-8"))
if "error" in them_d:
print("ERROR: " + them_d["error"], file=sys.stderr)
2015-07-25 01:04:15 +00:00
return 1
print(them_d["message"])
d.addCallback(_got_data)
else:
raise ValueError("bad command")
d.addCallback(lambda _: reactor.stop())
reactor.run()