appsocom 0.7.0__tar.gz → 0.8.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appsocom
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
5
5
  Author: Appsotech Limited
6
6
  License-Expression: MIT
@@ -86,7 +86,33 @@ def assistant_tools_route():
86
86
 
87
87
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
88
88
 
89
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
89
+ ## AI Tasks, Speech and Videos
90
+
91
+ ```python
92
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
93
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
94
+ marked["json"]["score"], marked["usage"]["credits"]
95
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
96
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
97
+ with kit.ai_stream("Tell a short story.") as story:
98
+ for piece in story:
99
+ print(piece, end="")
100
+ story.usage # model, tokens, cost, credits
101
+
102
+ # Speech
103
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
104
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
105
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
106
+
107
+ # Videos: an upload link for a browser, or send a file from your server
108
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
109
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
110
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
111
+ ```
112
+
113
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
114
+
115
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
90
116
 
91
117
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
92
118
 
@@ -67,7 +67,33 @@ def assistant_tools_route():
67
67
 
68
68
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
69
69
 
70
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
70
+ ## AI Tasks, Speech and Videos
71
+
72
+ ```python
73
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
74
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
75
+ marked["json"]["score"], marked["usage"]["credits"]
76
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
77
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
78
+ with kit.ai_stream("Tell a short story.") as story:
79
+ for piece in story:
80
+ print(piece, end="")
81
+ story.usage # model, tokens, cost, credits
82
+
83
+ # Speech
84
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
85
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
86
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
87
+
88
+ # Videos: an upload link for a browser, or send a file from your server
89
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
90
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
91
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
92
+ ```
93
+
94
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
95
+
96
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
71
97
 
72
98
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
73
99
 
