Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import inspect
  2. import selectors
  3. import sys
  4. import threading
  5. import time
  6. import traceback
  7. import socket
  8. from typing import Callable, Any
  9. from . import _logging
  10. from ._abnf import ABNF
  11. from ._url import parse_url
  12. from ._core import WebSocket, getdefaulttimeout
  13. from ._exceptions import *
  14. """
  15. _app.py
  16. websocket - WebSocket client library for Python
  17. Copyright 2023 engn33r
  18. Licensed under the Apache License, Version 2.0 (the "License");
  19. you may not use this file except in compliance with the License.
  20. You may obtain a copy of the License at
  21. http://www.apache.org/licenses/LICENSE-2.0
  22. Unless required by applicable law or agreed to in writing, software
  23. distributed under the License is distributed on an "AS IS" BASIS,
  24. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. See the License for the specific language governing permissions and
  26. limitations under the License.
  27. """
  28. __all__ = ["WebSocketApp"]
  29. RECONNECT = 0
  30. def setReconnect(reconnectInterval: int) -> None:
  31. global RECONNECT
  32. RECONNECT = reconnectInterval
  33. class DispatcherBase:
  34. """
  35. DispatcherBase
  36. """
  37. def __init__(self, app: Any, ping_timeout: float) -> None:
  38. self.app = app
  39. self.ping_timeout = ping_timeout
  40. def timeout(self, seconds: int, callback: Callable) -> None:
  41. time.sleep(seconds)
  42. callback()
  43. def reconnect(self, seconds: int, reconnector: Callable) -> None:
  44. try:
  45. _logging.info("reconnect() - retrying in {seconds_count} seconds [{frame_count} frames in stack]".format(
  46. seconds_count=seconds, frame_count=len(inspect.stack())))
  47. time.sleep(seconds)
  48. reconnector(reconnecting=True)
  49. except KeyboardInterrupt as e:
  50. _logging.info("User exited {err}".format(err=e))
  51. raise e
  52. class Dispatcher(DispatcherBase):
  53. """
  54. Dispatcher
  55. """
  56. def read(self, sock: socket.socket, read_callback: Callable, check_callback: Callable) -> None:
  57. sel = selectors.DefaultSelector()
  58. sel.register(self.app.sock.sock, selectors.EVENT_READ)
  59. try:
  60. while self.app.keep_running:
  61. r = sel.select(self.ping_timeout)
  62. if r:
  63. if not read_callback():
  64. break
  65. check_callback()
  66. finally:
  67. sel.close()
  68. class SSLDispatcher(DispatcherBase):
  69. """
  70. SSLDispatcher
  71. """
  72. def read(self, sock: socket.socket, read_callback: Callable, check_callback: Callable) -> None:
  73. sock = self.app.sock.sock
  74. sel = selectors.DefaultSelector()
  75. sel.register(sock, selectors.EVENT_READ)
  76. try:
  77. while self.app.keep_running:
  78. r = self.select(sock, sel)
  79. if r:
  80. if not read_callback():
  81. break
  82. check_callback()
  83. finally:
  84. sel.close()
  85. def select(self, sock, sel:selectors.DefaultSelector):
  86. sock = self.app.sock.sock
  87. if sock.pending():
  88. return [sock,]
  89. r = sel.select(self.ping_timeout)
  90. if len(r) > 0:
  91. return r[0][0]
  92. class WrappedDispatcher:
  93. """
  94. WrappedDispatcher
  95. """
  96. def __init__(self, app, ping_timeout: float, dispatcher: Dispatcher) -> None:
  97. self.app = app
  98. self.ping_timeout = ping_timeout
  99. self.dispatcher = dispatcher
  100. dispatcher.signal(2, dispatcher.abort) # keyboard interrupt
  101. def read(self, sock: socket.socket, read_callback: Callable, check_callback: Callable) -> None:
  102. self.dispatcher.read(sock, read_callback)
  103. self.ping_timeout and self.timeout(self.ping_timeout, check_callback)
  104. def timeout(self, seconds: int, callback: Callable) -> None:
  105. self.dispatcher.timeout(seconds, callback)
  106. def reconnect(self, seconds: int, reconnector: Callable) -> None:
  107. self.timeout(seconds, reconnector)
  108. class WebSocketApp:
  109. """
  110. Higher level of APIs are provided. The interface is like JavaScript WebSocket object.
  111. """
  112. def __init__(self, url: str, header: list or dict = None,
  113. on_open: Callable = None, on_message: Callable = None, on_error: Callable = None,
  114. on_close: Callable = None, on_ping: Callable = None, on_pong: Callable = None,
  115. on_cont_message: Callable = None,
  116. keep_running: bool = True, get_mask_key: Callable = None, cookie: str = None,
  117. subprotocols: list = None,
  118. on_data: Callable = None,
  119. socket: socket.socket = None) -> None:
  120. """
  121. WebSocketApp initialization
  122. Parameters
  123. ----------
  124. url: str
  125. Websocket url.
  126. header: list or dict
  127. Custom header for websocket handshake.
  128. on_open: function
  129. Callback object which is called at opening websocket.
  130. on_open has one argument.
  131. The 1st argument is this class object.
  132. on_message: function
  133. Callback object which is called when received data.
  134. on_message has 2 arguments.
  135. The 1st argument is this class object.
  136. The 2nd argument is utf-8 data received from the server.
  137. on_error: function
  138. Callback object which is called when we get error.
  139. on_error has 2 arguments.
  140. The 1st argument is this class object.
  141. The 2nd argument is exception object.
  142. on_close: function
  143. Callback object which is called when connection is closed.
  144. on_close has 3 arguments.
  145. The 1st argument is this class object.
  146. The 2nd argument is close_status_code.
  147. The 3rd argument is close_msg.
  148. on_cont_message: function
  149. Callback object which is called when a continuation
  150. frame is received.
  151. on_cont_message has 3 arguments.
  152. The 1st argument is this class object.
  153. The 2nd argument is utf-8 string which we get from the server.
  154. The 3rd argument is continue flag. if 0, the data continue
  155. to next frame data
  156. on_data: function
  157. Callback object which is called when a message received.
  158. This is called before on_message or on_cont_message,
  159. and then on_message or on_cont_message is called.
  160. on_data has 4 argument.
  161. The 1st argument is this class object.
  162. The 2nd argument is utf-8 string which we get from the server.
  163. The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
  164. The 4th argument is continue flag. If 0, the data continue
  165. keep_running: bool
  166. This parameter is obsolete and ignored.
  167. get_mask_key: function
  168. A callable function to get new mask keys, see the
  169. WebSocket.set_mask_key's docstring for more information.
  170. cookie: str
  171. Cookie value.
  172. subprotocols: list
  173. List of available sub protocols. Default is None.
  174. socket: socket
  175. Pre-initialized stream socket.
  176. """
  177. self.url = url
  178. self.header = header if header is not None else []
  179. self.cookie = cookie
  180. self.on_open = on_open
  181. self.on_message = on_message
  182. self.on_data = on_data
  183. self.on_error = on_error
  184. self.on_close = on_close
  185. self.on_ping = on_ping
  186. self.on_pong = on_pong
  187. self.on_cont_message = on_cont_message
  188. self.keep_running = False
  189. self.get_mask_key = get_mask_key
  190. self.sock = None
  191. self.last_ping_tm = 0
  192. self.last_pong_tm = 0
  193. self.ping_thread = None
  194. self.stop_ping = None
  195. self.ping_interval = 0
  196. self.ping_timeout = None
  197. self.ping_payload = ""
  198. self.subprotocols = subprotocols
  199. self.prepared_socket = socket
  200. self.has_errored = False
  201. self.has_done_teardown = False
  202. self.has_done_teardown_lock = threading.Lock()
  203. def send(self, data: str, opcode: int = ABNF.OPCODE_TEXT) -> None:
  204. """
  205. send message
  206. Parameters
  207. ----------
  208. data: str
  209. Message to send. If you set opcode to OPCODE_TEXT,
  210. data must be utf-8 string or unicode.
  211. opcode: int
  212. Operation code of data. Default is OPCODE_TEXT.
  213. """
  214. if not self.sock or self.sock.send(data, opcode) == 0:
  215. raise WebSocketConnectionClosedException(
  216. "Connection is already closed.")
  217. def close(self, **kwargs) -> None:
  218. """
  219. Close websocket connection.
  220. """
  221. self.keep_running = False
  222. if self.sock:
  223. self.sock.close(**kwargs)
  224. self.sock = None
  225. def _start_ping_thread(self) -> None:
  226. self.last_ping_tm = self.last_pong_tm = 0
  227. self.stop_ping = threading.Event()
  228. self.ping_thread = threading.Thread(target=self._send_ping)
  229. self.ping_thread.daemon = True
  230. self.ping_thread.start()
  231. def _stop_ping_thread(self) -> None:
  232. if self.stop_ping:
  233. self.stop_ping.set()
  234. if self.ping_thread and self.ping_thread.is_alive():
  235. self.ping_thread.join(3)
  236. self.last_ping_tm = self.last_pong_tm = 0
  237. def _send_ping(self) -> None:
  238. if self.stop_ping.wait(self.ping_interval) or self.keep_running is False:
  239. return
  240. while not self.stop_ping.wait(self.ping_interval) and self.keep_running is True:
  241. if self.sock:
  242. self.last_ping_tm = time.time()
  243. try:
  244. _logging.debug("Sending ping")
  245. self.sock.ping(self.ping_payload)
  246. except Exception as e:
  247. _logging.debug("Failed to send ping: {err}".format(err=e))
  248. def run_forever(self, sockopt: tuple = None, sslopt: dict = None,
  249. ping_interval: float = 0, ping_timeout: float or None = None,
  250. ping_payload: str = "",
  251. http_proxy_host: str = None, http_proxy_port: int or str = None,
  252. http_no_proxy: list = None, http_proxy_auth: tuple = None,
  253. http_proxy_timeout: float = None,
  254. skip_utf8_validation: bool = False,
  255. host: str = None, origin: str = None, dispatcher: Dispatcher = None,
  256. suppress_origin: bool = False, proxy_type: str = None, reconnect: int = None) -> bool:
  257. """
  258. Run event loop for WebSocket framework.
  259. This loop is an infinite loop and is alive while websocket is available.
  260. Parameters
  261. ----------
  262. sockopt: tuple
  263. Values for socket.setsockopt.
  264. sockopt must be tuple
  265. and each element is argument of sock.setsockopt.
  266. sslopt: dict
  267. Optional dict object for ssl socket option.
  268. ping_interval: int or float
  269. Automatically send "ping" command
  270. every specified period (in seconds).
  271. If set to 0, no ping is sent periodically.
  272. ping_timeout: int or float
  273. Timeout (in seconds) if the pong message is not received.
  274. ping_payload: str
  275. Payload message to send with each ping.
  276. http_proxy_host: str
  277. HTTP proxy host name.
  278. http_proxy_port: int or str
  279. HTTP proxy port. If not set, set to 80.
  280. http_no_proxy: list
  281. Whitelisted host names that don't use the proxy.
  282. http_proxy_timeout: int or float
  283. HTTP proxy timeout, default is 60 sec as per python-socks.
  284. http_proxy_auth: tuple
  285. HTTP proxy auth information. tuple of username and password. Default is None.
  286. skip_utf8_validation: bool
  287. skip utf8 validation.
  288. host: str
  289. update host header.
  290. origin: str
  291. update origin header.
  292. dispatcher: Dispatcher object
  293. customize reading data from socket.
  294. suppress_origin: bool
  295. suppress outputting origin header.
  296. proxy_type: str
  297. type of proxy from: http, socks4, socks4a, socks5, socks5h
  298. reconnect: int
  299. delay interval when reconnecting
  300. Returns
  301. -------
  302. teardown: bool
  303. False if the `WebSocketApp` is closed or caught KeyboardInterrupt,
  304. True if any other exception was raised during a loop.
  305. """
  306. if reconnect is None:
  307. reconnect = RECONNECT
  308. if ping_timeout is not None and ping_timeout <= 0:
  309. raise WebSocketException("Ensure ping_timeout > 0")
  310. if ping_interval is not None and ping_interval < 0:
  311. raise WebSocketException("Ensure ping_interval >= 0")
  312. if ping_timeout and ping_interval and ping_interval <= ping_timeout:
  313. raise WebSocketException("Ensure ping_interval > ping_timeout")
  314. if not sockopt:
  315. sockopt = []
  316. if not sslopt:
  317. sslopt = {}
  318. if self.sock:
  319. raise WebSocketException("socket is already opened")
  320. self.ping_interval = ping_interval
  321. self.ping_timeout = ping_timeout
  322. self.ping_payload = ping_payload
  323. self.keep_running = True
  324. def teardown(close_frame: ABNF = None):
  325. """
  326. Tears down the connection.
  327. Parameters
  328. ----------
  329. close_frame: ABNF frame
  330. If close_frame is set, the on_close handler is invoked
  331. with the statusCode and reason from the provided frame.
  332. """
  333. # teardown() is called in many code paths to ensure resources are cleaned up and on_close is fired.
  334. # To ensure the work is only done once, we use this bool and lock.
  335. with self.has_done_teardown_lock:
  336. if self.has_done_teardown:
  337. return
  338. self.has_done_teardown = True
  339. self._stop_ping_thread()
  340. self.keep_running = False
  341. if self.sock:
  342. self.sock.close()
  343. close_status_code, close_reason = self._get_close_args(
  344. close_frame if close_frame else None)
  345. self.sock = None
  346. # Finally call the callback AFTER all teardown is complete
  347. self._callback(self.on_close, close_status_code, close_reason)
  348. def setSock(reconnecting: bool = False) -> None:
  349. if reconnecting and self.sock:
  350. self.sock.shutdown()
  351. self.sock = WebSocket(
  352. self.get_mask_key, sockopt=sockopt, sslopt=sslopt,
  353. fire_cont_frame=self.on_cont_message is not None,
  354. skip_utf8_validation=skip_utf8_validation,
  355. enable_multithread=True)
  356. self.sock.settimeout(getdefaulttimeout())
  357. try:
  358. self.sock.connect(
  359. self.url, header=self.header, cookie=self.cookie,
  360. http_proxy_host=http_proxy_host,
  361. http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy,
  362. http_proxy_auth=http_proxy_auth, http_proxy_timeout=http_proxy_timeout,
  363. subprotocols=self.subprotocols,
  364. host=host, origin=origin, suppress_origin=suppress_origin,
  365. proxy_type=proxy_type, socket=self.prepared_socket)
  366. _logging.info("Websocket connected")
  367. if self.ping_interval:
  368. self._start_ping_thread()
  369. self._callback(self.on_open)
  370. dispatcher.read(self.sock.sock, read, check)
  371. except (WebSocketConnectionClosedException, ConnectionRefusedError, KeyboardInterrupt, SystemExit, Exception) as e:
  372. handleDisconnect(e, reconnecting)
  373. def read() -> bool:
  374. if not self.keep_running:
  375. return teardown()
  376. try:
  377. op_code, frame = self.sock.recv_data_frame(True)
  378. except (WebSocketConnectionClosedException, KeyboardInterrupt) as e:
  379. if custom_dispatcher:
  380. return handleDisconnect(e)
  381. else:
  382. raise e
  383. if op_code == ABNF.OPCODE_CLOSE:
  384. return teardown(frame)
  385. elif op_code == ABNF.OPCODE_PING:
  386. self._callback(self.on_ping, frame.data)
  387. elif op_code == ABNF.OPCODE_PONG:
  388. self.last_pong_tm = time.time()
  389. self._callback(self.on_pong, frame.data)
  390. elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:
  391. self._callback(self.on_data, frame.data,
  392. frame.opcode, frame.fin)
  393. self._callback(self.on_cont_message,
  394. frame.data, frame.fin)
  395. else:
  396. data = frame.data
  397. if op_code == ABNF.OPCODE_TEXT and not skip_utf8_validation:
  398. data = data.decode("utf-8")
  399. self._callback(self.on_data, data, frame.opcode, True)
  400. self._callback(self.on_message, data)
  401. return True
  402. def check() -> bool:
  403. if (self.ping_timeout):
  404. has_timeout_expired = time.time() - self.last_ping_tm > self.ping_timeout
  405. has_pong_not_arrived_after_last_ping = self.last_pong_tm - self.last_ping_tm < 0
  406. has_pong_arrived_too_late = self.last_pong_tm - self.last_ping_tm > self.ping_timeout
  407. if (self.last_ping_tm and
  408. has_timeout_expired and
  409. (has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late)):
  410. raise WebSocketTimeoutException("ping/pong timed out")
  411. return True
  412. def handleDisconnect(e: Exception, reconnecting: bool = False) -> bool:
  413. self.has_errored = True
  414. self._stop_ping_thread()
  415. if not reconnecting:
  416. self._callback(self.on_error, e)
  417. if isinstance(e, (KeyboardInterrupt, SystemExit)):
  418. teardown()
  419. # Propagate further
  420. raise
  421. if reconnect:
  422. _logging.info("{err} - reconnect".format(err=e))
  423. if custom_dispatcher:
  424. _logging.debug("Calling custom dispatcher reconnect [{frame_count} frames in stack]".format(frame_count=len(inspect.stack())))
  425. dispatcher.reconnect(reconnect, setSock)
  426. else:
  427. _logging.error("{err} - goodbye".format(err=e))
  428. teardown()
  429. custom_dispatcher = bool(dispatcher)
  430. dispatcher = self.create_dispatcher(ping_timeout, dispatcher, parse_url(self.url)[3])
  431. try:
  432. setSock()
  433. if not custom_dispatcher and reconnect:
  434. while self.keep_running:
  435. _logging.debug("Calling dispatcher reconnect [{frame_count} frames in stack]".format(frame_count=len(inspect.stack())))
  436. dispatcher.reconnect(reconnect, setSock)
  437. except (KeyboardInterrupt, Exception) as e:
  438. _logging.info("tearing down on exception {err}".format(err=e))
  439. teardown()
  440. finally:
  441. if not custom_dispatcher:
  442. # Ensure teardown was called before returning from run_forever
  443. teardown()
  444. return self.has_errored
  445. def create_dispatcher(self, ping_timeout: int, dispatcher: Dispatcher = None, is_ssl: bool = False) -> DispatcherBase:
  446. if dispatcher: # If custom dispatcher is set, use WrappedDispatcher
  447. return WrappedDispatcher(self, ping_timeout, dispatcher)
  448. timeout = ping_timeout or 10
  449. if is_ssl:
  450. return SSLDispatcher(self, timeout)
  451. return Dispatcher(self, timeout)
  452. def _get_close_args(self, close_frame: ABNF) -> list:
  453. """
  454. _get_close_args extracts the close code and reason from the close body
  455. if it exists (RFC6455 says WebSocket Connection Close Code is optional)
  456. """
  457. # Need to catch the case where close_frame is None
  458. # Otherwise the following if statement causes an error
  459. if not self.on_close or not close_frame:
  460. return [None, None]
  461. # Extract close frame status code
  462. if close_frame.data and len(close_frame.data) >= 2:
  463. close_status_code = 256 * close_frame.data[0] + close_frame.data[1]
  464. reason = close_frame.data[2:].decode('utf-8')
  465. return [close_status_code, reason]
  466. else:
  467. # Most likely reached this because len(close_frame_data.data) < 2
  468. return [None, None]
  469. def _callback(self, callback, *args) -> None:
  470. if callback:
  471. try:
  472. callback(self, *args)
  473. except Exception as e:
  474. _logging.error("error from callback {callback}: {err}".format(callback=callback, err=e))
  475. if self.on_error:
  476. self.on_error(self, e)