Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2014
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.16 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import argparse
  4. import code
  5. import sys
  6. import threading
  7. import websocket
  8. import json
  9. import time
  10.  
  11. global timer_stopped
  12. global description
  13. global duration
  14. timer_stopped = True
  15. description = ''
  16.  
  17. OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
  18. ENCODING = getattr(sys.stdin, "encoding", "").lower()
  19.  
  20. class VAction(argparse.Action):
  21. def __call__(self, parser, args, values, option_string=None):
  22. if values==None:
  23. values = "1"
  24. try:
  25. values = int(values)
  26. except ValueError:
  27. values = values.count("v")+1
  28. setattr(args, self.dest, values)
  29.  
  30. def parse_args():
  31. parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool")
  32. parser.add_argument("url", metavar="ws_url", nargs='?',
  33. default='wss://stream.toggl.com/ws',
  34. help="websocket url. ex. ws://echo.websocket.org/")
  35. parser.add_argument("key",
  36. help="api key")
  37.  
  38. return parser.parse_args()
  39.  
  40.  
  41. class InteractiveConsole(code.InteractiveConsole):
  42. def write(self, data):
  43. sys.stdout.write("\n")
  44. sys.stdout.flush()
  45.  
  46. def raw_input(self, prompt):
  47. line = raw_input(prompt)
  48. if ENCODING and ENCODING != "utf-8" and not isinstance(line, unicode):
  49. line = line.decode(ENCODING).encode("utf-8")
  50. elif isinstance(line, unicode):
  51. line = encode("utf-8")
  52.  
  53. return line
  54.  
  55.  
  56. def main():
  57. args = parse_args()
  58. console = InteractiveConsole()
  59. ws = websocket.create_connection(args.url)
  60.  
  61. ws.send( '{"type":"authenticate","api_token":"' + args.key + '"}' )
  62.  
  63. def recv():
  64. frame = ws.recv_frame()
  65. if not frame:
  66. raise websocket.WebSocketException("Not a valid frame %s" % frame)
  67. elif frame.opcode in OPCODE_DATA:
  68. return (frame.opcode, frame.data)
  69. elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
  70. ws.send_close()
  71. return (frame.opcode, None)
  72. elif frame.opcode == websocket.ABNF.OPCODE_PING:
  73. ws.pong("Hi!")
  74.  
  75. return None, None
  76.  
  77.  
  78. def recv_ws():
  79. global timer_stopped
  80. global duration
  81. global description
  82. while True:
  83. opcode, data = recv()
  84. if data == '{"type":"ping"}':
  85. ws.send('{"type":"pong"}')
  86. else:
  87. msgobj = None
  88. if opcode in OPCODE_DATA:
  89. msgobj = json.loads(data)
  90.  
  91. if msgobj:
  92. if (msgobj['data']['stop'] == None):
  93. timer_stopped = False
  94. else:
  95. timer_stopped = True
  96. description = msgobj['data']['description']
  97. duration = msgobj['data']['duration']
  98.  
  99.  
  100. thread = threading.Thread(target=recv_ws)
  101. thread.daemon = True
  102. thread.start()
  103.  
  104. def stdout_update():
  105. global timer_stopped
  106. global duration
  107. global description
  108. while True:
  109. if (timer_stopped):
  110. sys.stdout.write("\r \r")
  111. else:
  112. now = int(time.time())
  113. elapsed = now + int(duration)
  114. elapsed_str = time.strftime('%H:%M:%S', time.gmtime(elapsed))
  115. sys.stdout.write("\r " +
  116. str(elapsed_str) +
  117. " " +
  118. description +
  119. " \r")
  120. sys.stdout.flush()
  121. time.sleep(1)
  122.  
  123. thread = threading.Thread(target=stdout_update)
  124. thread.daemon = True
  125. thread.start()
  126.  
  127.  
  128. while True:
  129. try:
  130. message = console.raw_input("")
  131. except KeyboardInterrupt:
  132. sys.stdout.write("\n")
  133. return
  134. except EOFError:
  135. sys.stdout.write("\n")
  136. return
  137.  
  138.  
  139. if __name__ == "__main__":
  140. try:
  141. main()
  142. except Exception, e:
  143. print(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement