Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import argparse
- import code
- import sys
- import threading
- import websocket
- import json
- import time
- global timer_stopped
- global description
- global duration
- timer_stopped = True
- description = ''
- OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
- ENCODING = getattr(sys.stdin, "encoding", "").lower()
- class VAction(argparse.Action):
- def __call__(self, parser, args, values, option_string=None):
- if values==None:
- values = "1"
- try:
- values = int(values)
- except ValueError:
- values = values.count("v")+1
- setattr(args, self.dest, values)
- def parse_args():
- parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool")
- parser.add_argument("url", metavar="ws_url", nargs='?',
- default='wss://stream.toggl.com/ws',
- help="websocket url. ex. ws://echo.websocket.org/")
- parser.add_argument("key",
- help="api key")
- return parser.parse_args()
- class InteractiveConsole(code.InteractiveConsole):
- def write(self, data):
- sys.stdout.write("\n")
- sys.stdout.flush()
- def raw_input(self, prompt):
- line = raw_input(prompt)
- if ENCODING and ENCODING != "utf-8" and not isinstance(line, unicode):
- line = line.decode(ENCODING).encode("utf-8")
- elif isinstance(line, unicode):
- line = encode("utf-8")
- return line
- def main():
- args = parse_args()
- console = InteractiveConsole()
- ws = websocket.create_connection(args.url)
- ws.send( '{"type":"authenticate","api_token":"' + args.key + '"}' )
- def recv():
- frame = ws.recv_frame()
- if not frame:
- raise websocket.WebSocketException("Not a valid frame %s" % frame)
- elif frame.opcode in OPCODE_DATA:
- return (frame.opcode, frame.data)
- elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
- ws.send_close()
- return (frame.opcode, None)
- elif frame.opcode == websocket.ABNF.OPCODE_PING:
- ws.pong("Hi!")
- return None, None
- def recv_ws():
- global timer_stopped
- global duration
- global description
- while True:
- opcode, data = recv()
- if data == '{"type":"ping"}':
- ws.send('{"type":"pong"}')
- else:
- msgobj = None
- if opcode in OPCODE_DATA:
- msgobj = json.loads(data)
- if msgobj:
- if (msgobj['data']['stop'] == None):
- timer_stopped = False
- else:
- timer_stopped = True
- description = msgobj['data']['description']
- duration = msgobj['data']['duration']
- thread = threading.Thread(target=recv_ws)
- thread.daemon = True
- thread.start()
- def stdout_update():
- global timer_stopped
- global duration
- global description
- while True:
- if (timer_stopped):
- sys.stdout.write("\r \r")
- else:
- now = int(time.time())
- elapsed = now + int(duration)
- elapsed_str = time.strftime('%H:%M:%S', time.gmtime(elapsed))
- sys.stdout.write("\r " +
- str(elapsed_str) +
- " " +
- description +
- " \r")
- sys.stdout.flush()
- time.sleep(1)
- thread = threading.Thread(target=stdout_update)
- thread.daemon = True
- thread.start()
- while True:
- try:
- message = console.raw_input("")
- except KeyboardInterrupt:
- sys.stdout.write("\n")
- return
- except EOFError:
- sys.stdout.write("\n")
- return
- if __name__ == "__main__":
- try:
- main()
- except Exception, e:
- print(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement