No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

524 líneas
25KB

  1. import asyncio
  2. import engineio
  3. import six
  4. from . import asyncio_manager
  5. from . import exceptions
  6. from . import packet
  7. from . import server
  8. class AsyncServer(server.Server):
  9. """A Socket.IO server for asyncio.
  10. This class implements a fully compliant Socket.IO web server with support
  11. for websocket and long-polling transports, compatible with the asyncio
  12. framework on Python 3.5 or newer.
  13. :param client_manager: The client manager instance that will manage the
  14. client list. When this is omitted, the client list
  15. is stored in an in-memory structure, so the use of
  16. multiple connected servers is not possible.
  17. :param logger: To enable logging set to ``True`` or pass a logger object to
  18. use. To disable logging set to ``False``.
  19. :param json: An alternative json module to use for encoding and decoding
  20. packets. Custom json modules must have ``dumps`` and ``loads``
  21. functions that are compatible with the standard library
  22. versions.
  23. :param async_handlers: If set to ``True``, event handlers are executed in
  24. separate threads. To run handlers synchronously,
  25. set to ``False``. The default is ``True``.
  26. :param kwargs: Connection parameters for the underlying Engine.IO server.
  27. The Engine.IO configuration supports the following settings:
  28. :param async_mode: The asynchronous model to use. See the Deployment
  29. section in the documentation for a description of the
  30. available options. Valid async modes are "aiohttp". If
  31. this argument is not given, an async mode is chosen
  32. based on the installed packages.
  33. :param ping_timeout: The time in seconds that the client waits for the
  34. server to respond before disconnecting.
  35. :param ping_interval: The interval in seconds at which the client pings
  36. the server.
  37. :param max_http_buffer_size: The maximum size of a message when using the
  38. polling transport.
  39. :param allow_upgrades: Whether to allow transport upgrades or not.
  40. :param http_compression: Whether to compress packages when using the
  41. polling transport.
  42. :param compression_threshold: Only compress messages when their byte size
  43. is greater than this value.
  44. :param cookie: Name of the HTTP cookie that contains the client session
  45. id. If set to ``None``, a cookie is not sent to the client.
  46. :param cors_allowed_origins: Origin or list of origins that are allowed to
  47. connect to this server. Only the same origin
  48. is allowed by default. Set this argument to
  49. ``'*'`` to allow all origins, or to ``[]`` to
  50. disable CORS handling.
  51. :param cors_credentials: Whether credentials (cookies, authentication) are
  52. allowed in requests to this server.
  53. :param monitor_clients: If set to ``True``, a background task will ensure
  54. inactive clients are closed. Set to ``False`` to
  55. disable the monitoring task (not recommended). The
  56. default is ``True``.
  57. :param engineio_logger: To enable Engine.IO logging set to ``True`` or pass
  58. a logger object to use. To disable logging set to
  59. ``False``.
  60. """
  61. def __init__(self, client_manager=None, logger=False, json=None,
  62. async_handlers=True, **kwargs):
  63. if client_manager is None:
  64. client_manager = asyncio_manager.AsyncManager()
  65. super().__init__(client_manager=client_manager, logger=logger,
  66. binary=False, json=json,
  67. async_handlers=async_handlers, **kwargs)
  68. def is_asyncio_based(self):
  69. return True
  70. def attach(self, app, socketio_path='socket.io'):
  71. """Attach the Socket.IO server to an application."""
  72. self.eio.attach(app, socketio_path)
  73. async def emit(self, event, data=None, to=None, room=None, skip_sid=None,
  74. namespace=None, callback=None, **kwargs):
  75. """Emit a custom event to one or more connected clients.
  76. :param event: The event name. It can be any string. The event names
  77. ``'connect'``, ``'message'`` and ``'disconnect'`` are
  78. reserved and should not be used.
  79. :param data: The data to send to the client or clients. Data can be of
  80. type ``str``, ``bytes``, ``list`` or ``dict``. If a
  81. ``list`` or ``dict``, the data will be serialized as JSON.
  82. :param to: The recipient of the message. This can be set to the
  83. session ID of a client to address only that client, or to
  84. to any custom room created by the application to address all
  85. the clients in that room, If this argument is omitted the
  86. event is broadcasted to all connected clients.
  87. :param room: Alias for the ``to`` parameter.
  88. :param skip_sid: The session ID of a client to skip when broadcasting
  89. to a room or to all clients. This can be used to
  90. prevent a message from being sent to the sender.
  91. :param namespace: The Socket.IO namespace for the event. If this
  92. argument is omitted the event is emitted to the
  93. default namespace.
  94. :param callback: If given, this function will be called to acknowledge
  95. the the client has received the message. The arguments
  96. that will be passed to the function are those provided
  97. by the client. Callback functions can only be used
  98. when addressing an individual client.
  99. :param ignore_queue: Only used when a message queue is configured. If
  100. set to ``True``, the event is emitted to the
  101. clients directly, without going through the queue.
  102. This is more efficient, but only works when a
  103. single server process is used. It is recommended
  104. to always leave this parameter with its default
  105. value of ``False``.
  106. Note: this method is a coroutine.
  107. """
  108. namespace = namespace or '/'
  109. room = to or room
  110. self.logger.info('emitting event "%s" to %s [%s]', event,
  111. room or 'all', namespace)
  112. await self.manager.emit(event, data, namespace, room=room,
  113. skip_sid=skip_sid, callback=callback,
  114. **kwargs)
  115. async def send(self, data, to=None, room=None, skip_sid=None,
  116. namespace=None, callback=None, **kwargs):
  117. """Send a message to one or more connected clients.
  118. This function emits an event with the name ``'message'``. Use
  119. :func:`emit` to issue custom event names.
  120. :param data: The data to send to the client or clients. Data can be of
  121. type ``str``, ``bytes``, ``list`` or ``dict``. If a
  122. ``list`` or ``dict``, the data will be serialized as JSON.
  123. :param to: The recipient of the message. This can be set to the
  124. session ID of a client to address only that client, or to
  125. to any custom room created by the application to address all
  126. the clients in that room, If this argument is omitted the
  127. event is broadcasted to all connected clients.
  128. :param room: Alias for the ``to`` parameter.
  129. :param skip_sid: The session ID of a client to skip when broadcasting
  130. to a room or to all clients. This can be used to
  131. prevent a message from being sent to the sender.
  132. :param namespace: The Socket.IO namespace for the event. If this
  133. argument is omitted the event is emitted to the
  134. default namespace.
  135. :param callback: If given, this function will be called to acknowledge
  136. the the client has received the message. The arguments
  137. that will be passed to the function are those provided
  138. by the client. Callback functions can only be used
  139. when addressing an individual client.
  140. :param ignore_queue: Only used when a message queue is configured. If
  141. set to ``True``, the event is emitted to the
  142. clients directly, without going through the queue.
  143. This is more efficient, but only works when a
  144. single server process is used. It is recommended
  145. to always leave this parameter with its default
  146. value of ``False``.
  147. Note: this method is a coroutine.
  148. """
  149. await self.emit('message', data=data, to=to, room=room,
  150. skip_sid=skip_sid, namespace=namespace,
  151. callback=callback, **kwargs)
  152. async def call(self, event, data=None, to=None, sid=None, namespace=None,
  153. timeout=60, **kwargs):
  154. """Emit a custom event to a client and wait for the response.
  155. :param event: The event name. It can be any string. The event names
  156. ``'connect'``, ``'message'`` and ``'disconnect'`` are
  157. reserved and should not be used.
  158. :param data: The data to send to the client or clients. Data can be of
  159. type ``str``, ``bytes``, ``list`` or ``dict``. If a
  160. ``list`` or ``dict``, the data will be serialized as JSON.
  161. :param to: The session ID of the recipient client.
  162. :param sid: Alias for the ``to`` parameter.
  163. :param namespace: The Socket.IO namespace for the event. If this
  164. argument is omitted the event is emitted to the
  165. default namespace.
  166. :param timeout: The waiting timeout. If the timeout is reached before
  167. the client acknowledges the event, then a
  168. ``TimeoutError`` exception is raised.
  169. :param ignore_queue: Only used when a message queue is configured. If
  170. set to ``True``, the event is emitted to the
  171. client directly, without going through the queue.
  172. This is more efficient, but only works when a
  173. single server process is used. It is recommended
  174. to always leave this parameter with its default
  175. value of ``False``.
  176. """
  177. if not self.async_handlers:
  178. raise RuntimeError(
  179. 'Cannot use call() when async_handlers is False.')
  180. callback_event = self.eio.create_event()
  181. callback_args = []
  182. def event_callback(*args):
  183. callback_args.append(args)
  184. callback_event.set()
  185. await self.emit(event, data=data, room=to or sid, namespace=namespace,
  186. callback=event_callback, **kwargs)
  187. try:
  188. await asyncio.wait_for(callback_event.wait(), timeout)
  189. except asyncio.TimeoutError:
  190. six.raise_from(exceptions.TimeoutError(), None)
  191. return callback_args[0] if len(callback_args[0]) > 1 \
  192. else callback_args[0][0] if len(callback_args[0]) == 1 \
  193. else None
  194. async def close_room(self, room, namespace=None):
  195. """Close a room.
  196. This function removes all the clients from the given room.
  197. :param room: Room name.
  198. :param namespace: The Socket.IO namespace for the event. If this
  199. argument is omitted the default namespace is used.
  200. Note: this method is a coroutine.
  201. """
  202. namespace = namespace or '/'
  203. self.logger.info('room %s is closing [%s]', room, namespace)
  204. await self.manager.close_room(room, namespace)
  205. async def get_session(self, sid, namespace=None):
  206. """Return the user session for a client.
  207. :param sid: The session id of the client.
  208. :param namespace: The Socket.IO namespace. If this argument is omitted
  209. the default namespace is used.
  210. The return value is a dictionary. Modifications made to this
  211. dictionary are not guaranteed to be preserved. If you want to modify
  212. the user session, use the ``session`` context manager instead.
  213. """
  214. namespace = namespace or '/'
  215. eio_session = await self.eio.get_session(sid)
  216. return eio_session.setdefault(namespace, {})
  217. async def save_session(self, sid, session, namespace=None):
  218. """Store the user session for a client.
  219. :param sid: The session id of the client.
  220. :param session: The session dictionary.
  221. :param namespace: The Socket.IO namespace. If this argument is omitted
  222. the default namespace is used.
  223. """
  224. namespace = namespace or '/'
  225. eio_session = await self.eio.get_session(sid)
  226. eio_session[namespace] = session
  227. def session(self, sid, namespace=None):
  228. """Return the user session for a client with context manager syntax.
  229. :param sid: The session id of the client.
  230. This is a context manager that returns the user session dictionary for
  231. the client. Any changes that are made to this dictionary inside the
  232. context manager block are saved back to the session. Example usage::
  233. @eio.on('connect')
  234. def on_connect(sid, environ):
  235. username = authenticate_user(environ)
  236. if not username:
  237. return False
  238. with eio.session(sid) as session:
  239. session['username'] = username
  240. @eio.on('message')
  241. def on_message(sid, msg):
  242. async with eio.session(sid) as session:
  243. print('received message from ', session['username'])
  244. """
  245. class _session_context_manager(object):
  246. def __init__(self, server, sid, namespace):
  247. self.server = server
  248. self.sid = sid
  249. self.namespace = namespace
  250. self.session = None
  251. async def __aenter__(self):
  252. self.session = await self.server.get_session(
  253. sid, namespace=self.namespace)
  254. return self.session
  255. async def __aexit__(self, *args):
  256. await self.server.save_session(sid, self.session,
  257. namespace=self.namespace)
  258. return _session_context_manager(self, sid, namespace)
  259. async def disconnect(self, sid, namespace=None):
  260. """Disconnect a client.
  261. :param sid: Session ID of the client.
  262. :param namespace: The Socket.IO namespace to disconnect. If this
  263. argument is omitted the default namespace is used.
  264. Note: this method is a coroutine.
  265. """
  266. namespace = namespace or '/'
  267. if self.manager.is_connected(sid, namespace=namespace):
  268. self.logger.info('Disconnecting %s [%s]', sid, namespace)
  269. self.manager.pre_disconnect(sid, namespace=namespace)
  270. await self._send_packet(sid, packet.Packet(packet.DISCONNECT,
  271. namespace=namespace))
  272. await self._trigger_event('disconnect', namespace, sid)
  273. self.manager.disconnect(sid, namespace=namespace)
  274. if namespace == '/':
  275. await self.eio.disconnect(sid)
  276. async def handle_request(self, *args, **kwargs):
  277. """Handle an HTTP request from the client.
  278. This is the entry point of the Socket.IO application. This function
  279. returns the HTTP response body to deliver to the client.
  280. Note: this method is a coroutine.
  281. """
  282. return await self.eio.handle_request(*args, **kwargs)
  283. def start_background_task(self, target, *args, **kwargs):
  284. """Start a background task using the appropriate async model.
  285. This is a utility function that applications can use to start a
  286. background task using the method that is compatible with the
  287. selected async mode.
  288. :param target: the target function to execute. Must be a coroutine.
  289. :param args: arguments to pass to the function.
  290. :param kwargs: keyword arguments to pass to the function.
  291. The return value is a ``asyncio.Task`` object.
  292. Note: this method is a coroutine.
  293. """
  294. return self.eio.start_background_task(target, *args, **kwargs)
  295. async def sleep(self, seconds=0):
  296. """Sleep for the requested amount of time using the appropriate async
  297. model.
  298. This is a utility function that applications can use to put a task to
  299. sleep without having to worry about using the correct call for the
  300. selected async mode.
  301. Note: this method is a coroutine.
  302. """
  303. return await self.eio.sleep(seconds)
  304. async def _emit_internal(self, sid, event, data, namespace=None, id=None):
  305. """Send a message to a client."""
  306. # tuples are expanded to multiple arguments, everything else is sent
  307. # as a single argument
  308. if isinstance(data, tuple):
  309. data = list(data)
  310. else:
  311. data = [data]
  312. await self._send_packet(sid, packet.Packet(
  313. packet.EVENT, namespace=namespace, data=[event] + data, id=id,
  314. binary=None))
  315. async def _send_packet(self, sid, pkt):
  316. """Send a Socket.IO packet to a client."""
  317. encoded_packet = pkt.encode()
  318. if isinstance(encoded_packet, list):
  319. binary = False
  320. for ep in encoded_packet:
  321. await self.eio.send(sid, ep, binary=binary)
  322. binary = True
  323. else:
  324. await self.eio.send(sid, encoded_packet, binary=False)
  325. async def _handle_connect(self, sid, namespace):
  326. """Handle a client connection request."""
  327. namespace = namespace or '/'
  328. self.manager.connect(sid, namespace)
  329. if self.always_connect:
  330. await self._send_packet(sid, packet.Packet(packet.CONNECT,
  331. namespace=namespace))
  332. fail_reason = None
  333. try:
  334. success = await self._trigger_event('connect', namespace, sid,
  335. self.environ[sid])
  336. except exceptions.ConnectionRefusedError as exc:
  337. fail_reason = exc.error_args
  338. success = False
  339. if success is False:
  340. if self.always_connect:
  341. self.manager.pre_disconnect(sid, namespace)
  342. await self._send_packet(sid, packet.Packet(
  343. packet.DISCONNECT, data=fail_reason, namespace=namespace))
  344. self.manager.disconnect(sid, namespace)
  345. if not self.always_connect:
  346. await self._send_packet(sid, packet.Packet(
  347. packet.ERROR, data=fail_reason, namespace=namespace))
  348. if sid in self.environ: # pragma: no cover
  349. del self.environ[sid]
  350. return False
  351. elif not self.always_connect:
  352. await self._send_packet(sid, packet.Packet(packet.CONNECT,
  353. namespace=namespace))
  354. async def _handle_disconnect(self, sid, namespace):
  355. """Handle a client disconnect."""
  356. namespace = namespace or '/'
  357. if namespace == '/':
  358. namespace_list = list(self.manager.get_namespaces())
  359. else:
  360. namespace_list = [namespace]
  361. for n in namespace_list:
  362. if n != '/' and self.manager.is_connected(sid, n):
  363. await self._trigger_event('disconnect', n, sid)
  364. self.manager.disconnect(sid, n)
  365. if namespace == '/' and self.manager.is_connected(sid, namespace):
  366. await self._trigger_event('disconnect', '/', sid)
  367. self.manager.disconnect(sid, '/')
  368. async def _handle_event(self, sid, namespace, id, data):
  369. """Handle an incoming client event."""
  370. namespace = namespace or '/'
  371. self.logger.info('received event "%s" from %s [%s]', data[0], sid,
  372. namespace)
  373. if self.async_handlers:
  374. self.start_background_task(self._handle_event_internal, self, sid,
  375. data, namespace, id)
  376. else:
  377. await self._handle_event_internal(self, sid, data, namespace, id)
  378. async def _handle_event_internal(self, server, sid, data, namespace, id):
  379. r = await server._trigger_event(data[0], namespace, sid, *data[1:])
  380. if id is not None:
  381. # send ACK packet with the response returned by the handler
  382. # tuples are expanded as multiple arguments
  383. if r is None:
  384. data = []
  385. elif isinstance(r, tuple):
  386. data = list(r)
  387. else:
  388. data = [r]
  389. await server._send_packet(sid, packet.Packet(packet.ACK,
  390. namespace=namespace,
  391. id=id, data=data,
  392. binary=None))
  393. async def _handle_ack(self, sid, namespace, id, data):
  394. """Handle ACK packets from the client."""
  395. namespace = namespace or '/'
  396. self.logger.info('received ack from %s [%s]', sid, namespace)
  397. await self.manager.trigger_callback(sid, namespace, id, data)
  398. async def _trigger_event(self, event, namespace, *args):
  399. """Invoke an application event handler."""
  400. # first see if we have an explicit handler for the event
  401. if namespace in self.handlers and event in self.handlers[namespace]:
  402. if asyncio.iscoroutinefunction(self.handlers[namespace][event]) \
  403. is True:
  404. try:
  405. ret = await self.handlers[namespace][event](*args)
  406. except asyncio.CancelledError: # pragma: no cover
  407. ret = None
  408. else:
  409. ret = self.handlers[namespace][event](*args)
  410. return ret
  411. # or else, forward the event to a namepsace handler if one exists
  412. elif namespace in self.namespace_handlers:
  413. return await self.namespace_handlers[namespace].trigger_event(
  414. event, *args)
  415. async def _handle_eio_connect(self, sid, environ):
  416. """Handle the Engine.IO connection event."""
  417. if not self.manager_initialized:
  418. self.manager_initialized = True
  419. self.manager.initialize()
  420. self.environ[sid] = environ
  421. return await self._handle_connect(sid, '/')
  422. async def _handle_eio_message(self, sid, data):
  423. """Dispatch Engine.IO messages."""
  424. if sid in self._binary_packet:
  425. pkt = self._binary_packet[sid]
  426. if pkt.add_attachment(data):
  427. del self._binary_packet[sid]
  428. if pkt.packet_type == packet.BINARY_EVENT:
  429. await self._handle_event(sid, pkt.namespace, pkt.id,
  430. pkt.data)
  431. else:
  432. await self._handle_ack(sid, pkt.namespace, pkt.id,
  433. pkt.data)
  434. else:
  435. pkt = packet.Packet(encoded_packet=data)
  436. if pkt.packet_type == packet.CONNECT:
  437. await self._handle_connect(sid, pkt.namespace)
  438. elif pkt.packet_type == packet.DISCONNECT:
  439. await self._handle_disconnect(sid, pkt.namespace)
  440. elif pkt.packet_type == packet.EVENT:
  441. await self._handle_event(sid, pkt.namespace, pkt.id, pkt.data)
  442. elif pkt.packet_type == packet.ACK:
  443. await self._handle_ack(sid, pkt.namespace, pkt.id, pkt.data)
  444. elif pkt.packet_type == packet.BINARY_EVENT or \
  445. pkt.packet_type == packet.BINARY_ACK:
  446. self._binary_packet[sid] = pkt
  447. elif pkt.packet_type == packet.ERROR:
  448. raise ValueError('Unexpected ERROR packet.')
  449. else:
  450. raise ValueError('Unknown packet type.')
  451. async def _handle_eio_disconnect(self, sid):
  452. """Handle Engine.IO disconnect event."""
  453. await self._handle_disconnect(sid, '/')
  454. if sid in self.environ:
  455. del self.environ[sid]
  456. def _engineio_server_class(self):
  457. return engineio.AsyncServer