hoja-cli 0.21.4__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.
Files changed (107) hide show
  1. VERSION +1 -0
  2. google_workspace/__init__.py +19 -0
  3. google_workspace/client.py +253 -0
  4. google_workspace/config.py +39 -0
  5. google_workspace/errors.py +19 -0
  6. google_workspace/mcp_server.py +100 -0
  7. google_workspace/oauth.py +131 -0
  8. google_workspace/principal.py +83 -0
  9. google_workspace/py.typed +0 -0
  10. google_workspace/tools.py +64 -0
  11. google_workspace/writes.py +44 -0
  12. hoja/__init__.py +29 -0
  13. hoja/__main__.py +6 -0
  14. hoja/auth.py +42 -0
  15. hoja/cli.py +161 -0
  16. hoja/cli_state.py +55 -0
  17. hoja/client.py +268 -0
  18. hoja/commands/__init__.py +4 -0
  19. hoja/commands/auth_cmd.py +271 -0
  20. hoja/commands/comment.py +149 -0
  21. hoja/commands/cycle.py +75 -0
  22. hoja/commands/init.py +108 -0
  23. hoja/commands/issue.py +398 -0
  24. hoja/commands/label.py +163 -0
  25. hoja/commands/memory.py +240 -0
  26. hoja/commands/project.py +56 -0
  27. hoja/commands/raw.py +50 -0
  28. hoja/commands/team.py +102 -0
  29. hoja/commands/update.py +162 -0
  30. hoja/config.py +362 -0
  31. hoja/errors.py +107 -0
  32. hoja/filters.py +150 -0
  33. hoja/graphql/__init__.py +5 -0
  34. hoja/graphql/fragments.py +138 -0
  35. hoja/graphql/mutations.py +160 -0
  36. hoja/graphql/queries.py +245 -0
  37. hoja/mcp/__init__.py +27 -0
  38. hoja/mcp/content.py +151 -0
  39. hoja/mcp/prompts.py +298 -0
  40. hoja/mcp/resources.py +213 -0
  41. hoja/mcp/server.py +189 -0
  42. hoja/memory_board.py +370 -0
  43. hoja/models/__init__.py +37 -0
  44. hoja/models/base.py +64 -0
  45. hoja/models/cycle.py +32 -0
  46. hoja/models/enums.py +62 -0
  47. hoja/models/issue.py +99 -0
  48. hoja/models/label.py +17 -0
  49. hoja/models/project.py +60 -0
  50. hoja/models/team.py +31 -0
  51. hoja/models/user.py +32 -0
  52. hoja/models/workflow.py +65 -0
  53. hoja/output.py +410 -0
  54. hoja/skill_content/commands.md +222 -0
  55. hoja/skill_content/examples.md +193 -0
  56. hoja/skill_content/filters.md +101 -0
  57. hoja/skill_content/output-formats.md +92 -0
  58. hoja/skill_content/overview.md +123 -0
  59. hoja/skill_content/workflows.md +174 -0
  60. hoja_cli-0.21.4.dist-info/METADATA +279 -0
  61. hoja_cli-0.21.4.dist-info/RECORD +107 -0
  62. hoja_cli-0.21.4.dist-info/WHEEL +4 -0
  63. hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
  64. hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
  65. hoja_server/README.md +135 -0
  66. hoja_server/__init__.py +11 -0
  67. hoja_server/abac.py +116 -0
  68. hoja_server/agent_chat.py +280 -0
  69. hoja_server/agent_conversations.py +91 -0
  70. hoja_server/agent_durable.py +332 -0
  71. hoja_server/agent_prompt.py +117 -0
  72. hoja_server/agent_threads.py +96 -0
  73. hoja_server/agent_uploads.py +60 -0
  74. hoja_server/app.py +2189 -0
  75. hoja_server/cadence.py +231 -0
  76. hoja_server/cli.py +191 -0
  77. hoja_server/cloudflare_realtime.py +110 -0
  78. hoja_server/comment_policy.py +70 -0
  79. hoja_server/connector_actions.py +119 -0
  80. hoja_server/connectors_api.py +375 -0
  81. hoja_server/db.py +1816 -0
  82. hoja_server/denials.py +18 -0
  83. hoja_server/deployment.py +28 -0
  84. hoja_server/email_adapter.py +94 -0
  85. hoja_server/google_login.py +217 -0
  86. hoja_server/google_oidc.py +342 -0
  87. hoja_server/identity_transfer.py +210 -0
  88. hoja_server/mcp_oauth.py +623 -0
  89. hoja_server/mcp_tools.py +579 -0
  90. hoja_server/meeting_policy.py +179 -0
  91. hoja_server/meetings.py +1332 -0
  92. hoja_server/meetings_api.py +909 -0
  93. hoja_server/model_providers.py +205 -0
  94. hoja_server/realtime.py +690 -0
  95. hoja_server/resolvers.py +1281 -0
  96. hoja_server/schema.graphql +477 -0
  97. hoja_server/schema_sdl.py +8 -0
  98. hoja_server/secrets_box.py +39 -0
  99. hoja_server/signup_config.py +292 -0
  100. hoja_server/signup_gate.py +393 -0
  101. hoja_server/signup_policy.py +97 -0
  102. hoja_server/signup_store.py +577 -0
  103. hoja_server/store.py +2179 -0
  104. hoja_server/sync.py +249 -0
  105. hoja_server/tenant_context.py +131 -0
  106. hoja_server/turnstile.py +81 -0
  107. hoja_server/writer.py +1262 -0
