client.py 15 KB

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