wordplus-realtime 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ """WordPlus Cloud's realtime SDK for Python, outside WordPress: your server's part of rooms, presence, history, online
2
+ status, calls and group calls, sealed end to end. The browser part is the npm package @wordplus/realtime.
3
+
4
+ from wordplus_realtime import Realtime
5
+
6
+ realtime = Realtime.from_environment(profile=lambda user: {"name": name_of(user)})
7
+ realtime.room("order:{id}", lambda user, p: owns_order(user, p["id"]), history=20)
8
+ realtime.to("order:42").emit("updated", {"status": "paid"})
9
+
10
+ Django: ``wordplus_realtime.django``. FastAPI and Starlette: ``wordplus_realtime.fastapi``.
11
+ """
12
+
13
+ from .keys import GenerationStore, Keys, day_of, label_of, valid_label
14
+ from .patterns import Patterns, valid_pattern, valid_room
15
+ from .realtime import API_SERVER, SERVER, VERSION, CallQueries, Emitter, OnlineQueries, Realtime, RealtimeError, RoomQueries, StreamQueries, UserQueries, WebhookQueries
16
+
17
+ __all__ = [
18
+ "Realtime",
19
+ "RealtimeError",
20
+ "Emitter",
21
+ "RoomQueries",
22
+ "OnlineQueries",
23
+ "UserQueries",
24
+ "WebhookQueries",
25
+ "CallQueries",
26
+ "StreamQueries",
27
+ "Keys",
28
+ "GenerationStore",
29
+ "Patterns",
30
+ "valid_room",
31
+ "valid_pattern",
32
+ "valid_label",
33
+ "label_of",
34
+ "day_of",
35
+ "SERVER",
36
+ "API_SERVER",
37
+ "VERSION",
38
+ ]
39
+
40
+ __version__ = VERSION
@@ -0,0 +1,185 @@
1
+ """WordPlus Cloud's realtime SDK in Django, as an app: the browser's routes for the request's user, the realtime
2
+ server's webhook and the browser files, ``{% wordplus_realtime %}`` for a page's head, and a user's profile from
3
+ Django's user model.
4
+
5
+ # settings.py
6
+ INSTALLED_APPS = [..., "wordplus_realtime.django"]
7
+ WORDPLUS_REALTIME = {"base": "/api/realtime"} # optional: Realtime's options, the keys from the environment
8
+
9
+ # store/realtime.py, imported by your app's ready() or its urls
10
+ from wordplus_realtime.django import realtime
11
+ realtime.room("order:{id}", lambda user, p: Order.objects.filter(pk=p["id"], user_id=user).exists(), history=20)
12
+
13
+ # urls.py: POST /api/realtime/auth, /calls, /keys and /webhook, and GET /api/realtime/files/…
14
+ path("api/realtime/", include("wordplus_realtime.django.routes"))
15
+
16
+ {% load wordplus_realtime %}
17
+ <head>{% wordplus_realtime %}</head> {# the settings, and the import map of the client #}
18
+
19
+ The routes take the session's user and Django's CSRF check: the page's settings carry the token as X-CSRFToken. The
20
+ webhook, which the realtime server signs itself, takes neither. An app with a Realtime of its own includes
21
+ ``urls(its_realtime, user=…)`` instead, and the template tag takes that one.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import Any, Callable, Dict, List, Optional
27
+
28
+ from django.contrib.auth import get_user_model
29
+ from django.http import HttpRequest, HttpResponse, JsonResponse
30
+ from django.middleware.csrf import get_token
31
+ from django.urls import URLPattern, path
32
+ from django.views.decorators.csrf import csrf_exempt
33
+
34
+ from ..keys import UserId
35
+ from ..realtime import ROUTES, Realtime, _path_of
36
+
37
+ # The Realtime and the user the routes were made with, which {% wordplus_realtime %} takes: urls() sets them, and the
38
+ # one made from settings is it until then.
39
+ _current: Optional[Dict[str, Any]] = None
40
+ _from_settings: Optional[Realtime] = None
41
+
42
+
43
+ def get_realtime() -> Realtime:
44
+ """The app's Realtime: the one ``urls()`` was given, else the one made from ``settings.WORDPLUS_REALTIME`` (Realtime's
45
+ options by name, ``site``, ``secret`` and ``local_key`` from WORDPLUS_SITE, WORDPLUS_SECRET and WORDPLUS_LOCAL_KEY
46
+ when it leaves them out, ``profile``, ``has_keys`` and ``hidden`` functions or their dotted paths), with the profile
47
+ from Django's user model unless it names one."""
48
+ global _from_settings
49
+ if _current is not None:
50
+ return _current["realtime"]
51
+ if _from_settings is None:
52
+ from django.conf import settings
53
+ from django.utils.module_loading import import_string
54
+
55
+ options = dict(getattr(settings, "WORDPLUS_REALTIME", {}) or {})
56
+ options.pop("user", None) # the routes', settings_user()
57
+ for name in ("profile", "has_keys", "hidden"):
58
+ if isinstance(options.get(name), str):
59
+ options[name] = import_string(options[name])
60
+ options.setdefault("profile", user_profile)
61
+ # Its keys checked when first used, so manage.py runs before they are set (migrate, collectstatic in a build).
62
+ options.setdefault("check_keys", False)
63
+ site, secret, local_key = options.pop("site", None), options.pop("secret", None), options.pop("local_key", None)
64
+ _from_settings = Realtime(site, secret, local_key or "", **options) if site and secret else Realtime.from_environment(**options)
65
+ return _from_settings
66
+
67
+
68
+ def __getattr__(name: str) -> Any:
69
+ # `from wordplus_realtime.django import realtime`: made from settings when first asked, after Django read them.
70
+ if name == "realtime":
71
+ return get_realtime()
72
+ raise AttributeError(name)
73
+
74
+
75
+ def session_user(request: HttpRequest) -> Optional[UserId]:
76
+ """The signed-in user's id, or None."""
77
+ user = getattr(request, "user", None)
78
+ return user.pk if user is not None and user.is_authenticated else None
79
+
80
+
81
+ def user_profile(user_id: UserId) -> Optional[Dict[str, Any]]:
82
+ """A user's profile from Django's user model: their full name, or their username."""
83
+ found = get_user_model().objects.filter(pk=user_id).first()
84
+ if found is None:
85
+ return None
86
+ name = (found.get_full_name() if hasattr(found, "get_full_name") else "") or found.get_username()
87
+ return {"name": name} if name else None
88
+
89
+
90
+ def _json(status: int, body: Any) -> HttpResponse:
91
+ if status == 204:
92
+ response = HttpResponse(status=204)
93
+ else:
94
+ response = JsonResponse(body, status=status, safe=False, json_dumps_params={"separators": (",", ":"), "ensure_ascii": False})
95
+ response["Cache-Control"] = "no-store"
96
+ return response
97
+
98
+
99
+ def view(realtime: Realtime, user: Callable[[HttpRequest], Optional[UserId]] = session_user) -> Callable[..., HttpResponse]:
100
+ """The routes as one view, the action from the URL: ``path("<str:action>", view(realtime))``."""
101
+
102
+ def realtime_view(request: HttpRequest, action: str) -> HttpResponse:
103
+ return _json(*realtime.answer_request(request.method or "GET", request.headers.get("Content-Type", ""), action, request.body, user(request)))
104
+
105
+ return realtime_view
106
+
107
+
108
+ def webhook_view(realtime: Realtime) -> Callable[..., HttpResponse]:
109
+ """The realtime server's webhook: checked as it was sent, its events handed to the handlers ``realtime.on()`` set."""
110
+
111
+ @csrf_exempt
112
+ def realtime_webhook(request: HttpRequest) -> HttpResponse:
113
+ if request.method != "POST":
114
+ return _json(405, {"code": "method_not_allowed"})
115
+ return _json(*realtime.webhook(request.body, request.headers, request.get_full_path()))
116
+
117
+ return realtime_webhook
118
+
119
+
120
+ def file_view(realtime: Realtime) -> Callable[..., HttpResponse]:
121
+ """GET files/<version>/<name>: a browser file the package carries (``realtime.file_named()``), no session asked."""
122
+
123
+ def realtime_file(request: HttpRequest, name: str, version: Optional[str] = None) -> HttpResponse:
124
+ status, headers, body = realtime.file_named(request.method or "GET", version, name, request.headers.get("If-None-Match"))
125
+ response = HttpResponse(body or b"", status=status)
126
+ for header, value in headers.items():
127
+ response[header] = value
128
+ return response
129
+
130
+ return realtime_file
131
+
132
+
133
+ def _files(realtime: Realtime, at: str) -> List[URLPattern]:
134
+ if not realtime.serves_files:
135
+ return []
136
+ serve = file_view(realtime)
137
+ return [
138
+ path(at + "files/<str:name>", serve, name="wordplus-realtime-file"),
139
+ path(at + "files/<str:version>/<str:name>", serve, name="wordplus-realtime-files"),
140
+ ]
141
+
142
+
143
+ def urls(realtime: Realtime, user: Callable[[HttpRequest], Optional[UserId]] = session_user) -> List[URLPattern]:
144
+ """The routes' URLs, to include under the routes' base (``/api/realtime/`` by default): POST auth, calls, keys and
145
+ webhook, and GET files/<version>/<name>, the browser files. With routes at addresses of their own (the ``routes``
146
+ option), each at its whole address: include them at the root, ``path("", include(…))``. The first Realtime given here
147
+ is the one ``{% wordplus_realtime %}`` takes, with its user."""
148
+ global _current
149
+ if _current is None:
150
+ _current = {"realtime": realtime, "user": user}
151
+ if realtime.own_routes:
152
+ answer = view(realtime, user)
153
+ return _files(realtime, realtime.base.lstrip("/") + "/") + [
154
+ path(_path_of(realtime.address(name)).lstrip("/"), webhook_view(realtime), name="wordplus-realtime-webhook")
155
+ if name == "webhook"
156
+ else path(_path_of(realtime.address(name)).lstrip("/"), answer, {"action": name}, name="wordplus-realtime-" + name)
157
+ for name in ROUTES
158
+ ]
159
+ return _files(realtime, "") + [
160
+ path("webhook", webhook_view(realtime), name="wordplus-realtime-webhook"),
161
+ path("<str:action>", view(realtime, user), name="wordplus-realtime"),
162
+ ]
163
+
164
+
165
+ def config_for(realtime: Realtime, request: HttpRequest, user: Callable[[HttpRequest], Optional[UserId]] = session_user) -> Dict[str, Any]:
166
+ """The browser's settings for the request's user, with Django's CSRF token for the routes."""
167
+ return realtime.config(user(request), headers={"X-CSRFToken": get_token(request)})
168
+
169
+
170
+ def settings_user() -> Callable[[HttpRequest], Optional[UserId]]:
171
+ """Who a request's user is: ``WORDPLUS_REALTIME["user"]``, a function or its dotted path, else the session's user."""
172
+ from django.conf import settings
173
+ from django.utils.module_loading import import_string
174
+
175
+ named = (getattr(settings, "WORDPLUS_REALTIME", {}) or {}).get("user")
176
+ return import_string(named) if isinstance(named, str) else named or session_user
177
+
178
+
179
+ def head_for(request: HttpRequest, importmap: bool = True, user: Optional[Callable[[HttpRequest], Optional[UserId]]] = None) -> str:
180
+ """What ``{% wordplus_realtime %}`` writes: the settings for the request's user, as the routes find them unless
181
+ ``user`` says, with Django's CSRF token, and the import map of the client, from the Realtime the routes were made with."""
182
+ realtime = get_realtime()
183
+ if user is None:
184
+ user = _current["user"] if _current is not None else settings_user()
185
+ return realtime.head(user(request), headers={"X-CSRFToken": get_token(request)}, importmap=importmap)
@@ -0,0 +1,9 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class WordPlusRealtimeConfig(AppConfig):
5
+ """``"wordplus_realtime.django"`` in INSTALLED_APPS: its template tag, ``{% load wordplus_realtime %}``."""
6
+
7
+ name = "wordplus_realtime.django"
8
+ label = "wordplus_realtime"
9
+ verbose_name = "WordPlus Cloud realtime"
@@ -0,0 +1,6 @@
1
+ """``path("api/realtime/", include("wordplus_realtime.django.routes"))``: the routes of the Realtime made from settings
2
+ (``WORDPLUS_REALTIME``), for the user it names, else the session's."""
3
+
4
+ from . import get_realtime, settings_user, urls
5
+
6
+ urlpatterns = urls(get_realtime(), settings_user())
File without changes
@@ -0,0 +1,24 @@
1
+ """``{% load wordplus_realtime %}`` then ``{% wordplus_realtime %}`` in a page's head: the settings for the request's
2
+ user, with Django's CSRF token, and the import map of the client the routes serve, so the page's own module imports
3
+ ``@wordplus/realtime`` with no bundler. ``{% wordplus_realtime importmap=False %}`` for a page whose bundler resolves
4
+ it, and ``{% wordplus_realtime user=… %}`` for a page whose view knows its user another way than the routes do. It
5
+ needs the request in the template's context (django.template.context_processors.request)."""
6
+
7
+ from django import template
8
+ from django.utils.safestring import mark_safe
9
+
10
+ from .. import head_for
11
+
12
+ register = template.Library()
13
+
14
+ _ROUTES_USER = object()
15
+
16
+
17
+ @register.simple_tag(takes_context=True)
18
+ def wordplus_realtime(context, importmap=True, user=_ROUTES_USER):
19
+ request = context.get("request")
20
+ if request is None:
21
+ raise template.TemplateSyntaxError("{% wordplus_realtime %} needs the request: add django.template.context_processors.request to the template context processors")
22
+ if user is _ROUTES_USER:
23
+ return mark_safe(head_for(request, importmap=importmap))
24
+ return mark_safe(head_for(request, importmap=importmap, user=lambda _: user))
@@ -0,0 +1,84 @@
1
+ """WordPlus Cloud's realtime SDK in FastAPI and Starlette: the browser's routes and the realtime server's webhook as a
2
+ router, for the user the app finds.
3
+
4
+ realtime = Realtime.from_environment(profile=lambda user: {"name": name_of(user)})
5
+
6
+ async def current_user(request: Request) -> Optional[int]:
7
+ return (await session_of(request)).user_id
8
+
9
+ app.include_router(wordplus_realtime.fastapi.router(realtime, current_user), prefix="/api/realtime")
10
+
11
+ await realtime.to("order:42").aemit("updated", {"status": "paid"})
12
+
13
+ The rules and the webhook's handlers run on a worker thread, so they may query a database the plain way.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import inspect
19
+ from typing import Any, Awaitable, Callable, Optional
20
+
21
+ from fastapi import APIRouter, Request
22
+ from fastapi.responses import JSONResponse, Response
23
+ from starlette.concurrency import run_in_threadpool
24
+
25
+ from .keys import UserId
26
+ from .realtime import ROUTES, Realtime, _path_of
27
+
28
+
29
+ def router(realtime: Realtime, user: Callable[[Request], Any]) -> APIRouter:
30
+ """POST /auth, /calls, /keys and /webhook under the prefix it is included with. ``user(request)`` gives the request's
31
+ user's id, or None; it may be async. The webhook asks no user: the realtime server signs it. With routes at addresses
32
+ of their own (the ``routes`` option), each at its whole address: include it with no prefix."""
33
+ routes = APIRouter()
34
+
35
+ async def answer(action: str, request: Request) -> Response:
36
+ body = await request.body()
37
+ if action == "webhook":
38
+ path = request.url.path + ("?" + request.url.query if request.url.query else "")
39
+ status, answer = await run_in_threadpool(realtime.webhook, body, request.headers, path)
40
+ else:
41
+ who = user(request)
42
+ if inspect.isawaitable(who):
43
+ who = await who
44
+ status, answer = await run_in_threadpool(realtime.answer_request, request.method, request.headers.get("content-type", ""), action, body, who)
45
+ if status == 204:
46
+ return Response(status_code=204, headers={"Cache-Control": "no-store"})
47
+ return JSONResponse(answer, status_code=status, headers={"Cache-Control": "no-store"})
48
+
49
+ def at(action: str) -> Callable[[Request], Awaitable[Response]]:
50
+ # The route named here alone: a parameter of its own would be read from the query.
51
+ async def at_address(request: Request) -> Response:
52
+ return await answer(action, request)
53
+
54
+ return at_address
55
+
56
+ # The browser files the package carries: GET files/{version}/{name}, the same for every user.
57
+ async def file(request: Request) -> Response:
58
+ params = request.path_params
59
+ status, headers, body = realtime.file_named(request.method, params.get("version"), params["name"], request.headers.get("if-none-match"))
60
+ return Response(body or b"", status_code=status, headers=headers)
61
+
62
+ def files(at: str) -> None:
63
+ if realtime.serves_files:
64
+ routes.add_api_route(at + "/files/{name}", file, methods=["GET", "HEAD"], include_in_schema=False)
65
+ routes.add_api_route(at + "/files/{version}/{name}", file, methods=["GET", "HEAD"], include_in_schema=False)
66
+
67
+ if realtime.own_routes:
68
+ files(realtime.base)
69
+ for name in ROUTES:
70
+ routes.add_api_route(_path_of(realtime.address(name)), at(name), methods=["POST"], include_in_schema=False)
71
+ return routes
72
+
73
+ files("")
74
+
75
+ @routes.post("/{action}", include_in_schema=False)
76
+ async def wordplus_realtime(action: str, request: Request) -> Response:
77
+ return await answer(action, request)
78
+
79
+ return routes
80
+
81
+
82
+ def config_for(realtime: Realtime, user: Optional[UserId]) -> Any:
83
+ """The browser's settings for a user, for a page or a route of the app's own that answers them."""
84
+ return realtime.config(user)