client.py 15 KB

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