client.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from __future__ import annotations
  2. import asyncio
  3. import inspect
  4. import time
  5. import uuid
  6. from contextlib import contextmanager
  7. from pathlib import Path
  8. from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Iterable, Iterator, List, Optional, Union
  9. from fastapi import Request
  10. from fastapi.responses import Response
  11. from fastapi.templating import Jinja2Templates
  12. from nicegui import json
  13. from . import background_tasks, binding, core, helpers, outbox
  14. from .awaitable_response import AwaitableResponse
  15. from .dependencies import generate_resources
  16. from .element import Element
  17. from .favicon import get_favicon_url
  18. from .logging import log
  19. from .version import __version__
  20. if TYPE_CHECKING:
  21. from .page import page
  22. templates = Jinja2Templates(Path(__file__).parent / 'templates')
  23. class Client:
  24. page_routes: Dict[Callable[..., Any], str] = {}
  25. """Maps page builders to their routes."""
  26. instances: Dict[str, Client] = {}
  27. """Maps client IDs to clients."""
  28. auto_index_client: Client
  29. """The client that is used to render the auto-index page."""
  30. head_html = ''
  31. """HTML to be inserted in the <head> of the page template."""
  32. body_html = ''
  33. """HTML to be inserted in the <body> of the page template."""
  34. def __init__(self, page: page, *, shared: bool = False) -> None:
  35. self.id = str(uuid.uuid4())
  36. self.created = time.time()
  37. self.instances[self.id] = self
  38. self.elements: Dict[int, Element] = {}
  39. self.next_element_id: int = 0
  40. self.is_waiting_for_connection: bool = False
  41. self.is_waiting_for_disconnect: bool = False
  42. self.environ: Optional[Dict[str, Any]] = None
  43. self.shared = shared
  44. self.on_air = False
  45. self._disconnect_task: Optional[asyncio.Task] = None
  46. with Element('q-layout', _client=self).props('view="hhh lpr fff"').classes('nicegui-layout') as self.layout:
  47. with Element('q-page-container') as self.page_container:
  48. with Element('q-page'):
  49. self.content = Element('div').classes('nicegui-content')
  50. self.waiting_javascript_commands: Dict[str, Any] = {}
  51. self.page = page
  52. self.connect_handlers: List[Union[Callable[..., Any], Awaitable]] = []
  53. self.disconnect_handlers: List[Union[Callable[..., Any], Awaitable]] = []
  54. self._temporary_socket_id: Optional[str] = None
  55. @property
  56. def is_auto_index_client(self) -> bool:
  57. """Return True if this client is the auto-index client."""
  58. return self is self.auto_index_client
  59. @property
  60. def ip(self) -> Optional[str]:
  61. """Return the IP address of the client, or None if the client is not connected."""
  62. return self.environ['asgi.scope']['client'][0] if self.environ else None # pylint: disable=unsubscriptable-object
  63. @property
  64. def has_socket_connection(self) -> bool:
  65. """Return True if the client is connected, False otherwise."""
  66. return self.environ is not None
  67. def __enter__(self):
  68. self.content.__enter__()
  69. return self
  70. def __exit__(self, *_):
  71. self.content.__exit__()
  72. def build_response(self, request: Request, status_code: int = 200) -> Response:
  73. """Build a FastAPI response for the client."""
  74. prefix = request.headers.get('X-Forwarded-Prefix', request.scope.get('root_path', ''))
  75. elements = json.dumps({
  76. id: element._to_dict() for id, element in self.elements.items() # pylint: disable=protected-access
  77. })
  78. socket_io_js_query_params = {**core.app.config.socket_io_js_query_params, 'client_id': self.id}
  79. vue_html, vue_styles, vue_scripts, imports, js_imports = generate_resources(prefix, self.elements.values())
  80. return templates.TemplateResponse('index.html', {
  81. 'request': request,
  82. 'version': __version__,
  83. 'elements': elements.replace('&', '&amp;')
  84. .replace('<', '&lt;')
  85. .replace('>', '&gt;')
  86. .replace('`', '&#96;')
  87. .replace('$', '&#36;'),
  88. 'head_html': self.head_html,
  89. 'body_html': '<style>' + '\n'.join(vue_styles) + '</style>\n' + self.body_html + '\n' + '\n'.join(vue_html),
  90. 'vue_scripts': '\n'.join(vue_scripts),
  91. 'imports': json.dumps(imports),
  92. 'js_imports': '\n'.join(js_imports),
  93. 'quasar_config': json.dumps(core.app.config.quasar_config),
  94. 'title': self.page.resolve_title(),
  95. 'viewport': self.page.resolve_viewport(),
  96. 'favicon_url': get_favicon_url(self.page, prefix),
  97. 'dark': str(self.page.resolve_dark()),
  98. 'language': self.page.resolve_language(),
  99. 'prefix': prefix,
  100. 'tailwind': core.app.config.tailwind,
  101. 'prod_js': core.app.config.prod_js,
  102. 'socket_io_js_query_params': socket_io_js_query_params,
  103. 'socket_io_js_extra_headers': core.app.config.socket_io_js_extra_headers,
  104. 'socket_io_js_transports': core.app.config.socket_io_js_transports,
  105. }, status_code, {'Cache-Control': 'no-store', 'X-NiceGUI-Content': 'page'})
  106. async def connected(self, timeout: float = 3.0, check_interval: float = 0.1) -> None:
  107. """Block execution until the client is connected."""
  108. self.is_waiting_for_connection = True
  109. deadline = time.time() + timeout
  110. while not self.has_socket_connection:
  111. if time.time() > deadline:
  112. raise TimeoutError(f'No connection after {timeout} seconds')
  113. await asyncio.sleep(check_interval)
  114. self.is_waiting_for_connection = False
  115. async def disconnected(self, check_interval: float = 0.1) -> None:
  116. """Block execution until the client disconnects."""
  117. if not self.has_socket_connection:
  118. await self.connected()
  119. self.is_waiting_for_disconnect = True
  120. while self.id in self.instances:
  121. await asyncio.sleep(check_interval)
  122. self.is_waiting_for_disconnect = False
  123. def run_javascript(self, code: str, *,
  124. respond: Optional[bool] = None, # DEPRECATED
  125. timeout: float = 1.0, check_interval: float = 0.01) -> AwaitableResponse:
  126. """Execute JavaScript on the client.
  127. The client connection must be established before this method is called.
  128. You can do this by `await client.connected()` or register a callback with `client.on_connect(...)`.
  129. If the function is awaited, the result of the JavaScript code is returned.
  130. Otherwise, the JavaScript code is executed without waiting for a response.
  131. :param code: JavaScript code to run
  132. :param timeout: timeout in seconds (default: `1.0`)
  133. :param check_interval: interval in seconds to check for a response (default: `0.01`)
  134. :return: AwaitableResponse that can be awaited to get the result of the JavaScript code
  135. """
  136. if respond is True:
  137. log.warning('The "respond" argument of run_javascript() has been removed. '
  138. 'Now the method always returns an AwaitableResponse that can be awaited. '
  139. 'Please remove the "respond=True" argument.')
  140. if respond is False:
  141. raise ValueError('The "respond" argument of run_javascript() has been removed. '
  142. 'Now the method always returns an AwaitableResponse that can be awaited. '
  143. 'Please remove the "respond=False" argument and call the method without awaiting.')
  144. request_id = str(uuid.uuid4())
  145. target_id = self._temporary_socket_id or self.id
  146. def send_and_forget():
  147. outbox.enqueue_message('run_javascript', {'code': code}, target_id)
  148. async def send_and_wait():
  149. outbox.enqueue_message('run_javascript', {'code': code, 'request_id': request_id}, target_id)
  150. deadline = time.time() + timeout
  151. while request_id not in self.waiting_javascript_commands:
  152. if time.time() > deadline:
  153. raise TimeoutError('JavaScript did not respond in time')
  154. await asyncio.sleep(check_interval)
  155. return self.waiting_javascript_commands.pop(request_id)
  156. return AwaitableResponse(send_and_forget, send_and_wait)
  157. def open(self, target: Union[Callable[..., Any], str], new_tab: bool = False) -> None:
  158. """Open a new page in the client."""
  159. path = target if isinstance(target, str) else self.page_routes[target]
  160. outbox.enqueue_message('open', {'path': path, 'new_tab': new_tab}, self.id)
  161. def download(self, src: Union[str, bytes], filename: Optional[str] = None) -> None:
  162. """Download a file from a given URL or raw bytes."""
  163. outbox.enqueue_message('download', {'src': src, 'filename': filename}, self.id)
  164. def on_connect(self, handler: Union[Callable[..., Any], Awaitable]) -> None:
  165. """Register a callback to be called when the client connects."""
  166. self.connect_handlers.append(handler)
  167. def on_disconnect(self, handler: Union[Callable[..., Any], Awaitable]) -> None:
  168. """Register a callback to be called when the client disconnects."""
  169. self.disconnect_handlers.append(handler)
  170. def handle_handshake(self) -> None:
  171. """Cancel pending disconnect task and invoke connect handlers."""
  172. if self._disconnect_task:
  173. self._disconnect_task.cancel()
  174. self._disconnect_task = None
  175. for t in self.connect_handlers:
  176. self.safe_invoke(t)
  177. for t in core.app._connect_handlers: # pylint: disable=protected-access
  178. self.safe_invoke(t)
  179. def handle_disconnect(self) -> None:
  180. """Wait for the browser to reconnect; invoke disconnect handlers if it doesn't."""
  181. async def handle_disconnect() -> None:
  182. if self.page.reconnect_timeout is not None:
  183. delay = self.page.reconnect_timeout
  184. else:
  185. delay = core.app.config.reconnect_timeout # pylint: disable=protected-access
  186. await asyncio.sleep(delay)
  187. for t in self.disconnect_handlers:
  188. self.safe_invoke(t)
  189. for t in core.app._disconnect_handlers: # pylint: disable=protected-access
  190. self.safe_invoke(t)
  191. if not self.shared:
  192. self.delete()
  193. self._disconnect_task = background_tasks.create(handle_disconnect())
  194. def handle_event(self, msg: Dict) -> None:
  195. """Forward an event to the corresponding element."""
  196. with self:
  197. sender = self.elements.get(msg['id'])
  198. if sender:
  199. msg['args'] = [None if arg is None else json.loads(arg) for arg in msg.get('args', [])]
  200. if len(msg['args']) == 1:
  201. msg['args'] = msg['args'][0]
  202. sender._handle_event(msg) # pylint: disable=protected-access
  203. def handle_javascript_response(self, msg: Dict) -> None:
  204. """Store the result of a JavaScript command."""
  205. self.waiting_javascript_commands[msg['request_id']] = msg['result']
  206. def safe_invoke(self, func: Union[Callable[..., Any], Awaitable]) -> None:
  207. """Invoke the potentially async function in the client context and catch any exceptions."""
  208. try:
  209. if isinstance(func, Awaitable):
  210. async def func_with_client():
  211. with self:
  212. await func
  213. background_tasks.create(func_with_client())
  214. else:
  215. with self:
  216. result = func(self) if len(inspect.signature(func).parameters) == 1 else func()
  217. if helpers.is_coroutine_function(func):
  218. async def result_with_client():
  219. with self:
  220. await result
  221. background_tasks.create(result_with_client())
  222. except Exception as e:
  223. core.app.handle_exception(e)
  224. def remove_elements(self, elements: Iterable[Element]) -> None:
  225. """Remove the given elements from the client."""
  226. binding.remove(elements, Element)
  227. element_ids = [element.id for element in elements]
  228. for element_id in element_ids:
  229. del self.elements[element_id]
  230. for element in elements:
  231. element._handle_delete() # pylint: disable=protected-access
  232. element._deleted = True # pylint: disable=protected-access
  233. outbox.enqueue_delete(element)
  234. def remove_all_elements(self) -> None:
  235. """Remove all elements from the client."""
  236. self.remove_elements(self.elements.values())
  237. def delete(self) -> None:
  238. """Delete a client and all its elements.
  239. If the global clients dictionary does not contain the client, its elements are still removed and a KeyError is raised.
  240. Normally this should never happen, but has been observed (see #1826).
  241. """
  242. self.remove_all_elements()
  243. del Client.instances[self.id]
  244. @contextmanager
  245. def individual_target(self, socket_id: str) -> Iterator[None]:
  246. """Use individual socket ID while in this context.
  247. This context is useful for limiting messages from the shared auto-index page to a single client.
  248. """
  249. self._temporary_socket_id = socket_id
  250. yield
  251. self._temporary_socket_id = None
  252. @classmethod
  253. async def prune_instances(cls) -> None:
  254. """Prune stale clients in an endless loop."""
  255. while True:
  256. try:
  257. stale_clients = [
  258. client
  259. for client in cls.instances.values()
  260. if not client.shared and not client.has_socket_connection and client.created < time.time() - 60.0
  261. ]
  262. for client in stale_clients:
  263. client.delete()
  264. except Exception:
  265. # NOTE: make sure the loop doesn't crash
  266. log.exception('Error while pruning clients')
  267. await asyncio.sleep(10)