@@ -21,6 +21,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
21
21
  __all__ = [
22
22
  "SfuKit",
23
23
  "SfuKitError",
24
+ "AiStream",
24
25
  "sign_token",
25
26
  "verify_webhook",
26
27
  "sign_webhook",
@@ -30,7 +31,7 @@ __all__ = [
30
31
  "assistant_tools",
31
32
  "verify_assistant_tool_call",
32
33
  ]
33
- __version__ = "0.7.0"
34
+ __version__ = "0.8.0"
34
35
 
35
36
  SIGNATURE_HEADER = "X-SfuKit-Signature"
36
37
  _ID = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
@@ -67,6 +68,76 @@ def _json(value: Any) -> str:
67
68
  return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
68
69
 
69
70
 
71
+ def _http_error(what: str, e: urllib.error.HTTPError) -> "SfuKitError":
72
+ text = e.read().decode("utf-8", "replace")
73
+ try:
74
+ parsed: Any = json.loads(text)
75
+ except ValueError:
76
+ parsed = text
77
+ msg = parsed.get("error", text) if isinstance(parsed, dict) else text
78
+ return SfuKitError(e.code, f"sfukit {what}: {e.code} {msg}", parsed)
79
+
80
+
81
+ def _body(options: Dict[str, Any], names: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
82
+ """Keyword options as a request body: names mapped to the API's camelCase, None left out."""
83
+ return {(names or {}).get(k, k): v for k, v in options.items() if v is not None}
84
+
85
+
86
+ # snake_case options of the AI Tasks, Speech and Videos helpers, as the API spells them.
87
+ _NAMES = {
88
+ "max_tokens": "maxTokens",
89
+ "expires_in": "expiresIn",
90
+ "max_duration_seconds": "maxDurationSeconds",
91
+ "upload_length": "uploadLength",
92
+ "expires_in_seconds": "expiresInSeconds",
93
+ }
94
+
95
+
96
+ class AiStream:
97
+ """One streamed AI Tasks answer (from `SfuKit.ai_stream`).
98
+
99
+ Iterate it for the text as it is written; `usage` holds the call's usage (model, tokens,
100
+ cost, credits) once the stream has ended. Use it in a `with` block, or call `close()`, if
101
+ you stop reading early.
102
+ """
103
+
104
+ def __init__(self, response: Any):
105
+ self._res = response
106
+ self.usage: Optional[Dict[str, Any]] = None
107
+
108
+ def __iter__(self):
109
+ event = data = None
110
+ try:
111
+ for raw in self._res:
112
+ line = raw.decode("utf-8").rstrip("\r\n")
113
+ if line == "":
114
+ if event is not None and data is not None:
115
+ d = json.loads(data)
116
+ if event == "text" and d.get("text"):
117
+ yield d["text"]
118
+ elif event == "error":
119
+ raise SfuKitError(502, f"sfukit POST /ai/complete: {d.get('error') or 'stream failed'}", d)
120
+ elif event == "done":
121
+ self.usage = d.get("usage")
122
+ return
123
+ event = data = None
124
+ elif line.startswith("event: "):
125
+ event = line[7:]
126
+ elif line.startswith("data: ") and data is None:
127
+ data = line[6:]
128
+ finally:
129
+ self.close()
130
+
131
+ def close(self) -> None:
132
+ self._res.close()
133
+
134
+ def __enter__(self) -> "AiStream":
135
+ return self
136
+
137
+ def __exit__(self, *exc: Any) -> None:
138
+ self.close()
139
+
140
+
70
141
  class SfuKit:
71
142
  """Admin client for one sfukit deployment.
72
143
 
@@ -488,7 +559,8 @@ class SfuKit:
488
559
  options: name, role, conversation_id, tools (names), paths, tier, retention_days,
489
560
  monthly_messages (this person's messages per month), metadata (dict of strings, passed back with every tool call),
490
561
  context (what your app knows about this person that the assistant should always have, at most 3,000 characters),
491
- report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers), ttl_seconds (default 3600, max 43200).
562
+ report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers),
563
+ knowledge (a knowledge base collection to answer from, for an app that keeps each customer's knowledge apart), ttl_seconds (default 3600, max 43200).
492
564
  """
493
565
  body: Dict[str, Any] = {"userId": user_id}
494
566
  names = {"conversation_id": "conversationId", "retention_days": "retentionDays", "monthly_messages": "monthlyMessages", "report_usage": "reportUsage", "ttl_seconds": "ttlSeconds"}
@@ -501,14 +573,214 @@ class SfuKit:
501
573
  """Forget one person's conversation (its memory and transcript)."""
502
574
  self.request("DELETE", f"/assistant/conversations/{_id(user_id)}/{_id(conversation_id)}")
503
575
 
576
+ # ---------- AI Tasks (/ai/*; called AI Text in code) ----------
577
+
578
+ #: Seconds AI Tasks calls may take (they write whole answers); longer than `timeout`.
579
+ AI_TIMEOUT = 300.0
580
+
581
+ def ai_complete(self, prompt: Optional[str] = None, **options: Any) -> Dict[str, Any]:
582
+ """One Claude call with your own prompt: `prompt`, or `system` and `messages`.
583
+
584
+ options: system, messages ([{"role": "user" | "assistant", "content": …}]), json (True for any
585
+ JSON object, or a JSON Schema dict for an answer that keeps to it), tier ("standard", "smart",
586
+ "best"), max_tokens (default 4000, at most 32000), user (your id for the person this is for:
587
+ per-person monthly allowance, audit), label (your own label, shown in usage and audit).
588
+ Returns {"task", "tier", "text", "json"?, "error"?, "stopReason", "usage": {…, "credits"}}.
589
+ """
590
+ body = {"prompt": prompt, **options}
591
+ return self.request("POST", "/ai/complete", {**_body(body, _NAMES), "stream": False}, timeout=max(self.timeout, self.AI_TIMEOUT))
592
+
593
+ def ai_task(self, task: str, input: Dict[str, Any], **options: Any) -> Dict[str, Any]:
594
+ """A ready-made task: "write", "mark", "questions", "summary", "moderate" or "extract"
595
+ (see the AI Tasks docs for each input). options: tier, max_tokens, user, label."""
596
+ return self.request("POST", "/ai/complete", {**_body(options, _NAMES), "task": task, "input": input}, timeout=max(self.timeout, self.AI_TIMEOUT))
597
+
598
+ def ai_stream(self, prompt: Optional[str] = None, **options: Any) -> AiStream:
599
+ """Your own prompt, streamed: iterate the result for the text as it is written, then read
600
+ its `usage`. Takes the options of ai_complete except json. Raises SfuKitError at once when
601
+ the kit refuses the call (for example 429 at the daily limit)."""
602
+ body = _body({"prompt": prompt, **options}, _NAMES)
603
+ req = urllib.request.Request(
604
+ self.url + "/ai/complete",
605
+ data=_json({**body, "stream": True}).encode("utf-8"),
606
+ headers={**self._headers(), "Content-Type": "application/json"},
607
+ method="POST",
608
+ )
609
+ try:
610
+ return AiStream(urllib.request.urlopen(req, timeout=max(self.timeout, self.AI_TIMEOUT)))
611
+ except urllib.error.HTTPError as e:
612
+ raise _http_error("POST /ai/complete", e) from None
613
+
614
+ def get_ai_settings(self) -> Dict[str, Any]:
615
+ """{"settings": {…}, "dailyCapUsd": n}."""
616
+ return self.request("GET", "/ai/settings")
617
+
618
+ def set_ai_settings(self, settings: Dict[str, Any]) -> Dict[str, Any]:
619
+ """Replace AI Tasks' settings (the API's own keys): dailyBudgetUsd, userMonthlyUsd, tiers,
620
+ defaultTier, audit."""
621
+ return self.request("PUT", "/ai/settings", settings)
622
+
623
+ def get_ai_usage(self, days: int = 7) -> Dict[str, Any]:
624
+ """Spending (today against the cap, per day) and calls by task and model over `days` (1-90)."""
625
+ return self.request("GET", f"/ai/usage?days={int(days)}")
626
+
627
+ def get_ai_audit(self, day: Optional[str] = None, user: Optional[str] = None) -> Dict[str, Any]:
628
+ """One UTC day's calls (never their text), optionally one person's: {"day", "events", "truncated"}."""
629
+ q = {k: v for k, v in (("day", day), ("user", user)) if v}
630
+ return self.request("GET", "/ai/audit" + (f"?{urllib.parse.urlencode(q)}" if q else ""))
631
+
632
+ # ---------- Speech (/speech/tts, /speech/stt) ----------
633
+
634
+ def text_to_speech(self, text: str, **options: Any) -> bytes:
635
+ """Speak `text` (up to 5,000 characters): the audio file's bytes (mp3 unless format="wav").
636
+ Repeats of the same text come from the cache, free.
637
+
638
+ options: language (default "en"; Yoruba "yo", Hausa "ha" and Igbo "ig" use Spitch or ElevenLabs),
639
+ voice, provider ("cartesia", "elevenlabs", "spitch", "openai", "deepgram"), format ("mp3" or "wav"),
640
+ speed (0.5 to 2), model, cache (False: always made fresh, always billed).
641
+ """
642
+ return self.request("POST", "/speech/tts", {**_body({"text": text, **options}, _NAMES), "response": "audio"}, raw=bytes)
643
+
644
+ def text_to_speech_url(self, text: str, **options: Any) -> Dict[str, Any]:
645
+ """Speak `text` and get a signed link that plays without your key until it expires.
646
+ Takes the options of text_to_speech except cache, and expires_in (60 seconds to 7 days, default 3600).
647
+ Returns {"url", "expiresAt", "cached", "characters", "provider", "voice", "format"}."""
648
+ return self.request("POST", "/speech/tts", {**_body({"text": text, **options}, _NAMES), "response": "url"})
649
+
650
+ def speech_to_text(
651
+ self,
652
+ audio: Union[bytes, bytearray, memoryview],
653
+ content_type: str = "application/octet-stream",
654
+ language: Optional[str] = None,
655
+ provider: Optional[str] = None,
656
+ model: Optional[str] = None,
657
+ timeout: float = 120.0,
658
+ ) -> Dict[str, Any]:
659
+ """Transcribe a recording (up to 25 MB): {"text", "language"?, "seconds", "provider", "words"?}.
660
+
661
+ content_type: e.g. "audio/webm", "audio/wav", "audio/mpeg". language: unset = detected (Deepgram,
662
+ ElevenLabs). provider: "deepgram", "elevenlabs" or "spitch". model: a Deepgram model (default nova-3).
663
+ """
664
+ if not isinstance(audio, (bytes, bytearray, memoryview)):
665
+ raise SfuKitError(400, "audio must be bytes")
666
+ q = {k: v for k, v in (("language", language), ("provider", provider), ("model", model)) if v}
667
+ path = "/speech/stt" + (f"?{urllib.parse.urlencode(q)}" if q else "")
668
+ return self.request("POST", path, _encoded=(bytes(audio), content_type), timeout=timeout)
669
+
670
+ def get_speech_usage(self) -> Dict[str, Any]:
671
+ """Spending per day (US dollars) and today's cap: {"today": {…}, "days": […]}."""
672
+ return self.request("GET", "/speech/usage")
673
+
674
+ def set_speech_daily_budget(self, daily_budget_usd: Optional[float]) -> Dict[str, Any]:
675
+ """The project's own daily speech cap in US dollars (None = the server's default)."""
676
+ return self.request("PUT", "/speech/config", {"dailyBudgetUsd": daily_budget_usd})
677
+
678
+ # ---------- Videos (video on demand on R2) ----------
679
+
680
+ #: Seconds a video upload may take (a whole file, or one part of it); longer than `timeout`.
681
+ UPLOAD_TIMEOUT = 600.0
682
+
683
+ def create_video_upload(
684
+ self,
685
+ max_duration_seconds: int,
686
+ name: Optional[str] = None,
687
+ meta: Optional[Dict[str, str]] = None,
688
+ upload_length: Optional[int] = None,
689
+ ) -> Dict[str, Any]:
690
+ """An upload link for one video: give `uploadUrl` to the browser (it PUTs the file straight to it,
691
+ or its parts when `protocol` is "parts"), or send a file from your server with upload_video_file.
692
+
693
+ max_duration_seconds: the longest the video may be (longer ones are refused when converted).
694
+ meta: up to 10 string pairs of your own. upload_length: the file's size in bytes; required over 95 MB (up to 5 GB).
695
+ Returns {"videoId", "uploadUrl", "protocol": "put" | "parts", "partSize"?, "parts"?, "expiresAt"}.
696
+ """
697
+ return self.request(
698
+ "POST",
699
+ "/videos/uploads",
700
+ _body({"max_duration_seconds": max_duration_seconds, "name": name, "meta": meta, "upload_length": upload_length}, _NAMES),
701
+ )
702
+
703
+ def upload_video_file(self, upload: Dict[str, Any], file: Any) -> Dict[str, Any]:
704
+ """Send a file from your server to an upload link (both protocols): one PUT, or each part in turn
705
+ and then the finishing POST. `file` is bytes, or a binary file object (read in parts for big files).
706
+ Returns the video."""
707
+ url = upload["uploadUrl"]
708
+ timeout = max(self.timeout, self.UPLOAD_TIMEOUT)
709
+ if upload.get("protocol") == "put":
710
+ return self._upload(url, "PUT", file if isinstance(file, (bytes, bytearray, memoryview)) else file.read(), None, timeout)
711
+ size = upload.get("partSize") or 50 * 1024 * 1024
712
+ sep = "&" if "?" in url else "?"
713
+ parts = []
714
+ n = 1
715
+ for chunk in _slices(file, size):
716
+ parts.append(self._upload(f"{url}{sep}part={n}", "PUT", chunk, None, timeout))
717
+ n += 1
718
+ return self._upload(f"{url}{sep}complete", "POST", _json({"parts": parts}).encode("utf-8"), "application/json", timeout)
719
+
720
+ def copy_video(self, url: str, **options: Any) -> Dict[str, Any]:
721
+ """Bring in a video from a public https link (moving an existing library over).
722
+ options: name, meta, max_duration_seconds."""
723
+ return self.request("POST", "/videos/copy", {"url": url, **_body(options, _NAMES)})
724
+
725
+ def list_videos(self, after: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
726
+ """Your videos, newest first: {"videos": […], "next": …}. Pass `next` from the last page as `after`."""
727
+ q = {k: v for k, v in (("after", after), ("limit", limit)) if v is not None and v != ""}
728
+ return self.request("GET", "/videos" + (f"?{urllib.parse.urlencode(q)}" if q else ""))
729
+
730
+ def get_video(self, video_id: str) -> Dict[str, Any]:
731
+ return self.request("GET", f"/videos/{_id(video_id)}")
732
+
733
+ def update_video(self, video_id: str, **update: Any) -> Dict[str, Any]:
734
+ """Rename (name=), or replace your meta (meta=)."""
735
+ return self.request("PATCH", f"/videos/{_id(video_id)}", update)
736
+
737
+ def delete_video(self, video_id: str) -> None:
738
+ """Delete the video and its files for good."""
739
+ self.request("DELETE", f"/videos/{_id(video_id)}")
740
+
741
+ def video_playback(self, video_id: str, expires_in_seconds: Optional[int] = None) -> Dict[str, Any]:
742
+ """Signed links for one viewer: {"hls", "iframe", "thumbnail", "expiresAt"}. Make one per viewing; they expire."""
743
+ return self.request("POST", f"/videos/{_id(video_id)}/playback", _body({"expires_in_seconds": expires_in_seconds}, _NAMES))
744
+
745
+ def get_video_usage(self) -> Dict[str, Any]:
746
+ """Bytes kept, this month's meters and your caps."""
747
+ return self.request("GET", "/videos/usage")
748
+
504
749
  def health(self) -> Dict[str, Any]:
505
750
  return self.request("GET", "/health")
506
751
 
507
752
  # ---------- plumbing ----------
508
753
 
509
- def request(self, method: str, path: str, body: Any = None, raw: Any = False, _encoded: Optional[tuple] = None) -> Any:
510
- """Call any admin endpoint (for routes this SDK doesn't wrap yet). raw=True: text, raw=bytes: bytes."""
511
- headers = {"Authorization": f"Bearer {self._admin_key}", "User-Agent": f"sfukit-python/{__version__}"}
754
+ def _headers(self) -> Dict[str, str]:
755
+ return {"Authorization": f"Bearer {self._admin_key}", "User-Agent": f"sfukit-python/{__version__}"}
756
+
757
+ def _upload(self, url: str, method: str, data: Any, content_type: Optional[str], timeout: float) -> Any:
758
+ """Send bytes to an upload link the kit gave. The link carries its own token, so no key is sent."""
759
+ if urllib.parse.urlparse(url).scheme not in ("http", "https"):
760
+ raise SfuKitError(400, f'invalid upload link "{url}"')
761
+ headers = {"User-Agent": f"sfukit-python/{__version__}"}
762
+ if content_type:
763
+ headers["Content-Type"] = content_type
764
+ req = urllib.request.Request(url, data=bytes(data), headers=headers, method=method)
765
+ try:
766
+ with urllib.request.urlopen(req, timeout=timeout) as res:
767
+ text = res.read().decode("utf-8")
768
+ except urllib.error.HTTPError as e:
769
+ raise _http_error("video upload", e) from None
770
+ return json.loads(text) if text else None
771
+
772
+ def request(
773
+ self,
774
+ method: str,
775
+ path: str,
776
+ body: Any = None,
777
+ raw: Any = False,
778
+ _encoded: Optional[tuple] = None,
779
+ timeout: Optional[float] = None,
780
+ ) -> Any:
781
+ """Call any admin endpoint (for routes this SDK doesn't wrap yet). raw=True: text, raw=bytes: bytes.
782
+ timeout: seconds for this call (default: the client's)."""
783
+ headers = self._headers()
512
784
  data = None
513
785
  if _encoded is not None:
514
786
  data, headers["Content-Type"] = _encoded
@@ -517,24 +789,32 @@ class SfuKit:
517
789
  headers["Content-Type"] = "application/json"
518
790
  req = urllib.request.Request(self.url + path, data=data, headers=headers, method=method)
519
791
  try:
520
- with urllib.request.urlopen(req, timeout=self.timeout) as res:
792
+ with urllib.request.urlopen(req, timeout=self.timeout if timeout is None else timeout) as res:
521
793
  data_out = res.read()
522
794
  if raw is bytes:
523
795
  return data_out
524
796
  text = data_out.decode("utf-8")
525
797
  except urllib.error.HTTPError as e:
526
- text = e.read().decode("utf-8", "replace")
527
- try:
528
- parsed: Any = json.loads(text)
529
- except ValueError:
530
- parsed = text
531
- msg = parsed.get("error", text) if isinstance(parsed, dict) else text
532
- raise SfuKitError(e.code, f"sfukit {method} {path}: {e.code} {msg}", parsed) from None
798
+ raise _http_error(f"{method} {path}", e) from None
533
799
  if raw:
534
800
  return text
535
801
  return json.loads(text) if text else None
536
802
 
537
803
 
804
+ def _slices(file: Any, size: int):
805
+ """The file's parts of `size` bytes: slices of bytes, or reads from a file object."""
806
+ if isinstance(file, (bytes, bytearray, memoryview)):
807
+ view = memoryview(file)
808
+ for at in range(0, len(view), size):
809
+ yield view[at : at + size]
810
+ return
811
+ while True:
812
+ chunk = file.read(size)
813
+ if not chunk:
814
+ return
815
+ yield chunk
816
+
817
+
538
818
  def _b64url(data: bytes) -> str:
539
819
  return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
540
820
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appsocom
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
5
5
  Author: Appsotech Limited
6
6
  License-Expression: MIT
@@ -86,7 +86,33 @@ def assistant_tools_route():
86
86
 
87
87
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
88
88
 
89
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
89
+ ## AI Tasks, Speech and Videos
90
+
91
+ ```python
92
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
93
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
94
+ marked["json"]["score"], marked["usage"]["credits"]
95
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
96
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
97
+ with kit.ai_stream("Tell a short story.") as story:
98
+ for piece in story:
99
+ print(piece, end="")
100
+ story.usage # model, tokens, cost, credits
101
+
102
+ # Speech
103
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
104
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
105
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
106
+
107
+ # Videos: an upload link for a browser, or send a file from your server
108
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
109
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
110
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
111
+ ```
112
+
113
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
114
+
115
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
90
116
 
91
117
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
92
118
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "appsocom"
7
- version = "0.7.0"
7
+ version = "0.8.0"
8
8
  description = "Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -298,3 +298,223 @@ class DataSaverTokenTest(unittest.TestCase):
298
298
  self.assertNotIn("ds", claims(sign_token(SECRET, "r1", "u1", data_saver="off")["token"]))
299
299
  with self.assertRaises(ValueError):
300
300
  sign_token(SECRET, "r1", "u1", data_saver="ultra")
301
+
302
+
303
+ class ServicesHandler(BaseHTTPRequestHandler):
304
+ """A fake kit for AI Tasks, Speech and Videos: remembers every request it gets."""
305
+
306
+ seen = []
307
+
308
+ def log_message(self, *a):
309
+ pass
310
+
311
+ def _reply(self, code, payload, ctype="application/json"):
312
+ data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
313
+ self.send_response(code)
314
+ self.send_header("Content-Type", ctype)
315
+ self.send_header("Content-Length", str(len(data)))
316
+ self.end_headers()
317
+ self.wfile.write(data)
318
+
319
+ def _go(self):
320
+ n = int(self.headers.get("Content-Length") or 0)
321
+ raw = self.rfile.read(n) if n else b""
322
+ ServicesHandler.seen.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()}, raw))
323
+ path, _, query = self.path.partition("?")
324
+ body = json.loads(raw) if raw and self.headers.get("Content-Type") == "application/json" else {}
325
+ base = f"http://127.0.0.1:{self.server.server_port}"
326
+ if path == "/ai/complete":
327
+ if body.get("prompt") == "limit":
328
+ return self._reply(429, {"error": "AI Tasks has reached this project's daily limit"})
329
+ if body.get("stream"):
330
+ self.send_response(200)
331
+ self.send_header("Content-Type", "text/event-stream")
332
+ self.end_headers()
333
+ if body.get("prompt") == "boom":
334
+ self.wfile.write(b'event: text\ndata: {"text":"Hel"}\n\nevent: error\ndata: {"error":"the model stopped"}\n\n')
335
+ else:
336
+ self.wfile.write(b'event: text\ndata: {"text":"Hel"}\n\nevent: text\ndata: {"text":"lo \xc3\xa9"}\n\nevent: done\ndata: {"usage":{"credits":0.2}}\n\n')
337
+ return
338
+ return self._reply(200, {"task": body.get("task", "custom"), "text": "ok", "json": {"score": 3}, "usage": {"credits": 0.1}})
339
+ if path in ("/ai/settings", "/ai/usage", "/ai/audit", "/speech/usage"):
340
+ return self._reply(200, {})
341
+ if path == "/speech/tts":
342
+ if body.get("response") == "url":
343
+ return self._reply(200, {"url": f"{base}/speech/audio/t/x.mp3?exp=1&sig=a", "cached": True, "characters": 0})
344
+ return self._reply(200, b"\x01\x02", "audio/mpeg")
345
+ if path == "/speech/stt":
346
+ if raw == b"quota":
347
+ return self._reply(429, {"error": "the project's daily speech budget is used up"})
348
+ return self._reply(200, {"text": "hello", "seconds": 3, "provider": "deepgram"})
349
+ if path == "/speech/config":
350
+ return self._reply(200, {"dailyBudgetUsd": body.get("dailyBudgetUsd"), "effectiveDailyCapUsd": 5})
351
+ if path == "/videos/uploads":
352
+ parts = body.get("name") == "big"
353
+ out = {"videoId": "v", "uploadUrl": f"{base}/videos/upload/p/v?t=x", "protocol": "parts" if parts else "put", "expiresAt": ""}
354
+ return self._reply(200, {**out, "partSize": 4, "parts": 3} if parts else out)
355
+ if path == "/videos/copy":
356
+ return self._reply(200, {"videoId": "v", "status": "processing"})
357
+ if path == "/videos/upload/p/v":
358
+ if "part=" in query:
359
+ n = int(query.split("part=")[1])
360
+ return self._reply(200, {"partNumber": n, "etag": f"e{n}"})
361
+ return self._reply(200, {"videoId": "v", "status": "processing"})
362
+ if path == "/videos" or path.startswith("/videos/"): # list, one video, update, delete, playback, usage
363
+ return self._reply(200, {"videoId": "v", "videos": [], "next": None})
364
+ self._reply(404, {"error": "no such route"})
365
+
366
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _go
367
+
368
+
369
+ class ServicesTests(unittest.TestCase):
370
+ @classmethod
371
+ def setUpClass(cls):
372
+ cls.server = HTTPServer(("127.0.0.1", 0), ServicesHandler)
373
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
374
+ cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}", "k")
375
+
376
+ @classmethod
377
+ def tearDownClass(cls):
378
+ cls.server.shutdown()
379
+
380
+ def last(self):
381
+ method, path, headers, raw = ServicesHandler.seen[-1]
382
+ return method, path, headers, (json.loads(raw) if raw and headers.get("content-type") == "application/json" else None)
383
+
384
+ def test_ai_tasks_post_to_ai_complete(self):
385
+ r = self.kit.ai_task("mark", {"question": "q", "answer": "a"}, user="s1", tier="smart", max_tokens=500, label=None)
386
+ self.assertEqual(r["json"], {"score": 3})
387
+ method, path, headers, body = self.last()
388
+ self.assertEqual((method, path, headers["authorization"]), ("POST", "/ai/complete", "Bearer k"))
389
+ self.assertEqual(body, {"user": "s1", "tier": "smart", "maxTokens": 500, "task": "mark", "input": {"question": "q", "answer": "a"}})
390
+ self.kit.ai_complete("hi", system="Be brief", json=True)
391
+ self.assertEqual(self.last()[3], {"prompt": "hi", "system": "Be brief", "json": True, "stream": False})
392
+ self.kit.ai_complete(system="Mark it", messages=[{"role": "user", "content": "x"}], json={"type": "object"})
393
+ self.assertEqual(self.last()[3], {"system": "Mark it", "messages": [{"role": "user", "content": "x"}], "json": {"type": "object"}, "stream": False})
394
+
395
+ def test_ai_tasks_errors_carry_the_status(self):
396
+ with self.assertRaises(SfuKitError) as cm:
397
+ self.kit.ai_complete("limit")
398
+ self.assertEqual(cm.exception.status, 429)
399
+ self.assertIn("daily limit", str(cm.exception))
400
+ with self.assertRaises(SfuKitError) as cm:
401
+ self.kit.ai_stream("limit") # refused at once, not on the first read
402
+ self.assertEqual(cm.exception.status, 429)
403
+
404
+ def test_ai_stream_yields_text_then_usage(self):
405
+ stream = self.kit.ai_stream("x", tier="standard")
406
+ self.assertIsNone(stream.usage)
407
+ self.assertEqual("".join(stream), "Hello é")
408
+ self.assertEqual(stream.usage, {"credits": 0.2})
409
+ self.assertEqual(self.last()[3], {"prompt": "x", "tier": "standard", "stream": True})
410
+ with self.assertRaises(SfuKitError) as cm:
411
+ list(self.kit.ai_stream("boom"))
412
+ self.assertEqual((cm.exception.status, str(cm.exception)), (502, "sfukit POST /ai/complete: the model stopped"))
413
+ with self.kit.ai_stream("x") as s: # stopping early closes the connection
414
+ self.assertEqual(next(iter(s)), "Hel")
415
+
416
+ def test_ai_settings_usage_and_audit_paths(self):
417
+ self.kit.set_ai_settings({"dailyBudgetUsd": 2})
418
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("PUT", "/ai/settings", {"dailyBudgetUsd": 2}))
419
+ self.kit.get_ai_settings()
420
+ self.assertEqual(self.last()[:2], ("GET", "/ai/settings"))
421
+ self.kit.get_ai_usage(30)
422
+ self.assertEqual(self.last()[:2], ("GET", "/ai/usage?days=30"))
423
+ self.kit.get_ai_usage()
424
+ self.assertEqual(self.last()[1], "/ai/usage?days=7")
425
+ self.kit.get_ai_audit("2026-11-20", "u1")
426
+ self.assertEqual(self.last()[1], "/ai/audit?day=2026-11-20&user=u1")
427
+ self.kit.get_ai_audit()
428
+ self.assertEqual(self.last()[1], "/ai/audit")
429
+
430
+ def test_speech(self):
431
+ self.assertEqual(self.kit.text_to_speech("Hi", language="yo", cache=None), b"\x01\x02")
432
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("POST", "/speech/tts", {"text": "Hi", "language": "yo", "response": "audio"}))
433
+ link = self.kit.text_to_speech_url("Hi", expires_in=600, format="wav")
434
+ self.assertIn("/speech/audio/", link["url"])
435
+ self.assertEqual(self.last()[3], {"text": "Hi", "expiresIn": 600, "format": "wav", "response": "url"})
436
+ out = self.kit.speech_to_text(b"\x00\x01\x02", content_type="audio/webm", language="en")
437
+ self.assertEqual((out["text"], out["seconds"]), ("hello", 3))
438
+ method, path, headers, _ = self.last()
439
+ self.assertEqual((method, path, headers["content-type"], headers["authorization"]), ("POST", "/speech/stt?language=en", "audio/webm", "Bearer k"))
440
+ self.assertEqual(ServicesHandler.seen[-1][3], b"\x00\x01\x02")
441
+ self.kit.speech_to_text(bytearray(b"a"))
442
+ self.assertEqual((self.last()[1], self.last()[2]["content-type"]), ("/speech/stt", "application/octet-stream"))
443
+ with self.assertRaises(SfuKitError) as cm:
444
+ self.kit.speech_to_text(b"quota")
445
+ self.assertEqual(cm.exception.status, 429)
446
+ with self.assertRaises(SfuKitError):
447
+ self.kit.speech_to_text("not bytes") # type: ignore[arg-type]
448
+ self.kit.get_speech_usage()
449
+ self.assertEqual(self.last()[:2], ("GET", "/speech/usage"))
450
+ self.assertEqual(self.kit.set_speech_daily_budget(None)["dailyBudgetUsd"], None)
451
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("PUT", "/speech/config", {"dailyBudgetUsd": None}))
452
+ self.assertEqual(self.kit.set_speech_daily_budget(2)["dailyBudgetUsd"], 2)
453
+
454
+ def test_the_video_methods_call_the_right_routes(self):
455
+ kit, v = self.kit, "a" * 32
456
+ calls = []
457
+
458
+ def seen(fn, *a, **kw):
459
+ fn(*a, **kw)
460
+ method, path, _, body = self.last()
461
+ calls.append((method, path, body))
462
+
463
+ seen(kit.create_video_upload, 600, name="Lesson 1", upload_length=5000)
464
+ seen(kit.copy_video, "https://files.example/a.mp4", name="Old")
465
+ seen(kit.list_videos, after="abc", limit=10)
466
+ seen(kit.list_videos)
467
+ seen(kit.get_video, v)
468
+ seen(kit.update_video, v, name="New")
469
+ seen(kit.video_playback, v, expires_in_seconds=900)
470
+ seen(kit.video_playback, v)
471
+ seen(kit.get_video_usage)
472
+ seen(kit.delete_video, v)
473
+ self.assertEqual(
474
+ calls,
475
+ [
476
+ ("POST", "/videos/uploads", {"maxDurationSeconds": 600, "name": "Lesson 1", "uploadLength": 5000}),
477
+ ("POST", "/videos/copy", {"url": "https://files.example/a.mp4", "name": "Old"}),
478
+ ("GET", "/videos?after=abc&limit=10", None),
479
+ ("GET", "/videos", None),
480
+ ("GET", f"/videos/{v}", None),
481
+ ("PATCH", f"/videos/{v}", {"name": "New"}),
482
+ ("POST", f"/videos/{v}/playback", {"expiresInSeconds": 900}),
483
+ ("POST", f"/videos/{v}/playback", {}),
484
+ ("GET", "/videos/usage", None),
485
+ ("DELETE", f"/videos/{v}", None),
486
+ ],
487
+ )
488
+ for bad in ("..", "a/b", "x" * 200):
489
+ with self.assertRaises(SfuKitError):
490
+ kit.get_video(bad)
491
+
492
+ def test_upload_video_file_sends_one_put_or_parts_then_complete(self):
493
+ import io
494
+
495
+ kit = self.kit
496
+ up = kit.create_video_upload(600)
497
+ n = len(ServicesHandler.seen)
498
+ self.assertEqual(kit.upload_video_file(up, b"0123456789")["status"], "processing")
499
+ method, path, headers, raw = ServicesHandler.seen[-1]
500
+ self.assertEqual((len(ServicesHandler.seen) - n, method, path, raw), (1, "PUT", "/videos/upload/p/v?t=x", b"0123456789"))
501
+ self.assertNotIn("authorization", headers) # the link has its own token; the key stays home
502
+ self.assertEqual(kit.upload_video_file(up, io.BytesIO(b"abc"))["status"], "processing")
503
+
504
+ for source in (b"0123456789", io.BytesIO(b"0123456789")):
505
+ big = kit.create_video_upload(600, name="big")
506
+ n = len(ServicesHandler.seen)
507
+ kit.upload_video_file(big, source)
508
+ sent = ServicesHandler.seen[n:]
509
+ self.assertEqual(
510
+ [(m, p, len(r)) for m, p, _, r in sent],
511
+ [("PUT", "/videos/upload/p/v?t=x&part=1", 4), ("PUT", "/videos/upload/p/v?t=x&part=2", 4), ("PUT", "/videos/upload/p/v?t=x&part=3", 2), ("POST", "/videos/upload/p/v?t=x&complete", len(sent[-1][3]))],
512
+ )
513
+ self.assertEqual(json.loads(sent[-1][3]), {"parts": [{"partNumber": 1, "etag": "e1"}, {"partNumber": 2, "etag": "e2"}, {"partNumber": 3, "etag": "e3"}]})
514
+ self.assertEqual(sent[-1][2]["content-type"], "application/json")
515
+ self.assertTrue(all("authorization" not in h for _, _, h, _ in sent))
516
+
517
+ def test_upload_links_must_be_http(self):
518
+ with self.assertRaises(SfuKitError) as cm:
519
+ self.kit.upload_video_file({"uploadUrl": "file:///etc/passwd", "protocol": "put"}, b"x")
520
+ self.assertEqual(cm.exception.status, 400)
File without changes
File without changes