@@ -0,0 +1,1332 @@
1
+ """Meeting service: scheduling, guest links, waiting room, moderation, chat and SFU bookkeeping.
2
+
3
+ Every state change goes through ``meeting_policy`` (ABAC); this module only gathers the
4
+ attributes, applies the change and reports *who must be told* via ``Event`` objects (the
5
+ realtime hub in ``meetings_api`` delivers them). All methods are synchronous and are meant
6
+ to be run in a worker thread.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import secrets
14
+ import string
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timedelta, timezone
17
+
18
+ from sqlalchemy import and_, func, or_, select, update
19
+ from sqlalchemy.engine import Engine
20
+
21
+ from hoja_server import meeting_policy as P
22
+ from hoja_server.abac import Decision
23
+ from hoja_server.db import (
24
+ meeting,
25
+ meeting_chat,
26
+ meeting_invitee,
27
+ meeting_ring,
28
+ new_id,
29
+ now_iso,
30
+ token_hash,
31
+ user,
32
+ )
33
+ from hoja_server.db import (
34
+ meeting_participant as mp,
35
+ )
36
+ from hoja_server.store import team_visible, visible_team_clause
37
+
38
+ CODE_ALPHABET = "abcdefghjkmnpqrstuvwxyz"
39
+ CODE_RE = re.compile(r"^[a-z]{3}-[a-z]{4}-[a-z]{4}$")
40
+ TRACK_RE = re.compile(r"^(mic|cam|screen)-[A-Za-z0-9]{4,24}$")
41
+ TRACK_ACTION = {"mic": P.AUDIO, "cam": P.VIDEO, "screen": P.SCREEN}
42
+ ACCESS = ("invited", "team", "org")
43
+ SCREEN_SHARE = ("all", "host")
44
+ RECORDING = ("off", "allowed", "recording")
45
+ EMOJI = ("👍", "👏", "❤️", "😂", "🎉", "😮", "🙏", "✋")
46
+ DEFAULT_MAX_PARTICIPANTS = 25
47
+ MAX_TITLE = 200
48
+ MAX_CHAT = 2000
49
+ MAX_NAME = 80
50
+ CHAT_HISTORY = 100
51
+
52
+ SETTING_FIELDS = {
53
+ "waitingRoom": "waiting_room", "joinBeforeHost": "join_before_host", "muteOnEntry": "mute_on_entry",
54
+ "allowUnmute": "allow_unmute", "screenShare": "screen_share", "chatEnabled": "chat_enabled",
55
+ "locked": "locked",
56
+ }
57
+ MANAGE_FIELDS = {
58
+ "title": "title", "description": "description", "scheduledStart": "scheduled_start",
59
+ "durationMinutes": "duration_minutes", "access": "access", "teamId": "team_id", "issueId": "issue_id",
60
+ "projectId": "project_id", "linkEnabled": "link_enabled", "maxParticipants": "max_participants",
61
+ "recording": "recording",
62
+ }
63
+
64
+
65
+ def participant_cap() -> int:
66
+ try:
67
+ return max(2, int(os.environ.get("HOJA_MEETING_MAX_PARTICIPANTS", "100")))
68
+ except ValueError:
69
+ return 100
70
+
71
+
72
+ class MeetingError(Exception):
73
+ status = 400
74
+
75
+
76
+ class NotFound(MeetingError):
77
+ status = 404
78
+
79
+
80
+ class Invalid(MeetingError):
81
+ status = 400
82
+
83
+
84
+ class Conflict(MeetingError):
85
+ """The request is fine but needs a decision first (e.g. already in the meeting on another device)."""
86
+
87
+ status = 409
88
+
89
+ def __init__(self, message: str, payload: dict) -> None:
90
+ super().__init__(message)
91
+ self.payload = payload
92
+
93
+
94
+ class Denied(MeetingError):
95
+ status = 403
96
+
97
+ def __init__(self, decision: Decision) -> None:
98
+ super().__init__(decision.reason)
99
+ self.decision = decision
100
+
101
+
102
+ @dataclass
103
+ class Principal:
104
+ kind: str # "member" | "guest"
105
+ user_id: str | None = None
106
+ org_id: str | None = None
107
+ key_access: str | None = None
108
+ guest_token: str | None = None
109
+ seat_token: str | None = None # a member's companion-device seat (their main seat needs none)
110
+
111
+
112
+ @dataclass
113
+ class Event:
114
+ """A message for people *in* the meeting (delivered by participant id over the room socket)."""
115
+
116
+ to: frozenset
117
+ msg: dict
118
+
119
+
120
+ @dataclass
121
+ class Notice:
122
+ """A message for people *outside* the room (delivered by user id over the personal inbox socket)."""
123
+
124
+ users: frozenset
125
+ msg: dict
126
+
127
+
128
+ RING_SECONDS = 45
129
+ REMINDER_MINUTES = 5
130
+ RSVP_VALUES = ("accepted", "declined", "tentative")
131
+ EGRESS_USD_PER_GB = 0.05
132
+
133
+
134
+ def new_code() -> str:
135
+ pick = lambda n: "".join(secrets.choice(CODE_ALPHABET) for _ in range(n)) # noqa: E731
136
+ return f"{pick(3)}-{pick(4)}-{pick(4)}"
137
+
138
+
139
+ def normalize_code(code: str) -> str:
140
+ code = (code or "").strip().lower()
141
+ if not CODE_RE.match(code):
142
+ raise NotFound("Meeting not found.")
143
+ return code
144
+
145
+
146
+ def new_passcode() -> str:
147
+ return "".join(secrets.choice(string.digits) for _ in range(6))
148
+
149
+
150
+ def _passcode_hash(meeting_id: str, passcode: str) -> str:
151
+ return token_hash(f"{meeting_id}:{passcode}")
152
+
153
+
154
+ def _clean_text(value, limit: int, field: str, *, required=False) -> str | None:
155
+ if value is None:
156
+ if required:
157
+ raise Invalid(f"{field} is required.")
158
+ return None
159
+ text = "".join(ch for ch in str(value) if ch.isprintable() or ch in "\n\t").strip()
160
+ if required and not text:
161
+ raise Invalid(f"{field} is required.")
162
+ if len(text) > limit:
163
+ raise Invalid(f"{field} must be at most {limit} characters.")
164
+ return text
165
+
166
+
167
+ def _seconds(start: str | None, end: str | None) -> int | None:
168
+ if not start or not end:
169
+ return None
170
+ try:
171
+ return max(0, int((datetime.fromisoformat(end) - datetime.fromisoformat(start)).total_seconds()))
172
+ except ValueError:
173
+ return None
174
+
175
+
176
+ def _ics_text(value: str) -> str:
177
+ return (str(value).replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,")
178
+ .replace("\r", "").replace("\n", "\\n"))
179
+
180
+
181
+ def _ics_fold(line: str) -> str:
182
+ """RFC 5545: lines longer than 75 octets continue on the next line after a space."""
183
+ raw, out = line.encode(), []
184
+ while len(raw) > 75:
185
+ cut = 75
186
+ while cut > 0 and (raw[cut] & 0xC0) == 0x80: # never split a UTF-8 sequence
187
+ cut -= 1
188
+ out.append(raw[:cut].decode())
189
+ raw = b" " + raw[cut:]
190
+ out.append(raw.decode())
191
+ return "\r\n".join(out)
192
+
193
+
194
+ def _parse_start(value) -> str | None:
195
+ if value in (None, ""):
196
+ return None
197
+ try:
198
+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
199
+ except ValueError as exc:
200
+ raise Invalid("scheduledStart must be an ISO-8601 timestamp.") from exc
201
+ if parsed.tzinfo is None:
202
+ parsed = parsed.replace(tzinfo=timezone.utc)
203
+ return parsed.astimezone(timezone.utc).isoformat()
204
+
205
+
206
+ class MeetingService:
207
+ def __init__(self, engine: Engine) -> None:
208
+ self.engine = engine
209
+
210
+ # ------------------------------------------------------------------ attributes
211
+ def _meeting(self, conn, code: str):
212
+ row = conn.execute(select(meeting).where(meeting.c.code == normalize_code(code))).mappings().first()
213
+ if row is None:
214
+ raise NotFound("Meeting not found.")
215
+ return row
216
+
217
+ def organization_of(self, code: str) -> str | None:
218
+ """The workspace a meeting code belongs to (a system lookup: links cross workspaces)."""
219
+ try:
220
+ code = normalize_code(code)
221
+ except NotFound:
222
+ return None
223
+ with self.engine.connect() as conn:
224
+ return conn.execute(select(meeting.c.organization_id).where(meeting.c.code == code)).scalar()
225
+
226
+ def _me(self, conn, m, principal: Principal):
227
+ if principal.kind == "member":
228
+ if principal.seat_token: # a companion device presents the seat it was given
229
+ return conn.execute(select(mp).where(and_(
230
+ mp.c.meeting_id == m["id"], mp.c.user_id == principal.user_id,
231
+ mp.c.token_hash == token_hash(principal.seat_token)))).mappings().first()
232
+ return conn.execute(select(mp).where(and_(
233
+ mp.c.meeting_id == m["id"], mp.c.user_id == principal.user_id, mp.c.device_of.is_(None)))
234
+ .order_by(mp.c.created_at).limit(1)).mappings().first()
235
+ if principal.guest_token:
236
+ return conn.execute(select(mp).where(and_(mp.c.meeting_id == m["id"],
237
+ mp.c.token_hash == token_hash(principal.guest_token)))
238
+ ).mappings().first()
239
+ return None
240
+
241
+ def _subject(self, conn, m, principal: Principal, me, *, passcode: str | None = None) -> dict:
242
+ s: dict = {"kind": principal.kind, "bound": me is not None,
243
+ "passcode_ok": bool(passcode) and m["passcode_hash"] == _passcode_hash(m["id"], passcode)}
244
+ if me is not None:
245
+ s.update(role=me["role"], state=me["state"], was_admitted=me["joined_at"] is not None,
246
+ forced_mute=bool(me["muted_by_host"]) and not m["allow_unmute"])
247
+ if principal.kind != "member":
248
+ return s
249
+ u = conn.execute(select(user.c.admin, user.c.email, user.c.active).where(and_(
250
+ user.c.id == principal.user_id, user.c.organization_id == principal.org_id))).mappings().first()
251
+ same_org = bool(u and u["active"] is not False and principal.org_id == m["organization_id"])
252
+ s.update(same_org=same_org, admin=bool(u and u["admin"]), key_access=principal.key_access,
253
+ is_host=principal.user_id == m["host_id"])
254
+ if same_org:
255
+ clauses = [meeting_invitee.c.user_id == principal.user_id]
256
+ if u["email"]:
257
+ clauses.append(func.lower(meeting_invitee.c.email) == u["email"].lower())
258
+ inv = conn.execute(select(meeting_invitee.c.role).where(and_(
259
+ meeting_invitee.c.meeting_id == m["id"], or_(*clauses))).limit(1)).mappings().first()
260
+ s.update(invited=inv is not None, invite_role=inv["role"] if inv else None,
261
+ team_visible=bool(m["team_id"]) and team_visible(
262
+ conn, m["organization_id"], principal.user_id, m["team_id"]))
263
+ return s
264
+
265
+ def _resource(self, conn, m, *, target=None, actor=None) -> dict:
266
+ counts = conn.execute(select(mp.c.role, func.count()).where(and_(
267
+ mp.c.meeting_id == m["id"], mp.c.state == "admitted")).group_by(mp.c.role)).all()
268
+ admitted = sum(n for _, n in counts)
269
+ r = {"status": m["status"], "access": m["access"], "locked": m["locked"], "link_enabled": m["link_enabled"],
270
+ "waiting_room": m["waiting_room"], "join_before_host": m["join_before_host"],
271
+ "passcode_required": bool(m["passcode_hash"]), "full": admitted >= m["max_participants"],
272
+ "host_present": any(role in ("host", "cohost") for role, _ in counts),
273
+ "screen_share": m["screen_share"], "chat_enabled": m["chat_enabled"], "recording": m["recording"]}
274
+ if target is not None:
275
+ r["target_role"] = target["role"]
276
+ r["target_self"] = actor is not None and target["id"] == actor["id"]
277
+ return r
278
+
279
+ def _require(self, action: str, subject: dict, resource: dict) -> Decision:
280
+ decision = P.decide(action, subject, resource)
281
+ if not decision:
282
+ raise Denied(decision)
283
+ return decision
284
+
285
+ def _audience(self, conn, m) -> dict[str, frozenset]:
286
+ rows = conn.execute(select(mp.c.id, mp.c.role, mp.c.state).where(and_(
287
+ mp.c.meeting_id == m["id"], mp.c.state.in_(("admitted", "waiting"))))).all()
288
+ return {
289
+ "room": frozenset(i for i, _, st in rows if st == "admitted"),
290
+ "mods": frozenset(i for i, ro, st in rows if st == "admitted" and ro in ("host", "cohost")),
291
+ "everyone": frozenset(i for i, _, _ in rows),
292
+ }
293
+
294
+ # ------------------------------------------------------------------ serializers
295
+ @staticmethod
296
+ def pub(p) -> dict:
297
+ return {"id": p["id"], "name": p["display_name"], "kind": p["kind"], "role": p["role"], "state": p["state"],
298
+ "muted": bool(p["muted_by_host"]), "handRaised": bool(p["hand_raised"]),
299
+ "audio": bool(p["audio_on"]), "video": bool(p["video_on"]), "screen": bool(p["screen_on"]),
300
+ "sessionId": p["sfu_session_id"], "tracks": json.loads(p["tracks"] or "[]"),
301
+ "deviceOf": p["device_of"], "device": p["device_label"]}
302
+
303
+ def ser_meeting(self, conn, m, *, detail: bool = True) -> dict:
304
+ host = conn.execute(select(user.c.name, user.c.display_name).where(user.c.id == m["host_id"])
305
+ ).mappings().first() or {}
306
+ out = {"id": m["id"], "code": m["code"], "title": m["title"], "description": m["description"],
307
+ "hostId": m["host_id"], "hostName": host.get("display_name") or host.get("name"),
308
+ "teamId": m["team_id"], "issueId": m["issue_id"], "projectId": m["project_id"],
309
+ "access": m["access"], "linkEnabled": bool(m["link_enabled"]), "hasPasscode": bool(m["passcode_hash"]),
310
+ "status": m["status"], "scheduledStart": m["scheduled_start"], "durationMinutes": m["duration_minutes"],
311
+ "startedAt": m["started_at"], "endedAt": m["ended_at"], "createdAt": m["created_at"],
312
+ "durationSeconds": _seconds(m["started_at"], m["ended_at"]), "joinPath": f"/meet/{m['code']}",
313
+ "settings": {"waitingRoom": bool(m["waiting_room"]), "joinBeforeHost": bool(m["join_before_host"]),
314
+ "muteOnEntry": bool(m["mute_on_entry"]), "allowUnmute": bool(m["allow_unmute"]),
315
+ "screenShare": m["screen_share"], "chatEnabled": bool(m["chat_enabled"]),
316
+ "locked": bool(m["locked"]), "recording": m["recording"],
317
+ "maxParticipants": m["max_participants"]}}
318
+ if detail:
319
+ out["participantCount"] = conn.execute(select(func.count()).where(and_(
320
+ mp.c.meeting_id == m["id"], mp.c.state == "admitted"))).scalar()
321
+ return out
322
+
323
+ # ------------------------------------------------------------------ create / read
324
+ def create(self, principal: Principal, data: dict) -> tuple[dict, str | None, list]:
325
+ if principal.kind != "member":
326
+ raise Denied(Decision(False, "Sign in to create a meeting."))
327
+ with self.engine.begin() as conn:
328
+ subject = self._subject(conn, {"organization_id": principal.org_id, "host_id": None, "id": None,
329
+ "passcode_hash": None, "allow_unmute": True, "team_id": None},
330
+ principal, None)
331
+ self._require(P.CREATE, subject, {})
332
+ values, passcode = self._fresh_values(conn, principal, data)
333
+ for _ in range(8):
334
+ values["code"] = new_code()
335
+ if conn.execute(select(meeting.c.id).where(meeting.c.code == values["code"])).first() is None:
336
+ break
337
+ else:
338
+ raise Invalid("Could not allocate a meeting code. Try again.")
339
+ conn.execute(meeting.insert().values(**values))
340
+ if passcode:
341
+ conn.execute(update(meeting).where(meeting.c.id == values["id"]).values(
342
+ passcode_hash=_passcode_hash(values["id"], passcode)))
343
+ m = conn.execute(select(meeting).where(meeting.c.id == values["id"])).mappings().first()
344
+ fresh = self._add_invitees(conn, m, principal.user_id, data.get("invitees") or [], "attendee")
345
+ return self.ser_meeting(conn, m), passcode, self._invited_notices(conn, m, principal.user_id, fresh)
346
+
347
+ def _fresh_values(self, conn, principal: Principal, data: dict) -> tuple[dict, str | None]:
348
+ ts = now_iso()
349
+ v = {"id": new_id(), "organization_id": principal.org_id, "host_id": principal.user_id,
350
+ "title": _clean_text(data.get("title") or "Meeting", MAX_TITLE, "title", required=True),
351
+ "description": _clean_text(data.get("description"), 5000, "description"), "access": "invited",
352
+ "link_enabled": False, "waiting_room": True, "join_before_host": False, "mute_on_entry": True,
353
+ "allow_unmute": True, "screen_share": "all", "chat_enabled": True, "locked": False,
354
+ "recording": "off", "max_participants": DEFAULT_MAX_PARTICIPANTS, "status": "scheduled",
355
+ "scheduled_start": None, "duration_minutes": None, "team_id": None, "issue_id": None,
356
+ "project_id": None, "created_at": ts, "updated_at": ts}
357
+ v.update(self._clean_fields(conn, principal, {**{k: data[k] for k in SETTING_FIELDS if k in data},
358
+ **{k: data[k] for k in MANAGE_FIELDS
359
+ if k in data and k != "title" and k != "description"}}))
360
+ if v["access"] == "team" and not v["team_id"]:
361
+ raise Invalid("A team is required for team meetings.")
362
+ passcode = self._wanted_passcode(data.get("passcode"))
363
+ if v["link_enabled"] and not v["waiting_room"] and not passcode:
364
+ passcode = new_passcode() # a public link needs a waiting room or a passcode
365
+ return v, passcode
366
+
367
+ @staticmethod
368
+ def _wanted_passcode(value) -> str | None:
369
+ if value is True:
370
+ return new_passcode()
371
+ if isinstance(value, str) and value:
372
+ if not 4 <= len(value) <= 10 or not value.isalnum():
373
+ raise Invalid("Passcode must be 4-10 letters or digits.")
374
+ return value
375
+ return None
376
+
377
+ def _clean_fields(self, conn, principal: Principal, patch: dict) -> dict:
378
+ out: dict = {}
379
+ for key, col in {**SETTING_FIELDS, **MANAGE_FIELDS}.items():
380
+ if key not in patch:
381
+ continue
382
+ val = patch[key]
383
+ if col in ("waiting_room", "join_before_host", "mute_on_entry", "allow_unmute", "chat_enabled",
384
+ "locked", "link_enabled"):
385
+ if not isinstance(val, bool):
386
+ raise Invalid(f"{key} must be true or false.")
387
+ elif col == "access" and val not in ACCESS:
388
+ raise Invalid(f"access must be one of {', '.join(ACCESS)}.")
389
+ elif col == "screen_share" and val not in SCREEN_SHARE:
390
+ raise Invalid("screenShare must be 'all' or 'host'.")
391
+ elif col == "recording" and val not in RECORDING[:2]:
392
+ raise Invalid("recording must be 'off' or 'allowed'.")
393
+ elif col == "scheduled_start":
394
+ val = _parse_start(val)
395
+ elif col == "duration_minutes":
396
+ if val is not None and (not isinstance(val, int) or isinstance(val, bool) or not 5 <= val <= 1440):
397
+ raise Invalid("durationMinutes must be between 5 and 1440.")
398
+ elif col == "max_participants":
399
+ if not isinstance(val, int) or isinstance(val, bool) or not 2 <= val <= participant_cap():
400
+ raise Invalid(f"maxParticipants must be between 2 and {participant_cap()}.")
401
+ elif col == "team_id":
402
+ if val is not None and not team_visible(conn, principal.org_id, principal.user_id, str(val)):
403
+ raise Invalid("Unknown team.")
404
+ elif col == "title":
405
+ val = _clean_text(val, MAX_TITLE, "title", required=True)
406
+ elif col == "description":
407
+ val = _clean_text(val, 5000, "description")
408
+ elif col in ("issue_id", "project_id"):
409
+ val = str(val) if val else None
410
+ out[col] = val
411
+ return out
412
+
413
+ def get(self, code: str, principal: Principal) -> dict:
414
+ with self.engine.connect() as conn:
415
+ m = self._meeting(conn, code)
416
+ me = self._me(conn, m, principal)
417
+ subject = self._subject(conn, m, principal, me)
418
+ self._require(P.VIEW, subject, self._resource(conn, m))
419
+ out = self.ser_meeting(conn, m)
420
+ if m["status"] in ("ended", "cancelled"):
421
+ out["recap"] = self._recap(conn, m)
422
+ if subject.get("is_host") or subject.get("admin"):
423
+ out["usage"] = self._usage(conn, m)
424
+ out["isHost"] = bool(subject.get("is_host"))
425
+ if subject.get("kind") == "member" and subject.get("same_org"):
426
+ out["myResponse"] = "accepted" if subject.get("is_host") else self._my_responses(
427
+ conn, principal).get(m["id"])
428
+ return out
429
+
430
+ def _recap(self, conn, m) -> dict:
431
+ """After a meeting: when it ran, for how long and who came (each device listed once)."""
432
+ rows = conn.execute(select(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.joined_at.is_not(None)))
433
+ .order_by(mp.c.joined_at)).mappings().all()
434
+ end = m["ended_at"]
435
+ people = []
436
+ for r in rows:
437
+ left = r["left_at"] or end
438
+ people.append({"name": r["display_name"], "kind": r["kind"], "role": r["role"],
439
+ "device": r["device_label"] if r["device_of"] else None,
440
+ "joinedAt": r["joined_at"], "leftAt": left, "seconds": _seconds(r["joined_at"], left)})
441
+ return {"startedAt": m["started_at"], "endedAt": end, "durationSeconds": _seconds(m["started_at"], end),
442
+ "attendees": people,
443
+ "peopleCount": len({r["user_id"] or r["id"] for r in rows})}
444
+
445
+ def _usage(self, conn, m) -> dict:
446
+ """What this meeting cost: Cloudflare bills the bytes it sends *to* participants."""
447
+ down, up = conn.execute(select(func.coalesce(func.sum(mp.c.bytes_in), 0), func.coalesce(
448
+ func.sum(mp.c.bytes_out), 0)).where(mp.c.meeting_id == m["id"])).one()
449
+ return {"egressBytes": int(down), "ingressBytes": int(up),
450
+ "estimatedCostUsd": round(int(down) / 1e9 * EGRESS_USD_PER_GB, 4)}
451
+
452
+ def preview(self, code: str) -> dict:
453
+ """What an anonymous visitor with the link may see; uniform 404 otherwise."""
454
+ with self.engine.connect() as conn:
455
+ m = self._meeting(conn, code)
456
+ if not P.decide(P.PREVIEW, {"kind": "guest"}, self._resource(conn, m)):
457
+ raise NotFound("Meeting not found.")
458
+ host = conn.execute(select(user.c.name, user.c.display_name).where(user.c.id == m["host_id"])
459
+ ).mappings().first() or {}
460
+ return {"code": m["code"], "title": m["title"], "status": m["status"],
461
+ "endedAt": m["ended_at"], "durationSeconds": _seconds(m["started_at"], m["ended_at"]),
462
+ "hostName": host.get("display_name") or host.get("name"),
463
+ "scheduledStart": m["scheduled_start"], "passcodeRequired": bool(m["passcode_hash"]),
464
+ "waitingRoom": bool(m["waiting_room"])}
465
+
466
+ def _blank_meeting(self, principal: Principal) -> dict:
467
+ return {"organization_id": principal.org_id, "host_id": None, "id": None, "passcode_hash": None,
468
+ "allow_unmute": True, "team_id": None}
469
+
470
+ def _involved(self, conn, principal: Principal):
471
+ """SQL clause for meetings this member may see: hosting, invited, took part, workspace- or team-wide."""
472
+ email = conn.execute(select(user.c.email).where(user.c.id == principal.user_id)).scalar()
473
+ invited = select(meeting_invitee.c.meeting_id).where(or_(
474
+ meeting_invitee.c.user_id == principal.user_id,
475
+ *([func.lower(meeting_invitee.c.email) == email.lower()] if email else [])))
476
+ took_part = select(mp.c.meeting_id).where(mp.c.user_id == principal.user_id)
477
+ team_clause = visible_team_clause(conn, principal.org_id, principal.user_id, meeting.c.team_id)
478
+ team_access = and_(meeting.c.access == "team", meeting.c.team_id.is_not(None),
479
+ team_clause if team_clause is not None else True)
480
+ return and_(meeting.c.organization_id == principal.org_id,
481
+ or_(meeting.c.host_id == principal.user_id, meeting.c.id.in_(invited),
482
+ meeting.c.id.in_(took_part), meeting.c.access == "org", team_access))
483
+
484
+ def _member_listing(self, conn, principal: Principal) -> None:
485
+ if principal.kind != "member":
486
+ raise Denied(Decision(False, "Sign in to list meetings."))
487
+ self._require(P.LIST, self._subject(conn, self._blank_meeting(principal), principal, None), {})
488
+
489
+ def _my_responses(self, conn, principal: Principal) -> dict[str, str]:
490
+ email = conn.execute(select(user.c.email).where(user.c.id == principal.user_id)).scalar()
491
+ rows = conn.execute(select(meeting_invitee.c.meeting_id, meeting_invitee.c.response).where(or_(
492
+ meeting_invitee.c.user_id == principal.user_id,
493
+ *([func.lower(meeting_invitee.c.email) == email.lower()] if email else [])))).all()
494
+ return {mid: resp for mid, resp in rows}
495
+
496
+ def list(self, principal: Principal, scope: str = "upcoming", limit: int = 50) -> list[dict]:
497
+ limit = max(1, min(int(limit), 200))
498
+ with self.engine.connect() as conn:
499
+ self._member_listing(conn, principal)
500
+ states = ("scheduled", "live") if scope == "upcoming" else ("ended", "cancelled")
501
+ order = (meeting.c.scheduled_start.asc().nulls_last(), meeting.c.created_at.desc()) \
502
+ if scope == "upcoming" else (meeting.c.created_at.desc(),)
503
+ rows = conn.execute(select(meeting).where(and_(
504
+ self._involved(conn, principal), meeting.c.status.in_(states)))
505
+ .order_by(*order).limit(limit)).mappings().all()
506
+ mine = self._my_responses(conn, principal)
507
+ return [self._with_me(conn, m, principal, mine) for m in rows]
508
+
509
+ def _with_me(self, conn, m, principal: Principal, mine: dict) -> dict:
510
+ out = self.ser_meeting(conn, m, detail=False)
511
+ out["isHost"] = m["host_id"] == principal.user_id
512
+ out["myResponse"] = "accepted" if out["isHost"] else mine.get(m["id"])
513
+ return out
514
+
515
+ def calendar(self, principal: Principal, start: str, end: str) -> list[dict]:
516
+ """Meetings that start (or, when unscheduled, were created) in [start, end)."""
517
+ lo, hi = _parse_start(start), _parse_start(end)
518
+ if not lo or not hi or hi <= lo:
519
+ raise Invalid("from and to must be ISO-8601 timestamps with from < to.")
520
+ if datetime.fromisoformat(hi) - datetime.fromisoformat(lo) > timedelta(days=100):
521
+ raise Invalid("The calendar range is limited to 100 days.")
522
+ with self.engine.connect() as conn:
523
+ self._member_listing(conn, principal)
524
+ rows = conn.execute(select(meeting).where(and_(
525
+ self._involved(conn, principal), meeting.c.status != "cancelled",
526
+ or_(and_(meeting.c.scheduled_start >= lo, meeting.c.scheduled_start < hi),
527
+ and_(meeting.c.scheduled_start.is_(None), meeting.c.created_at >= lo,
528
+ meeting.c.created_at < hi)))).order_by(meeting.c.scheduled_start.asc().nulls_last(),
529
+ meeting.c.created_at).limit(500)).mappings().all()
530
+ mine = self._my_responses(conn, principal)
531
+ return [self._with_me(conn, m, principal, mine) for m in rows]
532
+
533
+ def invitations(self, principal: Principal) -> list[dict]:
534
+ """Meetings I was invited to and have not answered yet."""
535
+ with self.engine.connect() as conn:
536
+ self._member_listing(conn, principal)
537
+ email = conn.execute(select(user.c.email).where(user.c.id == principal.user_id)).scalar()
538
+ cutoff = (datetime.now(timezone.utc) - timedelta(hours=4)).isoformat()
539
+ rows = conn.execute(
540
+ select(meeting, meeting_invitee.c.invited_by).select_from(
541
+ meeting.join(meeting_invitee, meeting_invitee.c.meeting_id == meeting.c.id)).where(and_(
542
+ meeting.c.organization_id == principal.org_id, meeting_invitee.c.response == "needsAction",
543
+ meeting.c.status.in_(("scheduled", "live")), meeting.c.host_id != principal.user_id,
544
+ or_(meeting.c.scheduled_start.is_(None), meeting.c.scheduled_start >= cutoff),
545
+ or_(meeting_invitee.c.user_id == principal.user_id,
546
+ *([func.lower(meeting_invitee.c.email) == email.lower()] if email else []))))
547
+ .order_by(meeting.c.scheduled_start.asc().nulls_last()).limit(100)).mappings().all()
548
+ out = []
549
+ for r in rows:
550
+ item = self.ser_meeting(conn, r, detail=False)
551
+ item["myResponse"] = "needsAction"
552
+ inviter = conn.execute(select(user.c.name, user.c.display_name).where(
553
+ user.c.id == r["invited_by"])).mappings().first() or {}
554
+ item["invitedBy"] = inviter.get("display_name") or inviter.get("name")
555
+ out.append(item)
556
+ return out
557
+
558
+ def people(self, principal: Principal) -> list[dict]:
559
+ with self.engine.connect() as conn:
560
+ self._member_listing(conn, principal)
561
+ rows = conn.execute(select(user.c.id, user.c.name, user.c.display_name, user.c.email, user.c.avatar_url)
562
+ .where(and_(user.c.organization_id == principal.org_id,
563
+ user.c.active.is_not(False), user.c.archived_at.is_(None)))
564
+ .order_by(func.lower(user.c.name)).limit(1000)).mappings().all()
565
+ return [{"id": r["id"], "name": r["display_name"] or r["name"], "email": r["email"],
566
+ "avatarUrl": r["avatar_url"]} for r in rows]
567
+
568
+ # ------------------------------------------------------------------ update / invite
569
+ def update(self, code: str, principal: Principal, patch: dict) -> tuple[dict, str | None, list[Event]]:
570
+ with self.engine.begin() as conn:
571
+ m = self._meeting(conn, code)
572
+ me = self._me(conn, m, principal)
573
+ subject = self._subject(conn, m, principal, me)
574
+ resource = self._resource(conn, m)
575
+ manage_only = {k for k in patch if k in MANAGE_FIELDS} | ({"passcode"} if "passcode" in patch else set())
576
+ unknown = set(patch) - set(MANAGE_FIELDS) - set(SETTING_FIELDS) - {"passcode"}
577
+ if unknown:
578
+ raise Invalid(f"Unknown fields: {', '.join(sorted(unknown))}.")
579
+ self._require(P.MANAGE if manage_only else P.SETTINGS, subject, resource)
580
+ values = self._clean_fields(conn, principal, patch)
581
+ passcode = None
582
+ if "passcode" in patch:
583
+ if patch["passcode"] in (False, None, ""):
584
+ values["passcode_hash"] = None
585
+ else:
586
+ passcode = self._wanted_passcode(patch["passcode"])
587
+ values["passcode_hash"] = _passcode_hash(m["id"], passcode)
588
+ access = values.get("access", m["access"])
589
+ team_id = values.get("team_id", m["team_id"])
590
+ if access == "team" and not team_id:
591
+ raise Invalid("A team is required for team meetings.")
592
+ link = values.get("link_enabled", m["link_enabled"])
593
+ room = values.get("waiting_room", m["waiting_room"])
594
+ has_code = values["passcode_hash"] if "passcode_hash" in values else m["passcode_hash"]
595
+ if link and not room and not has_code:
596
+ passcode = new_passcode()
597
+ values["passcode_hash"] = _passcode_hash(m["id"], passcode)
598
+ if values:
599
+ values["updated_at"] = now_iso()
600
+ conn.execute(update(meeting).where(meeting.c.id == m["id"]).values(**values))
601
+ before = m
602
+ m = conn.execute(select(meeting).where(meeting.c.id == m["id"])).mappings().first()
603
+ events: list = [Event(self._audience(conn, m)["everyone"],
604
+ {"t": "meeting", "meeting": self.ser_meeting(conn, m)})]
605
+ if any(before[k] != m[k] for k in ("title", "scheduled_start", "duration_minutes")):
606
+ events.append(self._notice_invitees(conn, m, {"t": "meeting_updated",
607
+ "meeting": self.ser_meeting(conn, m, detail=False)},
608
+ exclude={principal.user_id}))
609
+ return self.ser_meeting(conn, m), passcode, events
610
+
611
+ def cancel(self, code: str, principal: Principal) -> list[Event]:
612
+ with self.engine.begin() as conn:
613
+ m = self._meeting(conn, code)
614
+ me = self._me(conn, m, principal)
615
+ self._require(P.MANAGE, self._subject(conn, m, principal, me), self._resource(conn, m))
616
+ events = self._finish(conn, m, "cancelled" if m["status"] == "scheduled" else "ended")
617
+ events.append(self._notice_invitees(conn, m, {"t": "meeting_cancelled", "code": m["code"],
618
+ "title": m["title"]}, exclude={principal.user_id}))
619
+ return events
620
+
621
+ def add_invitees(self, code: str, principal: Principal, invitees: list,
622
+ role: str = "attendee") -> tuple[list[dict], list]:
623
+ if role not in ("attendee", "cohost"):
624
+ raise Invalid("role must be 'attendee' or 'cohost'.")
625
+ with self.engine.begin() as conn:
626
+ m = self._meeting(conn, code)
627
+ me = self._me(conn, m, principal)
628
+ subject = self._subject(conn, m, principal, me)
629
+ self._require(P.INVITE, subject, self._resource(conn, m))
630
+ if role == "cohost":
631
+ self._require(P.MANAGE, subject, self._resource(conn, m))
632
+ fresh = self._add_invitees(conn, m, principal.user_id, invitees, role)
633
+ return self._invitees(conn, m), self._invited_notices(conn, m, principal.user_id, fresh)
634
+
635
+ def _add_invitees(self, conn, m, inviter_id, invitees: list, role: str) -> list[str]:
636
+ """Record invitees; returns the workspace members newly invited (they get a notification)."""
637
+ fresh: list[str] = []
638
+ if not isinstance(invitees, list) or len(invitees) > 200:
639
+ raise Invalid("invitees must be a list of at most 200 emails or user ids.")
640
+ for raw in invitees:
641
+ ref = str(raw or "").strip()
642
+ if not ref:
643
+ continue
644
+ row = conn.execute(select(user.c.id).where(and_(
645
+ user.c.organization_id == m["organization_id"],
646
+ or_(user.c.id == ref, func.lower(user.c.email) == ref.lower())))).first()
647
+ if row is None and "@" not in ref:
648
+ raise Invalid(f"Unknown invitee {ref!r}.")
649
+ uid, email = (row[0], None) if row else (None, ref.lower()[:254])
650
+ dup = conn.execute(select(meeting_invitee.c.id).where(and_(
651
+ meeting_invitee.c.meeting_id == m["id"],
652
+ meeting_invitee.c.user_id == uid if uid else func.lower(meeting_invitee.c.email) == email))).first()
653
+ if dup:
654
+ if role == "cohost":
655
+ conn.execute(update(meeting_invitee).where(meeting_invitee.c.id == dup[0]).values(role=role))
656
+ continue
657
+ conn.execute(meeting_invitee.insert().values(
658
+ id=new_id(), meeting_id=m["id"], user_id=uid, email=email, role=role, invited_by=inviter_id,
659
+ created_at=now_iso()))
660
+ if uid and uid != inviter_id:
661
+ fresh.append(uid)
662
+ return fresh
663
+
664
+ def _invitees(self, conn, m) -> list[dict]:
665
+ rows = conn.execute(select(meeting_invitee, user.c.name, user.c.email.label("user_email")).select_from(
666
+ meeting_invitee.outerjoin(user, user.c.id == meeting_invitee.c.user_id)).where(
667
+ meeting_invitee.c.meeting_id == m["id"]).order_by(meeting_invitee.c.created_at)).mappings().all()
668
+ return [{"id": r["id"], "userId": r["user_id"], "email": r["user_email"] or r["email"], "name": r["name"],
669
+ "role": r["role"], "response": r["response"]} for r in rows]
670
+
671
+ def invitees(self, code: str, principal: Principal) -> list[dict]:
672
+ with self.engine.connect() as conn:
673
+ m = self._meeting(conn, code)
674
+ me = self._me(conn, m, principal)
675
+ self._require(P.INVITE, self._subject(conn, m, principal, me), self._resource(conn, m))
676
+ return self._invitees(conn, m)
677
+
678
+ def remove_invitee(self, code: str, principal: Principal, invitee_id: str) -> None:
679
+ with self.engine.begin() as conn:
680
+ m = self._meeting(conn, code)
681
+ me = self._me(conn, m, principal)
682
+ self._require(P.MANAGE, self._subject(conn, m, principal, me), self._resource(conn, m))
683
+ conn.execute(meeting_invitee.delete().where(and_(
684
+ meeting_invitee.c.id == invitee_id, meeting_invitee.c.meeting_id == m["id"])))
685
+
686
+ # ------------------------------------------------------------------ join / leave
687
+ def join(self, code: str, principal: Principal, *, display_name: str | None = None,
688
+ passcode: str | None = None, device_id: str | None = None, device_label: str | None = None,
689
+ mode: str | None = None) -> dict:
690
+ """Join (or rejoin). A member already in on another device must choose: ``switch`` takes the seat
691
+ over, ``companion`` adds this device as a second seat (e.g. a phone for the mic)."""
692
+ if mode not in (None, "switch", "companion"):
693
+ raise Invalid("mode must be 'switch' or 'companion'.")
694
+ device_id = (device_id or "")[:64] or None
695
+ device_label = _clean_text(device_label, 24, "deviceLabel") or None
696
+ with self.engine.begin() as conn:
697
+ m = self._meeting(conn, code)
698
+ if principal.kind == "member" and principal.org_id != m["organization_id"]:
699
+ principal = Principal("guest") # a member of another workspace joins as a guest
700
+ me = self._me(conn, m, principal)
701
+ subject = self._subject(conn, m, principal, me, passcode=passcode)
702
+ resource = self._resource(conn, m)
703
+ self._require(P.JOIN, subject, resource)
704
+ events: list[Event] = []
705
+ primary = None
706
+ if principal.kind == "member" and me is not None and me["device_of"] is None and not principal.seat_token:
707
+ active = me["state"] in ("admitted", "waiting")
708
+ if active and me["device_id"] != device_id: # another device holds the seat
709
+ if mode is None:
710
+ raise Conflict("You are already in this meeting on another device.", {
711
+ "code": "already_joined", "device": me["device_label"] or "another device",
712
+ "since": me["joined_at"] or me["created_at"], "canCompanion": me["state"] == "admitted"})
713
+ if mode == "companion":
714
+ if me["state"] != "admitted":
715
+ raise Invalid("Wait to be admitted on your main device first.")
716
+ primary, me = me, None
717
+ subject = {**subject, "companion": True, "bound": False, "role": None, "state": None}
718
+ else: # switch: the old device is told to stand down
719
+ events.append(Event(frozenset({me["id"]}), {"t": "taken_over"}))
720
+ elif mode == "companion" and not active:
721
+ raise Invalid("Join on your main device first, then add this one.")
722
+ elif principal.kind == "member" and me is None and mode == "companion":
723
+ raise Invalid("Join on your main device first, then add this one.")
724
+ entered = bool(P.decide(P.ENTER, subject, resource))
725
+ if principal.kind == "member":
726
+ if me is not None and me["device_of"]:
727
+ name = me["display_name"] # a companion keeps its label
728
+ else:
729
+ row = conn.execute(select(user.c.display_name, user.c.name).where(
730
+ user.c.id == principal.user_id)).mappings().first() or {}
731
+ name = row.get("display_name") or row.get("name") or "Member"
732
+ if primary is not None:
733
+ name = f"{name} ({device_label or 'Other device'})"
734
+ else:
735
+ name = _clean_text(display_name, MAX_NAME, "name") or (me["display_name"] if me else None)
736
+ if not name:
737
+ raise Invalid("A display name is required.")
738
+ if primary is not None or (me is not None and me["device_of"]):
739
+ role = "attendee" # companions never carry moderation powers
740
+ elif subject.get("is_host"):
741
+ role = "host"
742
+ elif subject.get("invite_role") == "cohost" or (me and me["role"] in ("host", "cohost")):
743
+ role = "cohost"
744
+ else:
745
+ role = "attendee"
746
+ entered = entered or bool(me and me["state"] == "admitted") # a refresh must not demote anyone
747
+ state = "admitted" if entered else "waiting"
748
+ ts = now_iso()
749
+ raw_token = None
750
+ if me is None:
751
+ pid = new_id()
752
+ if principal.kind == "guest" or primary is not None:
753
+ raw_token = secrets.token_urlsafe(32)
754
+ conn.execute(mp.insert().values(
755
+ id=pid, meeting_id=m["id"], user_id=principal.user_id if principal.kind == "member" else None,
756
+ kind=principal.kind, display_name=name, role=role, state=state,
757
+ token_hash=token_hash(raw_token) if raw_token else None, muted_by_host=False,
758
+ hand_raised=False, created_at=ts,
759
+ device_of=primary["id"] if primary is not None else None))
760
+ else:
761
+ pid = me["id"]
762
+ first_entry = state == "admitted" and (me is None or me["joined_at"] is None)
763
+ conn.execute(update(mp).where(mp.c.id == pid).values(
764
+ state=state, role=role, display_name=name, left_at=None, hand_raised=False,
765
+ device_id=device_id, device_label=device_label,
766
+ **({"joined_at": ts, "muted_by_host": bool(m["mute_on_entry"]) and role == "attendee"}
767
+ if first_entry else {})))
768
+ released: list[str] = []
769
+ if state == "admitted":
770
+ self._go_live(conn, m, ts)
771
+ if role in ("host", "cohost") and not m["waiting_room"]:
772
+ released = self._release_waiting(conn, m, ts)
773
+ me_row = conn.execute(select(mp).where(mp.c.id == pid)).mappings().first()
774
+ audience = self._audience(conn, m)
775
+ if state == "admitted":
776
+ events.append(Event(audience["room"] - {pid}, {"t": "joined", "participant": self.pub(me_row)}))
777
+ else:
778
+ events.append(Event(audience["mods"], {"t": "waiting", "participant": self.pub(me_row)}))
779
+ events.extend(Event(frozenset({r}), {"t": "resync"}) for r in released)
780
+ events.extend(Event(audience["room"] - {r}, {"t": "joined", "participant": self.pub(
781
+ conn.execute(select(mp).where(mp.c.id == r)).mappings().first())}) for r in released)
782
+ m = conn.execute(select(meeting).where(meeting.c.id == m["id"])).mappings().first()
783
+ return {"participant": self.pub(me_row), "guestToken": raw_token if principal.kind == "guest" else None,
784
+ "seatToken": raw_token if primary is not None else None, "state": state,
785
+ "meeting": self.ser_meeting(conn, m), "events": events,
786
+ "reason": None if entered else (P.decide(P.ENTER, subject, resource).reason)}
787
+
788
+ def _go_live(self, conn, m, ts: str) -> None:
789
+ if m["status"] == "scheduled":
790
+ conn.execute(update(meeting).where(meeting.c.id == m["id"]).values(
791
+ status="live", started_at=m["started_at"] or ts, updated_at=ts))
792
+
793
+ def _release_waiting(self, conn, m, ts: str) -> list[str]:
794
+ """Admit everyone parked while the host was away (no waiting room configured)."""
795
+ capacity = m["max_participants"] - conn.execute(select(func.count()).where(and_(
796
+ mp.c.meeting_id == m["id"], mp.c.state == "admitted"))).scalar()
797
+ rows = conn.execute(select(mp.c.id, mp.c.role, mp.c.joined_at).where(and_(
798
+ mp.c.meeting_id == m["id"], mp.c.state == "waiting")).order_by(mp.c.created_at)).all()
799
+ out = []
800
+ for pid, role, joined in rows[:max(capacity, 0)]:
801
+ conn.execute(update(mp).where(mp.c.id == pid).values(
802
+ state="admitted", **({"joined_at": ts, "muted_by_host": bool(m["mute_on_entry"])
803
+ and role == "attendee"} if joined is None else {})))
804
+ out.append(pid)
805
+ return out
806
+
807
+ def snapshot(self, code: str, principal: Principal) -> dict:
808
+ """Full state for one connected participant (waiting or admitted)."""
809
+ with self.engine.connect() as conn:
810
+ m = self._meeting(conn, code)
811
+ me = self._me(conn, m, principal)
812
+ subject = self._subject(conn, m, principal, me)
813
+ resource = self._resource(conn, m)
814
+ self._require(P.VIEW, subject, resource)
815
+ if me is None or me["state"] not in ("waiting", "admitted"):
816
+ raise Denied(Decision(False, "Join the meeting first."))
817
+ out = {"meeting": self.ser_meeting(conn, m), "you": self.pub(me), "participants": [], "waiting": [],
818
+ "chat": []}
819
+ if me["state"] == "admitted":
820
+ rows = conn.execute(select(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.state == "admitted"))
821
+ .order_by(mp.c.joined_at)).mappings().all()
822
+ out["participants"] = [self.pub(p) for p in rows]
823
+ if me["role"] in ("host", "cohost"):
824
+ wait = conn.execute(select(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.state == "waiting"))
825
+ .order_by(mp.c.created_at)).mappings().all()
826
+ out["waiting"] = [self.pub(p) for p in wait]
827
+ chat = conn.execute(select(meeting_chat).where(and_(
828
+ meeting_chat.c.meeting_id == m["id"],
829
+ or_(meeting_chat.c.recipient_id.is_(None), meeting_chat.c.recipient_id == me["id"],
830
+ meeting_chat.c.sender_id == me["id"]))).order_by(meeting_chat.c.created_at.desc())
831
+ .limit(CHAT_HISTORY)).mappings().all()
832
+ out["chat"] = [self._chat(c) for c in reversed(chat)]
833
+ return out
834
+
835
+ @staticmethod
836
+ def _chat(c) -> dict:
837
+ return {"id": c["id"], "from": c["sender_id"], "to": c["recipient_id"], "body": c["body"],
838
+ "at": c["created_at"]}
839
+
840
+ def leave(self, code: str, principal: Principal) -> list[Event]:
841
+ with self.engine.begin() as conn:
842
+ m = self._meeting(conn, code)
843
+ me = self._me(conn, m, principal)
844
+ if me is None or me["state"] not in ("waiting", "admitted"):
845
+ return []
846
+ return self._leave(conn, m, me)
847
+
848
+ def leave_by_id(self, participant_id: str) -> list[Event]:
849
+ """Used by the hub when a participant's last socket stayed closed past the grace period."""
850
+ with self.engine.begin() as conn:
851
+ me = conn.execute(select(mp).where(mp.c.id == participant_id)).mappings().first()
852
+ if me is None or me["state"] not in ("waiting", "admitted"):
853
+ return []
854
+ m = conn.execute(select(meeting).where(meeting.c.id == me["meeting_id"])).mappings().first()
855
+ return self._leave(conn, m, me)
856
+
857
+ def _leave(self, conn, m, me) -> list[Event]:
858
+ was_admitted = me["state"] == "admitted"
859
+ conn.execute(update(mp).where(mp.c.id == me["id"]).values(
860
+ state="left", left_at=now_iso(), hand_raised=False, sfu_session_id=None, sfu_sub_session_id=None,
861
+ tracks=None, audio_on=False, video_on=False, screen_on=False))
862
+ audience = self._audience(conn, m)
863
+ events = [Event(audience["room"] if was_admitted else audience["mods"],
864
+ {"t": "left", "id": me["id"]})]
865
+ if was_admitted and not audience["room"] and m["status"] == "live":
866
+ events += self._finish(conn, m, "scheduled" if m["scheduled_start"] else "ended", audience=audience)
867
+ return events
868
+
869
+ def _finish(self, conn, m, status: str, audience=None) -> list:
870
+ audience = audience or self._audience(conn, m)
871
+ ts = now_iso()
872
+ conn.execute(update(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.state == "admitted")).values(
873
+ state="left", left_at=ts, sfu_session_id=None, sfu_sub_session_id=None, tracks=None, hand_raised=False,
874
+ audio_on=False, video_on=False, screen_on=False))
875
+ ended = status in ("ended", "cancelled")
876
+ if ended:
877
+ conn.execute(update(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.state == "waiting")
878
+ ).values(state="denied"))
879
+ conn.execute(update(meeting).where(meeting.c.id == m["id"]).values(
880
+ status=status, updated_at=ts, locked=False, **({"ended_at": ts} if ended else {})))
881
+ recipients = audience["everyone"] if ended else audience["room"]
882
+ events: list = [Event(recipients, {"t": "ended" if ended else "emptied", "status": status})]
883
+ if ended:
884
+ events.extend(self._end_rings(conn, m, "cancelled"))
885
+ return events
886
+
887
+ # ------------------------------------------------------------------ in-meeting actions
888
+ def perform(self, code: str, principal: Principal, action: str, payload: dict | None = None) -> dict:
889
+ payload = payload or {}
890
+ handler = getattr(self, f"_act_{action}", None)
891
+ if handler is None or action.startswith("_"):
892
+ raise Invalid(f"Unknown action {action!r}.")
893
+ with self.engine.begin() as conn:
894
+ m = self._meeting(conn, code)
895
+ me = self._me(conn, m, principal)
896
+ subject = self._subject(conn, m, principal, me)
897
+ ctx = {"m": m, "me": me, "subject": subject, "principal": principal}
898
+ result, events = handler(conn, ctx, payload)
899
+ return {"result": result or {}, "events": events}
900
+
901
+ def _target(self, conn, ctx, payload):
902
+ tid = str(payload.get("target") or "")
903
+ row = conn.execute(select(mp).where(and_(mp.c.id == tid, mp.c.meeting_id == ctx["m"]["id"]))
904
+ ).mappings().first() if tid else None
905
+ if row is None:
906
+ raise Invalid("Unknown participant.")
907
+ return row
908
+
909
+ def _check(self, conn, ctx, action, target=None):
910
+ resource = self._resource(conn, ctx["m"], target=target, actor=ctx["me"])
911
+ self._require(action, ctx["subject"], resource)
912
+ return resource
913
+
914
+ def _fresh(self, conn, pid):
915
+ return conn.execute(select(mp).where(mp.c.id == pid)).mappings().first()
916
+
917
+ def _updated(self, conn, ctx, pid, to="room") -> Event:
918
+ return Event(self._audience(conn, ctx["m"])[to], {"t": "participant", "participant": self.pub(self._fresh(conn, pid))})
919
+
920
+ def _act_admit(self, conn, ctx, payload):
921
+ target = self._target(conn, ctx, payload)
922
+ resource = self._check(conn, ctx, P.ADMIT, target)
923
+ if target["state"] != "waiting":
924
+ raise Invalid("That participant is not waiting.")
925
+ if resource["full"]:
926
+ raise Invalid("The meeting is full.")
927
+ ts = now_iso()
928
+ self._admit(conn, ctx["m"], target, ts)
929
+ audience = self._audience(conn, ctx["m"])
930
+ fresh = self._fresh(conn, target["id"])
931
+ return {}, [Event(frozenset({target["id"]}), {"t": "resync"}),
932
+ Event(audience["room"] - {target["id"]}, {"t": "joined", "participant": self.pub(fresh)}),
933
+ Event(audience["mods"], {"t": "waiting_done", "id": target["id"]})]
934
+
935
+ def _admit(self, conn, m, target, ts):
936
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(
937
+ state="admitted", **({"joined_at": ts, "muted_by_host": bool(m["mute_on_entry"])
938
+ and target["role"] == "attendee"} if target["joined_at"] is None else {})))
939
+ self._go_live(conn, m, ts)
940
+
941
+ def _act_admit_all(self, conn, ctx, payload):
942
+ self._check(conn, ctx, P.ADMIT)
943
+ ts = now_iso()
944
+ released = self._release_waiting(conn, ctx["m"], ts)
945
+ audience = self._audience(conn, ctx["m"])
946
+ events = [Event(frozenset({r}), {"t": "resync"}) for r in released]
947
+ events += [Event(audience["room"] - {r}, {"t": "joined", "participant": self.pub(self._fresh(conn, r))})
948
+ for r in released]
949
+ events.append(Event(audience["mods"], {"t": "waiting_done", "id": "*"}))
950
+ return {"admitted": len(released)}, events
951
+
952
+ def _act_deny(self, conn, ctx, payload):
953
+ target = self._target(conn, ctx, payload)
954
+ self._check(conn, ctx, P.DENY_ENTRY, target)
955
+ if target["state"] != "waiting":
956
+ raise Invalid("That participant is not waiting.")
957
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(state="denied"))
958
+ return {}, [Event(frozenset({target["id"]}), {"t": "denied"}),
959
+ Event(self._audience(conn, ctx["m"])["mods"], {"t": "waiting_done", "id": target["id"]})]
960
+
961
+ def _act_remove(self, conn, ctx, payload):
962
+ target = self._target(conn, ctx, payload)
963
+ self._check(conn, ctx, P.REMOVE, target)
964
+ audience = self._audience(conn, ctx["m"])
965
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(
966
+ state="removed", left_at=now_iso(), sfu_session_id=None, sfu_sub_session_id=None, tracks=None,
967
+ hand_raised=False, audio_on=False, video_on=False, screen_on=False))
968
+ return {}, [Event(frozenset({target["id"]}), {"t": "removed"}),
969
+ Event(audience["room"] - {target["id"]}, {"t": "left", "id": target["id"]})]
970
+
971
+ def _act_mute(self, conn, ctx, payload):
972
+ target = self._target(conn, ctx, payload)
973
+ self._check(conn, ctx, P.MUTE, target)
974
+ muted = bool(payload.get("muted", True))
975
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(
976
+ muted_by_host=muted, **({"audio_on": False} if muted else {})))
977
+ return {}, [Event(frozenset({target["id"]}), {"t": "mute", "muted": muted, "by": ctx["me"]["id"]}),
978
+ self._updated(conn, ctx, target["id"])]
979
+
980
+ def _act_mute_all(self, conn, ctx, payload):
981
+ self._check(conn, ctx, P.MUTE_ALL)
982
+ allow = bool(payload.get("allowUnmute", True))
983
+ m = ctx["m"]
984
+ conn.execute(update(mp).where(and_(mp.c.meeting_id == m["id"], mp.c.state == "admitted",
985
+ mp.c.role == "attendee")).values(muted_by_host=True, audio_on=False))
986
+ conn.execute(update(meeting).where(meeting.c.id == m["id"]).values(allow_unmute=allow, updated_at=now_iso()))
987
+ fresh = conn.execute(select(meeting).where(meeting.c.id == m["id"])).mappings().first()
988
+ audience = self._audience(conn, m)
989
+ return {}, [Event(audience["room"], {"t": "mute_all", "allowUnmute": allow}),
990
+ Event(audience["everyone"], {"t": "meeting", "meeting": self.ser_meeting(conn, fresh)})]
991
+
992
+ def _act_lower_hand(self, conn, ctx, payload):
993
+ target = self._target(conn, ctx, payload)
994
+ self._check(conn, ctx, P.LOWER_HAND, target)
995
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(hand_raised=False))
996
+ return {}, [self._updated(conn, ctx, target["id"])]
997
+
998
+ def _act_hand(self, conn, ctx, payload):
999
+ self._check(conn, ctx, P.HAND)
1000
+ conn.execute(update(mp).where(mp.c.id == ctx["me"]["id"]).values(hand_raised=bool(payload.get("raised", True))))
1001
+ return {}, [self._updated(conn, ctx, ctx["me"]["id"])]
1002
+
1003
+ def _act_react(self, conn, ctx, payload):
1004
+ self._check(conn, ctx, P.REACT)
1005
+ emoji = payload.get("emoji")
1006
+ if emoji not in EMOJI:
1007
+ raise Invalid("Unsupported reaction.")
1008
+ return {}, [Event(self._audience(conn, ctx["m"])["room"], {"t": "react", "from": ctx["me"]["id"], "emoji": emoji})]
1009
+
1010
+ def _act_chat(self, conn, ctx, payload):
1011
+ self._check(conn, ctx, P.CHAT)
1012
+ body = _clean_text(payload.get("body"), MAX_CHAT, "message", required=True)
1013
+ to = payload.get("to")
1014
+ audience = self._audience(conn, ctx["m"])
1015
+ recipients = audience["room"]
1016
+ if to:
1017
+ if to not in audience["room"]:
1018
+ raise Invalid("Recipient is not in the meeting.")
1019
+ recipients = frozenset({to, ctx["me"]["id"]})
1020
+ row = {"id": new_id(), "meeting_id": ctx["m"]["id"], "sender_id": ctx["me"]["id"], "recipient_id": to or None,
1021
+ "body": body, "created_at": now_iso()}
1022
+ conn.execute(meeting_chat.insert().values(**row))
1023
+ return {}, [Event(recipients, {"t": "chat", "message": self._chat(row)})]
1024
+
1025
+ def _act_promote(self, conn, ctx, payload):
1026
+ target = self._target(conn, ctx, payload)
1027
+ self._check(conn, ctx, P.PROMOTE, target)
1028
+ role = payload.get("role", "cohost")
1029
+ if role not in ("cohost", "attendee"):
1030
+ raise Invalid("role must be 'cohost' or 'attendee'.")
1031
+ if target["state"] != "admitted":
1032
+ raise Invalid("That participant is not in the meeting.")
1033
+ if role == "cohost" and target["kind"] != "member":
1034
+ raise Invalid("Only workspace members can be co-hosts.")
1035
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(role=role))
1036
+ return {}, [self._updated(conn, ctx, target["id"])]
1037
+
1038
+ def _act_transfer_host(self, conn, ctx, payload):
1039
+ target = self._target(conn, ctx, payload)
1040
+ self._check(conn, ctx, P.TRANSFER_HOST, target)
1041
+ if target["kind"] != "member" or target["state"] != "admitted":
1042
+ raise Invalid("The new host must be a workspace member in the meeting.")
1043
+ conn.execute(update(mp).where(mp.c.id == target["id"]).values(role="host"))
1044
+ conn.execute(update(mp).where(mp.c.id == ctx["me"]["id"]).values(role="cohost"))
1045
+ conn.execute(update(meeting).where(meeting.c.id == ctx["m"]["id"]).values(
1046
+ host_id=target["user_id"], updated_at=now_iso()))
1047
+ fresh = conn.execute(select(meeting).where(meeting.c.id == ctx["m"]["id"])).mappings().first()
1048
+ audience = self._audience(conn, ctx["m"])
1049
+ return {}, [self._updated(conn, ctx, target["id"]), self._updated(conn, ctx, ctx["me"]["id"]),
1050
+ Event(audience["everyone"], {"t": "meeting", "meeting": self.ser_meeting(conn, fresh)})]
1051
+
1052
+ def _act_settings(self, conn, ctx, payload):
1053
+ self._check(conn, ctx, P.SETTINGS)
1054
+ unknown = set(payload) - set(SETTING_FIELDS)
1055
+ if unknown:
1056
+ raise Invalid(f"Unknown settings: {', '.join(sorted(unknown))}.")
1057
+ values = self._clean_fields(conn, ctx["principal"], payload)
1058
+ if values:
1059
+ conn.execute(update(meeting).where(meeting.c.id == ctx["m"]["id"]).values(
1060
+ updated_at=now_iso(), **values))
1061
+ fresh = conn.execute(select(meeting).where(meeting.c.id == ctx["m"]["id"])).mappings().first()
1062
+ return {}, [Event(self._audience(conn, ctx["m"])["everyone"],
1063
+ {"t": "meeting", "meeting": self.ser_meeting(conn, fresh)})]
1064
+
1065
+ def _act_lock(self, conn, ctx, payload):
1066
+ return self._act_settings(conn, ctx, {"locked": bool(payload.get("locked", True))})
1067
+
1068
+ def _act_record(self, conn, ctx, payload):
1069
+ self._check(conn, ctx, P.RECORD)
1070
+ state = "recording" if payload.get("state") == "start" else "allowed"
1071
+ conn.execute(update(meeting).where(meeting.c.id == ctx["m"]["id"]).values(recording=state, updated_at=now_iso()))
1072
+ return {}, [Event(self._audience(conn, ctx["m"])["room"],
1073
+ {"t": "recording", "state": state, "by": ctx["me"]["display_name"]})]
1074
+
1075
+ def _act_media(self, conn, ctx, payload):
1076
+ """Tell the room what my mic/camera/screen are doing (drives the tiles' mute and camera-off icons)."""
1077
+ self._check(conn, ctx, P.MEDIA_STATE)
1078
+ values = {}
1079
+ for key, col in (("audio", "audio_on"), ("video", "video_on"), ("screen", "screen_on")):
1080
+ if key in payload:
1081
+ values[col] = bool(payload[key])
1082
+ if values.get("audio_on") and ctx["subject"].get("forced_mute"):
1083
+ raise Invalid("The host muted you and disabled unmuting.")
1084
+ if values:
1085
+ conn.execute(update(mp).where(mp.c.id == ctx["me"]["id"]).values(**values))
1086
+ return {}, [self._updated(conn, ctx, ctx["me"]["id"])]
1087
+
1088
+ def _act_end(self, conn, ctx, payload):
1089
+ self._check(conn, ctx, P.END)
1090
+ return {}, self._finish(conn, ctx["m"], "ended")
1091
+
1092
+ def _act_leave(self, conn, ctx, payload):
1093
+ me = ctx["me"]
1094
+ if me is None or me["state"] not in ("waiting", "admitted"):
1095
+ return {}, []
1096
+ return {}, self._leave(conn, ctx["m"], me)
1097
+
1098
+ # ------------------------------------------------------------------ notifications
1099
+ def _summary(self, conn, m) -> dict:
1100
+ return self.ser_meeting(conn, m, detail=False)
1101
+
1102
+ def _name_of(self, conn, user_id) -> str | None:
1103
+ row = conn.execute(select(user.c.display_name, user.c.name).where(user.c.id == user_id)).mappings().first()
1104
+ return (row or {}).get("display_name") or (row or {}).get("name")
1105
+
1106
+ def _invited_notices(self, conn, m, inviter_id, user_ids: list[str]) -> list:
1107
+ if not user_ids:
1108
+ return []
1109
+ return [Notice(frozenset(user_ids), {"t": "invited", "meeting": self._summary(conn, m),
1110
+ "by": self._name_of(conn, inviter_id)})]
1111
+
1112
+ def _invitee_user_ids(self, conn, m, exclude=()) -> frozenset:
1113
+ rows = conn.execute(select(meeting_invitee.c.user_id).where(and_(
1114
+ meeting_invitee.c.meeting_id == m["id"], meeting_invitee.c.user_id.is_not(None),
1115
+ meeting_invitee.c.response != "declined"))).all()
1116
+ return frozenset(r[0] for r in rows) - set(exclude)
1117
+
1118
+ def _notice_invitees(self, conn, m, msg: dict, exclude=()) -> Notice:
1119
+ return Notice(self._invitee_user_ids(conn, m, exclude), msg)
1120
+
1121
+ def rsvp(self, code: str, principal: Principal, response: str) -> list:
1122
+ if response not in RSVP_VALUES:
1123
+ raise Invalid(f"response must be one of {', '.join(RSVP_VALUES)}.")
1124
+ with self.engine.begin() as conn:
1125
+ m = self._meeting(conn, code)
1126
+ subject = self._subject(conn, m, principal, self._me(conn, m, principal))
1127
+ self._require(P.RSVP, subject, self._resource(conn, m))
1128
+ email = conn.execute(select(user.c.email).where(user.c.id == principal.user_id)).scalar()
1129
+ conn.execute(update(meeting_invitee).where(and_(meeting_invitee.c.meeting_id == m["id"], or_(
1130
+ meeting_invitee.c.user_id == principal.user_id,
1131
+ *([func.lower(meeting_invitee.c.email) == email.lower()] if email else [])))).values(
1132
+ response=response, user_id=principal.user_id))
1133
+ return [Notice(frozenset({m["host_id"]}), {
1134
+ "t": "rsvp", "code": m["code"], "title": m["title"], "response": response,
1135
+ "by": self._name_of(conn, principal.user_id)})]
1136
+
1137
+ def ring(self, code: str, principal: Principal, user_ids: list) -> tuple[list[dict], list]:
1138
+ """Call people: invite them if needed and ring them for RING_SECONDS."""
1139
+ if not isinstance(user_ids, list) or not 0 < len(user_ids) <= 50:
1140
+ raise Invalid("userIds must list 1-50 workspace members.")
1141
+ with self.engine.begin() as conn:
1142
+ m = self._meeting(conn, code)
1143
+ subject = self._subject(conn, m, principal, self._me(conn, m, principal))
1144
+ resource = self._resource(conn, m)
1145
+ self._require(P.INVITE, subject, resource)
1146
+ if m["status"] not in ("scheduled", "live"):
1147
+ raise Invalid("This meeting is over.")
1148
+ if principal.kind != "member":
1149
+ raise Denied(Decision(False, "Only members can place calls."))
1150
+ targets = [r[0] for r in conn.execute(select(user.c.id).where(and_(
1151
+ user.c.organization_id == m["organization_id"], user.c.active.is_not(False),
1152
+ user.c.id.in_([str(u) for u in user_ids]), user.c.id != principal.user_id)))]
1153
+ if not targets:
1154
+ raise Invalid("No one to call.")
1155
+ self._add_invitees(conn, m, principal.user_id, targets, "attendee")
1156
+ now = datetime.now(timezone.utc)
1157
+ conn.execute(update(meeting_ring).where(and_(
1158
+ meeting_ring.c.meeting_id == m["id"], meeting_ring.c.to_id.in_(targets),
1159
+ meeting_ring.c.state == "ringing")).values(state="cancelled", responded_at=now.isoformat()))
1160
+ caller = {"id": principal.user_id, "name": self._name_of(conn, principal.user_id)}
1161
+ summary = self._summary(conn, m)
1162
+ rings, notices = [], []
1163
+ for uid in targets:
1164
+ row = {"id": new_id(), "meeting_id": m["id"], "organization_id": m["organization_id"],
1165
+ "from_id": principal.user_id, "to_id": uid, "state": "ringing",
1166
+ "created_at": now.isoformat(), "expires_at": (now + timedelta(seconds=RING_SECONDS)).isoformat()}
1167
+ conn.execute(meeting_ring.insert().values(**row))
1168
+ rings.append({"id": row["id"], "userId": uid, "expiresAt": row["expires_at"]})
1169
+ notices.append(Notice(frozenset({uid}), {"t": "ring", "ring": {
1170
+ "id": row["id"], "from": caller, "meeting": summary, "expiresAt": row["expires_at"]}}))
1171
+ return rings, notices
1172
+
1173
+ def respond_ring(self, ring_id: str, principal: Principal, answer: str) -> tuple[dict, list]:
1174
+ if answer not in ("accept", "decline"):
1175
+ raise Invalid("answer must be 'accept' or 'decline'.")
1176
+ if principal.kind != "member":
1177
+ raise Denied(Decision(False, "Sign in to answer calls."))
1178
+ with self.engine.begin() as conn:
1179
+ r = conn.execute(select(meeting_ring).where(and_(
1180
+ meeting_ring.c.id == ring_id, meeting_ring.c.to_id == principal.user_id,
1181
+ meeting_ring.c.organization_id == principal.org_id))).mappings().first()
1182
+ if r is None:
1183
+ raise NotFound("Call not found.")
1184
+ m = conn.execute(select(meeting).where(meeting.c.id == r["meeting_id"])).mappings().first()
1185
+ if r["state"] != "ringing" or r["expires_at"] <= datetime.now(timezone.utc).isoformat() \
1186
+ or m["status"] not in ("scheduled", "live"):
1187
+ raise Invalid("This call has ended.")
1188
+ state = "accepted" if answer == "accept" else "declined"
1189
+ conn.execute(update(meeting_ring).where(meeting_ring.c.id == ring_id).values(
1190
+ state=state, responded_at=now_iso()))
1191
+ if answer == "accept":
1192
+ conn.execute(update(meeting_invitee).where(and_(
1193
+ meeting_invitee.c.meeting_id == m["id"], meeting_invitee.c.user_id == principal.user_id)
1194
+ ).values(response="accepted"))
1195
+ notices = [Notice(frozenset({r["from_id"]}), {
1196
+ "t": "ring_answered", "id": ring_id, "answer": answer, "code": m["code"],
1197
+ "by": self._name_of(conn, principal.user_id)}),
1198
+ Notice(frozenset({principal.user_id}), {"t": "ring_ended", "id": ring_id, "reason": state})]
1199
+ return {"code": m["code"], "answer": answer}, notices
1200
+
1201
+ def expire_ring(self, ring_id: str) -> list:
1202
+ with self.engine.begin() as conn:
1203
+ r = conn.execute(select(meeting_ring).where(meeting_ring.c.id == ring_id)).mappings().first()
1204
+ if r is None or r["state"] != "ringing":
1205
+ return []
1206
+ conn.execute(update(meeting_ring).where(meeting_ring.c.id == ring_id).values(
1207
+ state="missed", responded_at=now_iso()))
1208
+ m = conn.execute(select(meeting).where(meeting.c.id == r["meeting_id"])).mappings().first()
1209
+ return [Notice(frozenset({r["to_id"]}), {"t": "ring_ended", "id": ring_id, "reason": "missed"}),
1210
+ Notice(frozenset({r["from_id"]}), {"t": "ring_answered", "id": ring_id, "answer": "missed",
1211
+ "code": m["code"], "by": self._name_of(conn, r["to_id"])})]
1212
+
1213
+ def _end_rings(self, conn, m, reason: str) -> list:
1214
+ rows = conn.execute(select(meeting_ring.c.id, meeting_ring.c.to_id).where(and_(
1215
+ meeting_ring.c.meeting_id == m["id"], meeting_ring.c.state == "ringing"))).all()
1216
+ if not rows:
1217
+ return []
1218
+ conn.execute(update(meeting_ring).where(and_(
1219
+ meeting_ring.c.meeting_id == m["id"], meeting_ring.c.state == "ringing")).values(
1220
+ state=reason, responded_at=now_iso()))
1221
+ return [Notice(frozenset({to}), {"t": "ring_ended", "id": rid, "reason": reason}) for rid, to in rows]
1222
+
1223
+ def pending_rings(self, principal: Principal) -> list[dict]:
1224
+ """Calls still ringing for me (sent on inbox connect so a reload does not lose them)."""
1225
+ if principal.kind != "member":
1226
+ return []
1227
+ with self.engine.connect() as conn:
1228
+ now = datetime.now(timezone.utc).isoformat()
1229
+ rows = conn.execute(select(meeting_ring, meeting).select_from(
1230
+ meeting_ring.join(meeting, meeting.c.id == meeting_ring.c.meeting_id)).where(and_(
1231
+ meeting_ring.c.to_id == principal.user_id, meeting_ring.c.state == "ringing",
1232
+ meeting_ring.c.expires_at > now, meeting.c.status.in_(("scheduled", "live"))))).mappings().all()
1233
+ return [{"id": r["id"], "from": {"id": r["from_id"], "name": self._name_of(conn, r["from_id"])},
1234
+ "meeting": self._summary(conn, r), "expiresAt": r["expires_at"]} for r in rows]
1235
+
1236
+ def due_reminders(self, now: datetime | None = None) -> list:
1237
+ """'Starting soon' notices, once per meeting, for the host and everyone who has not declined."""
1238
+ now = now or datetime.now(timezone.utc)
1239
+ horizon = (now + timedelta(minutes=REMINDER_MINUTES)).isoformat()
1240
+ with self.engine.begin() as conn:
1241
+ rows = conn.execute(select(meeting).where(and_(
1242
+ meeting.c.status == "scheduled", meeting.c.reminded_at.is_(None),
1243
+ meeting.c.scheduled_start.is_not(None), meeting.c.scheduled_start <= horizon,
1244
+ meeting.c.scheduled_start >= (now - timedelta(minutes=2)).isoformat()))).mappings().all()
1245
+ notices = []
1246
+ for m in rows:
1247
+ conn.execute(update(meeting).where(meeting.c.id == m["id"]).values(reminded_at=now.isoformat()))
1248
+ start = datetime.fromisoformat(m["scheduled_start"])
1249
+ minutes = max(0, round((start - now).total_seconds() / 60))
1250
+ notices.append(Notice(frozenset({m["host_id"]}) | self._invitee_user_ids(conn, m), {
1251
+ "t": "starting_soon", "minutes": minutes, "meeting": self._summary(conn, m)}))
1252
+ return notices
1253
+
1254
+ def usage(self, code: str, principal: Principal, bytes_in: int, bytes_out: int) -> None:
1255
+ """Cumulative byte counters from the browser's getStats(); used to report what a meeting cost."""
1256
+ for value in (bytes_in, bytes_out):
1257
+ if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 10**13:
1258
+ raise Invalid("Byte counters must be integers.")
1259
+ with self.engine.begin() as conn:
1260
+ m = self._meeting(conn, code)
1261
+ me = self._me(conn, m, principal)
1262
+ self._require(P.USAGE, self._subject(conn, m, principal, me), self._resource(conn, m))
1263
+ conn.execute(update(mp).where(mp.c.id == me["id"]).values(
1264
+ bytes_in=max(me["bytes_in"] or 0, bytes_in), bytes_out=max(me["bytes_out"] or 0, bytes_out)))
1265
+
1266
+ def ics(self, code: str, principal: Principal, base_url: str) -> str:
1267
+ with self.engine.connect() as conn:
1268
+ m = self._meeting(conn, code)
1269
+ me = self._me(conn, m, principal)
1270
+ self._require(P.VIEW, self._subject(conn, m, principal, me), self._resource(conn, m))
1271
+ host = conn.execute(select(user.c.name, user.c.display_name, user.c.email).where(
1272
+ user.c.id == m["host_id"])).mappings().first() or {}
1273
+ start = datetime.fromisoformat(m["scheduled_start"] or m["created_at"]).astimezone(timezone.utc)
1274
+ end = start + timedelta(minutes=m["duration_minutes"] or 60)
1275
+ fmt = "%Y%m%dT%H%M%SZ"
1276
+ url = f"{base_url.rstrip('/')}/meet/{m['code']}"
1277
+ lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Hoja//Meetings//EN", "CALSCALE:GREGORIAN",
1278
+ "METHOD:PUBLISH", "BEGIN:VEVENT", f"UID:{m['id']}@hoja", f"DTSTAMP:{datetime.now(timezone.utc).strftime(fmt)}",
1279
+ f"DTSTART:{start.strftime(fmt)}", f"DTEND:{end.strftime(fmt)}",
1280
+ f"SUMMARY:{_ics_text(m['title'])}",
1281
+ f"DESCRIPTION:{_ics_text((m['description'] or '') + chr(10) + 'Join: ' + url)}",
1282
+ f"LOCATION:{_ics_text(url)}", f"URL:{url}",
1283
+ f"STATUS:{'CANCELLED' if m['status'] == 'cancelled' else 'CONFIRMED'}"]
1284
+ if host.get("email"):
1285
+ lines.append(f"ORGANIZER;CN={_ics_text(host.get('display_name') or host.get('name') or 'Host')}:"
1286
+ f"mailto:{host['email']}")
1287
+ for inv in self._invitees(conn, m):
1288
+ if inv["email"]:
1289
+ lines.append(f"ATTENDEE;CN={_ics_text(inv['name'] or inv['email'])}:mailto:{inv['email']}")
1290
+ lines += ["END:VEVENT", "END:VCALENDAR"]
1291
+ return "\r\n".join(_ics_fold(line) for line in lines) + "\r\n"
1292
+
1293
+ # ------------------------------------------------------------------ SFU bookkeeping
1294
+ def media_context(self, code: str, principal: Principal, action: str = P.SUBSCRIBE) -> dict:
1295
+ with self.engine.connect() as conn:
1296
+ m = self._meeting(conn, code)
1297
+ me = self._me(conn, m, principal)
1298
+ subject = self._subject(conn, m, principal, me)
1299
+ self._require(action, subject, self._resource(conn, m))
1300
+ return {"meeting_id": m["id"], "participant": dict(me), "subject": subject,
1301
+ "resource": self._resource(conn, m)}
1302
+
1303
+ def authorize_media(self, code: str, principal: Principal, action: str) -> None:
1304
+ self.media_context(code, principal, action)
1305
+
1306
+ def set_session(self, participant_id: str, session_id: str, role: str = "pub") -> None:
1307
+ """role 'pub' = the peer connection that sends my tracks, 'sub' = the one that receives others'."""
1308
+ column = "sfu_session_id" if role == "pub" else "sfu_sub_session_id"
1309
+ with self.engine.begin() as conn:
1310
+ conn.execute(update(mp).where(mp.c.id == participant_id).values(**{column: session_id}))
1311
+
1312
+ def remote_track_ok(self, meeting_id: str, session_id: str, track_name: str) -> bool:
1313
+ with self.engine.connect() as conn:
1314
+ row = conn.execute(select(mp.c.tracks).where(and_(
1315
+ mp.c.meeting_id == meeting_id, mp.c.state == "admitted", mp.c.sfu_session_id == session_id))).first()
1316
+ return bool(row) and any(t.get("name") == track_name for t in json.loads(row[0] or "[]"))
1317
+
1318
+ def change_tracks(self, participant_id: str, add: list[dict] | None = None,
1319
+ remove: list[str] | None = None) -> list[Event]:
1320
+ with self.engine.begin() as conn:
1321
+ p = self._fresh(conn, participant_id)
1322
+ if p is None or p["state"] != "admitted":
1323
+ return []
1324
+ tracks = {t["name"]: t for t in json.loads(p["tracks"] or "[]")}
1325
+ for t in add or []:
1326
+ tracks[t["name"]] = t
1327
+ for name in remove or []:
1328
+ tracks.pop(name, None)
1329
+ conn.execute(update(mp).where(mp.c.id == participant_id).values(tracks=json.dumps(list(tracks.values()))))
1330
+ m = conn.execute(select(meeting).where(meeting.c.id == p["meeting_id"])).mappings().first()
1331
+ return [Event(self._audience(conn, m)["room"],
1332
+ {"t": "participant", "participant": self.pub(self._fresh(conn, participant_id))})]