mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat(plugins): add GitHub store and scoped collaborative panels
This commit is contained in:
1 parent
b9fccb8757
commit
ce681f749d
40 files changed
+1370
-5
No files matched your search
@@ -0,0 +1,158 @@
|
||||
# WebSpeak 功能插件开发 / Functional plugin development
|
||||
|
||||
本文描述 dev 分支的功能插件 API v1。实例需要包含插件商店;正式版 v0.2.9 尚无此接口。功能包 `.wplugin` 与外观包 `.wskin`、皮肤内部组件及其 API 独立。
|
||||
|
||||
## 使用与作用域
|
||||
|
||||
管理员进入 `/admin/plugins`,从 [GitHub 分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 安装或导入本地 `.wplugin`。检查作者、许可证和权限后,选择作用域、保存公开配置并启用。安装、更新后默认禁用,不能静默获取新权限。管理写操作受管理员会话、同源和 CSRF 保护,并记录审计。
|
||||
|
||||
用户连接语音工作台后,通过独立的“插件功能”入口打开隔离面板,不依赖皮肤的挂载位置。关闭面板或返回列表会退出插件房间、销毁 iframe 并停止媒体;插件不修改原生工作台 DOM。
|
||||
|
||||
| 类型 | 配置和房间边界 |
|
||||
| --- | --- |
|
||||
| `server` 服务器插件 | 配置允许的 TS `host:port`,用户按实际 TS 目标及频道进入各自房间 |
|
||||
| `instance` WebSpeak 实例插件 | 同一网关的已连接用户共享一个插件房间,跨 TS 服务器和频道 |
|
||||
|
||||
服务器绑定使用网关解析后的实际连接地址,不接受插件或浏览器自报的目标。使用 SRV、Nickname 或别名时,在实例连接列表核对实际目标。配置支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化。服务器插件未配置目标时不能启用。切频道会退出旧服务器插件房间,实例插件保留房间。断线、重连、卸载、更新或管理员修改配置会关闭旧上下文,需重新打开。
|
||||
|
||||
“所有人”指打开插件的 WebSpeak 浏览器参与者,TS 原生客户端不会运行网页插件。不同 WebSpeak 网关目前不共享插件房间。使用浏览器直连中继网关时,插件目录和房间属于实际连接的语音网关,需要在那里安装配置;只使用 UDP 加速不会改变房间归属。
|
||||
|
||||
## 包格式
|
||||
|
||||
`.wplugin` 是 UTF-8 JSON,最多 512 KiB,不是 ZIP;不包含服务端可执行文件、原生模块或任意路径。
|
||||
|
||||
```json
|
||||
{
|
||||
"manifest": {
|
||||
"apiVersion": 1, "id": "community.example", "name": "Example",
|
||||
"version": "1.0.0", "author": "Author", "license": "MIT",
|
||||
"description": "Collaborative panel",
|
||||
"scopes": ["server", "instance"],
|
||||
"permissions": ["room.read", "room.write"]
|
||||
},
|
||||
"html": "<main id='app'></main>",
|
||||
"script": "(async () => { const context = await webspeak.ready; })();",
|
||||
"styles": {
|
||||
"light": "body { background: #fff; color: #16332e; }",
|
||||
"dark": "body { background: #20242b; color: #edf5f2; }"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
两个基础样式都必须提供。宿主根据当前皮肤文字明暗推断基础配色,发送 `context.theme`,一次只启用一个样式表。iframe 不继承皮肤 CSS,无需适配每款皮肤的组件位置。语言为 `zh/en/de/ru/ja`,建议五种文案和英文回退。每段 HTML、脚本或样式最多 256 KiB,总包仍受 512 KiB 限制。ID 为小写字母、数字、点和连字符,最长 80 字符。
|
||||
|
||||
完整示例源文件在 [watch-together](examples/watch-together/manifest.json):`manifest.json`、`panel.html`、`player.js`、`light.css`、`dark.css`。
|
||||
|
||||
```sh
|
||||
node --import tsx scripts/build-plugin.mjs docs/examples/watch-together docs/examples/watch-together.wplugin
|
||||
node --import tsx --test src/plugins/plugins.test.ts
|
||||
```
|
||||
|
||||
构建器读取上述五个文件。其他工具链只需生成同格式 JSON。独立插件仓库不需要 WebSpeak 源码即可生成包;宿主导入时也会校验。
|
||||
|
||||
## 公共浏览器 API
|
||||
|
||||
脚本开始前,宿主提供只读 `window.webspeak`,不需要导入内部 Vue 组件。
|
||||
|
||||
```ts
|
||||
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
|
||||
interface Snapshot {
|
||||
roomId: string;
|
||||
revision: number;
|
||||
state: JsonValue; // 空房间初始为 null
|
||||
serverTime: number; // 网关 Unix 毫秒时间
|
||||
participants: { id: string; nickname: string }[];
|
||||
}
|
||||
interface Context {
|
||||
self: { id: string; nickname: string }; // 临时会话 ID,不是 TS 私钥或 UID
|
||||
config: JsonValue; // 管理员提供的公开配置
|
||||
scope: "server" | "instance";
|
||||
snapshot: Snapshot;
|
||||
theme: "light" | "dark";
|
||||
language: "zh" | "en" | "de" | "ru" | "ja";
|
||||
}
|
||||
interface WebSpeakPluginAPI {
|
||||
apiVersion: 1;
|
||||
ready: Promise<Context>;
|
||||
room: {
|
||||
snapshot(): Promise<Snapshot>;
|
||||
update(expectedRevision: number, state: JsonValue): Promise<Snapshot>;
|
||||
subscribe(listener: (snapshot: Snapshot) => void): () => void;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
`room.read` 允许读房间和订阅状态;`room.write` 允许替换共享状态,必须同时声明读权限。不需要共享数据的独立功能面板可声明空权限数组:仍可打开并获得公开配置,但上下文仅含空快照,不能读写或订阅其他参与者。当前所有已加入且拥有写权限的参与者都能操作,没有隐含主持人角色或 TS 管理权限。API 不提供 TS Query、宿主 DOM、系统文件、管理员凭据或任意宿主方法。需要新能力时另行提议接口,不能访问内部实现绕过。
|
||||
|
||||
更新使用比较并交换:读取 N 后提交 N,成功返回 N+1;冲突返回 `PLUGIN_REVISION_CONFLICT`。重新读取,让用户重试或基于新状态重算,不能盲目覆盖。
|
||||
|
||||
```js
|
||||
const api = window.webspeak;
|
||||
const context = await api.ready;
|
||||
let snapshot = context.snapshot;
|
||||
const unsubscribe = api.room.subscribe(next => {
|
||||
if (next.roomId !== snapshot.roomId || next.revision < snapshot.revision) return;
|
||||
snapshot = next;
|
||||
render(next.state);
|
||||
});
|
||||
async function update(next) {
|
||||
try { snapshot = await api.room.update(snapshot.revision, next); }
|
||||
catch (error) {
|
||||
if (error.message === "PLUGIN_REVISION_CONFLICT") snapshot = await api.room.snapshot();
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
addEventListener("pagehide", unsubscribe, { once: true });
|
||||
```
|
||||
|
||||
共享状态上限 16 KiB、16 层嵌套、4096 个节点,只接受 JSON,不接受非有限数、原型键或二进制媒体。公开配置上限 8 KiB。每会话每秒最多 20 个插件请求,每个房间每秒最多 10 次共享写入,关闭操作不受频率限制。最多 8 个已打开插件(当前面板一次打开一个);每网关最多 800 个非空房间、50 个已安装插件。读取快照不触发广播。不要通过高频写状态传视频帧。服务端只保存通用状态与成员,不执行插件代码。
|
||||
|
||||
最后一位参与者离开立即销毁房间,重启也会丢失临时房间。安装和配置持久化于数据目录 `plugins/*.json`,原子替换;实例备份应包含此目录。需要持久业务数据或外部适配器时,应定义额外能力协议。
|
||||
|
||||
主要错误:`PLUGIN_NOT_CONNECTED`、`PLUGIN_NOT_ALLOWED`、`PLUGIN_DISABLED`、`PLUGIN_NOT_OPEN`、`PLUGIN_PERMISSION_DENIED`、`PLUGIN_REVISION_CONFLICT`、`PLUGIN_RATE_LIMITED`、`PLUGIN_TOO_LARGE`、`PLUGIN_TIMEOUT`。配置或包变化会关闭旧上下文并提示重新打开。
|
||||
|
||||
为避免可选插件消息挤占语音连接的内存,出站队列超过 512 KiB 时跳过插件消息。恢复连接质量后可请求快照或重新打开插件;请求无响应会超时,不代表共享写入一定没有执行。
|
||||
|
||||
## 同步观影示例
|
||||
|
||||
状态为 `{ url, position, playing, updatedAt }`。加载、播放、暂停、跳转共享;音量、全屏与播放许可仅影响自己。使用快照 `serverTime` 估算网关时钟,推算播放 elapsed time,定时校正漂移,大偏移跳转、小偏移暂调速。后来加入读取同一快照追上进度,不依赖过去的操作事件。
|
||||
|
||||
视频由每个浏览器直接从 URL 加载,不经过 WebSpeak 中转。支持浏览器可解码的 MP4/WebM 等直链,不支持播放网页、DRM、登录后 URL 或嵌入式平台播放器。HTTPS 实例一般需要 HTTPS 视频。自动播放受浏览器策略限制,可能需要点击“允许播放”。源端带宽、网络和缓冲会影响误差,不承诺逐帧同步。
|
||||
|
||||
## 隔离与清理
|
||||
|
||||
使用 opaque-origin `sandbox="allow-scripts"` iframe,不授予 `allow-same-origin`、顶部导航、弹窗、表单、麦克风或摄像头。宿主 RPC 校验 `event.source`、随机通道和面板生命周期;插件不能选择另一个 ID 或房间。CSP 禁止 fetch/WebSocket、外部脚本、嵌套 iframe,仅允许直接媒体及 HTTPS 图片。媒体源仍会收到浏览器请求,配置、共享状态和视频 URL 都不能包含管理员密钥。
|
||||
|
||||
隔离不是恶意代码审核、CPU/内存配额的替代品。管理员应审查来源。插件在 `pagehide` 清理计时器、订阅和媒体;宿主关闭时销毁 iframe,后端移除房间成员,迟到响应不能重开已关闭面板。
|
||||
|
||||
## GitHub 分发协议
|
||||
|
||||
根仓库 `main/index.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"plugins": [{
|
||||
"id": "community.example",
|
||||
"repository": "https://github.com/OWNER/REPOSITORY",
|
||||
"metadataPath": "plugin.json"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
`metadataPath` 默认 `plugin.json`,也支持子目录。同一个仓库可以分发多个插件。对应仓库默认分支的元数据:
|
||||
|
||||
```json
|
||||
{
|
||||
"manifest": { "apiVersion": 1, "id": "community.example", "name": "Example", "version": "1.0.0", "author": "Author", "license": "MIT", "description": "Example", "scopes": ["server"], "permissions": ["room.read", "room.write"] },
|
||||
"package": { "ref": "IMMUTABLE_COMMIT_OR_TAG", "path": "example.wplugin", "sha256": "64_lowercase_hex_digits" }
|
||||
}
|
||||
```
|
||||
|
||||
使用真实 SHA-256,推荐固定提交或发布标签;不要上传占位值。只访问 `raw.githubusercontent.com`,拒绝重定向、非法地址/路径、超时和超限数据。安装时重读目录和元数据,核对管理员看到的 revision,再下载校验摘要及清单;installedRevision 也作并发保护。失败保留旧包。摘要是内容一致性校验,不是作者签名或安全认证。
|
||||
|
||||
## English quick start
|
||||
|
||||
Functional plugins are portable UTF-8 `.wplugin` JSON bundles, independent of skins. Install under `/admin/plugins`, review permissions, select `server` (target + channel) or `instance` (one room across connected users of this gateway), and explicitly enable. Open the common Plugins panel after joining voice. Native TS clients and separate WebSpeak gateways do not share this runtime.
|
||||
|
||||
Await `window.webspeak.ready`, subscribe with `webspeak.room.subscribe`, and write with revision-checked `room.update`. The API types, limits and distribution schemas above are normative. Both light/dark styles are required. The [Watch Together example](examples/watch-together/player.js) implements clock-based progress, late joining, conflict recovery, autoplay handling and cleanup without host-specific player code. Build using the command above and import into an isolated development instance. Develop plugins without modifying WebSpeak runtime files; propose missing capabilities separately.
|
||||
@@ -359,3 +359,10 @@ Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusamm
|
||||
- [LainHE](https://github.com/LainHE) — [zusammengeführte PRs #2, #8, #28, #31–#35, #37, #38 und #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): Browser-Fehlerübersetzungen, Skalierung und Startseitenlayout, Bildschirmfreigabe-Bitrate und Zuschaueravatare, Relay-Zielprüfung und Wiederverbindung, vertrauenswürdige Proxys, Weitergabe von Verbindungsfehlern, Audio-Fehlermeldungen und Ressourcenfreigabe bei WebRTC-Fehlern.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) verbesserte das Beibehalten des KAAK-Arbeitsbereichs und die Wiederverbindung nach der ersten Verbindung. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) und [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) lieferten das ursprüngliche Design und die Implementierung des Discord-Skins (Commit-Autor **yumi**), die das WebSpeak-Projekt in einen [eigenständig verteilten `.wskin`-Skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) überführte.
|
||||
|
||||
## Funktionale Plugins entwickeln (dev)
|
||||
|
||||
Plugin-API, Server-/Instanzbereiche, gemeinsamer Videoplayer und GitHub-Verteilung:
|
||||
|
||||
- [Plugin-Entwicklungsleitfaden](PLUGIN_DEVELOPMENT.md)
|
||||
- [Agent Skill für Plugin-Entwicklung](../.agents/skills/webspeak-plugin-development/SKILL.md)
|
||||
@@ -369,3 +369,10 @@ This list acknowledges the upstream SDK author, contributions through merged Git
|
||||
- [LainHE](https://github.com/LainHE) — [merged PRs #2, #8, #28, #31–#35, #37, #38 and #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE), covering browser error translations, scaling and home layout, screen-share bitrate and viewer avatars, relay target validation and recovery, trusted proxy handling, connection-failure propagation, audio fault reporting, and WebRTC failure cleanup.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added registered TeamSpeak nickname connections and preserved nickname targets; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) improved KAAK workspace retention and reconnection after the first connection. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) and [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) supplied the original Discord skin design and implementation (commit author **yumi**), later adapted by the WebSpeak project into an [independently distributed `.wskin` skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
|
||||
## Functional plugin development (dev)
|
||||
|
||||
Plugin API, server/instance scopes, Watch Together example, and GitHub distribution:
|
||||
|
||||
- [Plugin development guide](PLUGIN_DEVELOPMENT.md)
|
||||
- [Plugin development Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md)
|
||||
@@ -241,3 +241,10 @@ WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で
|
||||
- [LainHE](https://github.com/LainHE) — [マージ済み PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE)。ブラウザのエラー翻訳、拡大縮小とホームのレイアウト、画面共有のビットレートと視聴者アバター、中継先の検証と再接続、信頼済みプロキシの扱い、接続失敗の通知、音声エラー報告、WebRTC 失敗時のリソース解放を改善。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネーム接続と接続先の保持に対応し、[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) で初回接続後の KAAK ワークスペース保持と再接続を改善。[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) と [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) では Discord スキンの原作デザインと実装を提供(コミット名義 **yumi**)。その後、WebSpeak プロジェクトが[独立配布の `.wskin` スキン](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)へ移植。
|
||||
|
||||
## 機能プラグイン開発(dev)
|
||||
|
||||
プラグイン API、サーバー/インスタンススコープ、同期プレーヤー、GitHub 配布:
|
||||
|
||||
- [プラグイン開発ガイド](PLUGIN_DEVELOPMENT.md)
|
||||
- [プラグイン開発 Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md)
|
||||
@@ -243,3 +243,10 @@ WebSpeak распространяется по [GNU Affero General Public Licens
|
||||
- [LainHE](https://github.com/LainHE) — [объединённые PR #2, #8, #28, #31–#35, #37, #38 и #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): переводы ошибок браузера, масштабирование и компоновка главной страницы, битрейт трансляции и аватары зрителей, проверка целей и восстановление ретранслятора, доверенные прокси, передача ошибок подключения, сообщения об ошибках аудио и освобождение ресурсов при сбоях WebRTC.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak с сохранением имени цели; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) улучшил сохранение рабочего пространства KAAK и повторное подключение после первого соединения. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) и [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) содержали исходный дизайн и реализацию скина Discord (автор коммитов **yumi**), которые проект WebSpeak перенёс в [отдельно распространяемый скин `.wskin`](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
|
||||
## Разработка функциональных плагинов (dev)
|
||||
|
||||
API плагинов, области сервера/экземпляра, совместный видеоплеер и распространение через GitHub:
|
||||
|
||||
- [Руководство по разработке плагинов](PLUGIN_DEVELOPMENT.md)
|
||||
- [Agent Skill для разработки плагинов](../.agents/skills/webspeak-plugin-development/SKILL.md)
|
||||
@@ -373,3 +373,10 @@ npm start
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
|
||||
## 功能插件开发(dev)
|
||||
|
||||
功能插件系统的开发指南、服务器与实例作用域、同步观影示例和 GitHub 分发:
|
||||
|
||||
- [插件开发指南](PLUGIN_DEVELOPMENT.md)
|
||||
- [插件开发 Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md)
|
||||
@@ -0,0 +1 @@
|
||||
{"manifest":{"apiVersion":1,"id":"community.watch-together","name":"Watch Together / 一起观看","version":"1.0.0","author":"Huddle-Up-Forge","license":"AGPL-3.0-only","description":"A shared video player with synchronized playback, pause and seeking. / 同步播放、暂停与跳转的视频播放器。","scopes":["server","instance"],"permissions":["room.read","room.write"]},"html":"<main>\n <header><h1 id=\"title\">Watch Together</h1><span id=\"members\"></span></header>\n <p id=\"lead\"></p>\n <form id=\"source\"><label><span id=\"url-label\">Video URL</span><input id=\"url\" type=\"url\" maxlength=\"2048\" placeholder=\"https://…/video.mp4\" required></label><button id=\"load\" type=\"button\">Load</button></form>\n <video id=\"video\" playsinline preload=\"metadata\"></video>\n <div class=\"controls\"><button id=\"play\" type=\"button\">▶</button><button id=\"pause\" type=\"button\">Ⅱ</button><button id=\"unlock\" type=\"button\">Enable playback</button><button id=\"fullscreen\" type=\"button\">⛶</button><label class=\"volume\">♫ <input id=\"volume\" type=\"range\" min=\"0\" max=\"1\" step=\".05\" value=\".7\" aria-label=\"Volume\"></label></div>\n <label class=\"seek\"><span id=\"time\">0:00 / 0:00</span><input id=\"seek\" type=\"range\" min=\"0\" max=\"1\" step=\".1\" value=\"0\" aria-label=\"Seek\"></label>\n <p id=\"status\" role=\"status\"></p>\n <p id=\"note\" class=\"note\"></p>\n</main>\n","script":"/* Uses only the public plugin API. Nothing here imports WebSpeak internals. */\n(async () => {\n const api = window.webspeak, context = await api.ready;\n const $ = id => document.getElementById(id), video = $('video');\n const language = context.language, zh = language === 'zh';\n const texts = {\n zh: ['一起观看','所有参与者共享播放、暂停和进度;音量仅影响自己。','视频直链','载入视频','允许播放','请使用浏览器支持的 MP4 / WebM 视频直链。不会把视频经过 WebSpeak 服务器转发。','浏览器阻止自动播放,请点击“允许播放”。','视频无法加载,请检查地址、格式与 HTTPS。','有人同时操作,已获取最新进度,请重试。'],\n en: ['Watch Together','Playback, pause and seeking are shared; volume is local.','Direct video URL','Load video','Enable playback','Use a browser-compatible MP4 / WebM URL. Video is fetched directly, never relayed by WebSpeak.','Autoplay was blocked. Click Enable playback.','Video could not load. Check URL, format and HTTPS.','Another participant changed playback. Refreshed; please try again.'],\n de: ['Gemeinsam ansehen','Wiedergabe, Pause und Position sind gemeinsam; Lautstärke ist lokal.','Direkte Video-URL','Video laden','Wiedergabe erlauben','Browserkompatible MP4-/WebM-URL verwenden. Video wird direkt geladen.','Autoplay blockiert. Wiedergabe erlauben anklicken.','Video nicht ladbar. URL, Format und HTTPS prüfen.','Gleichzeitige Änderung. Aktualisiert; erneut versuchen.'],\n ru: ['Смотреть вместе','Воспроизведение, пауза и позиция общие; громкость локальная.','Прямая ссылка на видео','Загрузить видео','Разрешить воспроизведение','Используйте прямую ссылку MP4 / WebM. Видео загружается напрямую.','Автовоспроизведение заблокировано. Нажмите Разрешить воспроизведение.','Не удалось загрузить видео. Проверьте адрес, формат и HTTPS.','Другой участник изменил состояние. Обновлено; повторите.'],\n ja: ['一緒に見る','再生・停止・位置を共有します。音量は自分の端末のみです。','動画の直接 URL','動画を読み込む','再生を許可','ブラウザー対応の MP4 / WebM URL を使用します。動画は直接取得されます。','自動再生がブロックされました。「再生を許可」を押してください。','動画を読み込めません。URL・形式・HTTPS を確認してください。','他の参加者が操作しました。最新状態で再試行してください。'],\n };\n const t = texts[language] || texts.en;\n ['title','lead','url-label','load','unlock','note'].forEach((id,i) => $(id).textContent=t[i]);\n $('play').ariaLabel=zh?'同步播放':'Play for everyone'; $('pause').ariaLabel=zh?'同步暂停':'Pause for everyone';\n $('fullscreen').ariaLabel=zh?'全屏':'Fullscreen';\n let snapshot=context.snapshot, offset=snapshot.serverTime-Date.now(), source='', busy=false, seeking=false, playingAttempt=false;\n video.volume=.7;\n function validState(value) {\n if(!value || typeof value.url!=='string' || value.url.length>2048 || typeof value.playing!=='boolean' || !Number.isFinite(value.position) || value.position<0 || value.position>604800 || Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
body{background:#20242b;color:#e9eeee}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #58676b;border-radius:8px;background:#303840;color:#e9eeee;font:inherit}button{padding:10px 15px;border:1px solid #588579;border-radius:8px;background:#254c43;color:#dcfff4;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#080c0e;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#ffaf91}input[type=range]{accent-color:#7cdbc2}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}}
|
||||
@@ -0,0 +1 @@
|
||||
body{background:#f2f7f6;color:#183c38}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #83aaa4;border-radius:8px;background:#fff;color:#183c38;font:inherit}button{padding:10px 15px;border:1px solid #739e96;border-radius:8px;background:#e0f1eb;color:#174d41;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#101719;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#a33c24}input[type=range]{accent-color:#168575}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"id": "community.watch-together",
|
||||
"name": "Watch Together / 一起观看",
|
||||
"version": "1.0.0",
|
||||
"author": "Huddle-Up-Forge",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A shared video player with synchronized playback, pause and seeking. / 同步播放、暂停与跳转的视频播放器。",
|
||||
"scopes": ["server", "instance"],
|
||||
"permissions": ["room.read", "room.write"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<main>
|
||||
<header><h1 id="title">Watch Together</h1><span id="members"></span></header>
|
||||
<p id="lead"></p>
|
||||
<form id="source"><label><span id="url-label">Video URL</span><input id="url" type="url" maxlength="2048" placeholder="https://…/video.mp4" required></label><button id="load" type="button">Load</button></form>
|
||||
<video id="video" playsinline preload="metadata"></video>
|
||||
<div class="controls"><button id="play" type="button">▶</button><button id="pause" type="button">Ⅱ</button><button id="unlock" type="button">Enable playback</button><button id="fullscreen" type="button">⛶</button><label class="volume">♫ <input id="volume" type="range" min="0" max="1" step=".05" value=".7" aria-label="Volume"></label></div>
|
||||
<label class="seek"><span id="time">0:00 / 0:00</span><input id="seek" type="range" min="0" max="1" step=".1" value="0" aria-label="Seek"></label>
|
||||
<p id="status" role="status"></p>
|
||||
<p id="note" class="note"></p>
|
||||
</main>
|
||||
@@ -0,0 +1,65 @@
|
||||
/* Uses only the public plugin API. Nothing here imports WebSpeak internals. */
|
||||
(async () => {
|
||||
const api = window.webspeak, context = await api.ready;
|
||||
const $ = id => document.getElementById(id), video = $('video');
|
||||
const language = context.language, zh = language === 'zh';
|
||||
const texts = {
|
||||
zh: ['一起观看','所有参与者共享播放、暂停和进度;音量仅影响自己。','视频直链','载入视频','允许播放','请使用浏览器支持的 MP4 / WebM 视频直链。不会把视频经过 WebSpeak 服务器转发。','浏览器阻止自动播放,请点击“允许播放”。','视频无法加载,请检查地址、格式与 HTTPS。','有人同时操作,已获取最新进度,请重试。'],
|
||||
en: ['Watch Together','Playback, pause and seeking are shared; volume is local.','Direct video URL','Load video','Enable playback','Use a browser-compatible MP4 / WebM URL. Video is fetched directly, never relayed by WebSpeak.','Autoplay was blocked. Click Enable playback.','Video could not load. Check URL, format and HTTPS.','Another participant changed playback. Refreshed; please try again.'],
|
||||
de: ['Gemeinsam ansehen','Wiedergabe, Pause und Position sind gemeinsam; Lautstärke ist lokal.','Direkte Video-URL','Video laden','Wiedergabe erlauben','Browserkompatible MP4-/WebM-URL verwenden. Video wird direkt geladen.','Autoplay blockiert. Wiedergabe erlauben anklicken.','Video nicht ladbar. URL, Format und HTTPS prüfen.','Gleichzeitige Änderung. Aktualisiert; erneut versuchen.'],
|
||||
ru: ['Смотреть вместе','Воспроизведение, пауза и позиция общие; громкость локальная.','Прямая ссылка на видео','Загрузить видео','Разрешить воспроизведение','Используйте прямую ссылку MP4 / WebM. Видео загружается напрямую.','Автовоспроизведение заблокировано. Нажмите Разрешить воспроизведение.','Не удалось загрузить видео. Проверьте адрес, формат и HTTPS.','Другой участник изменил состояние. Обновлено; повторите.'],
|
||||
ja: ['一緒に見る','再生・停止・位置を共有します。音量は自分の端末のみです。','動画の直接 URL','動画を読み込む','再生を許可','ブラウザー対応の MP4 / WebM URL を使用します。動画は直接取得されます。','自動再生がブロックされました。「再生を許可」を押してください。','動画を読み込めません。URL・形式・HTTPS を確認してください。','他の参加者が操作しました。最新状態で再試行してください。'],
|
||||
};
|
||||
const t = texts[language] || texts.en;
|
||||
['title','lead','url-label','load','unlock','note'].forEach((id,i) => $(id).textContent=t[i]);
|
||||
$('play').ariaLabel=zh?'同步播放':'Play for everyone'; $('pause').ariaLabel=zh?'同步暂停':'Pause for everyone';
|
||||
$('fullscreen').ariaLabel=zh?'全屏':'Fullscreen';
|
||||
let snapshot=context.snapshot, offset=snapshot.serverTime-Date.now(), source='', busy=false, seeking=false, playingAttempt=false;
|
||||
video.volume=.7;
|
||||
function validState(value) {
|
||||
if(!value || typeof value.url!=='string' || value.url.length>2048 || typeof value.playing!=='boolean' || !Number.isFinite(value.position) || value.position<0 || value.position>604800 || !Number.isFinite(value.updatedAt)) return null;
|
||||
try {const u=new URL(value.url);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)return null;}catch{return null;}
|
||||
return value;
|
||||
}
|
||||
function targetPosition(state) {return Math.max(0,Math.min(604800,state.position+(state.playing?Math.max(0,(Date.now()+offset-state.updatedAt)/1000):0)));}
|
||||
function status(message='') {$('status').textContent=message;}
|
||||
async function apply() {
|
||||
const state=validState(snapshot.state); if(!state)return;
|
||||
if(source!==state.url){source=state.url;video.src=source;$('url').value=source;video.load();}
|
||||
const desired=targetPosition(state);
|
||||
if(Number.isFinite(video.duration)&&video.duration>0&&desired>=video.duration){video.pause();video.playbackRate=1;return;}
|
||||
if(video.readyState>=1 && !seeking){const diff=desired-video.currentTime;
|
||||
if(Math.abs(diff)>(state.playing?.7:.04))video.currentTime=Math.min(desired,Number.isFinite(video.duration)?video.duration:desired);
|
||||
video.playbackRate=state.playing&&Math.abs(diff)>.15&&Math.abs(diff)<=.7?(diff>0?1.03:.97):1;
|
||||
}
|
||||
if(state.playing&&video.paused&&!playingAttempt){playingAttempt=true;try{await video.play();status();}catch{status(t[6]);}finally{playingAttempt=false;}}
|
||||
else if(!state.playing&&!video.paused)video.pause();
|
||||
}
|
||||
function receive(next) {if(next.roomId!==snapshot.roomId || next.revision<snapshot.revision)return;snapshot=next;offset=next.serverTime-Date.now();$('members').textContent=(zh?'参与者:':'Participants: ')+next.participants.length;void apply();}
|
||||
async function update(patch) {
|
||||
if(busy)return;busy=true;
|
||||
try {
|
||||
const state=validState(snapshot.state), next={url:state?.url||source,position:state?targetPosition(state):0,playing:state?.playing||false,updatedAt:Date.now()+offset,...patch};
|
||||
if(!validState(next))throw new Error(t[7]);
|
||||
receive(await api.room.update(snapshot.revision,next)); status();
|
||||
} catch(error){if(error.message==='PLUGIN_REVISION_CONFLICT'){receive(await api.room.snapshot());status(t[8]);}else status(error.message);}
|
||||
finally{busy=false;}
|
||||
}
|
||||
const load=()=>{if($('url').checkValidity())void update({url:$('url').value.trim(),position:0,playing:false});else $('url').reportValidity();};
|
||||
$('load').addEventListener('click',load);
|
||||
$('source').addEventListener('submit',event=>event.preventDefault());
|
||||
$('url').addEventListener('keydown',event=>{if(event.key==='Enter'){event.preventDefault();load();}});
|
||||
$('play').addEventListener('click',()=>{void video.play().catch(()=>status(t[6]));void update({playing:true});});
|
||||
$('pause').addEventListener('click',()=>void update({playing:false,position:video.currentTime}));
|
||||
$('unlock').addEventListener('click',()=>{void video.play().then(()=>{if(!snapshot.state?.playing)video.pause();status();}).catch(()=>status(t[6]));});
|
||||
$('fullscreen').addEventListener('click',()=>void video.requestFullscreen?.().catch(()=>undefined));
|
||||
$('volume').addEventListener('input',()=>video.volume=Number($('volume').value));
|
||||
$('seek').addEventListener('input',()=>{seeking=true;});
|
||||
$('seek').addEventListener('change',()=>{seeking=false;void update({position:Number($('seek').value)});});
|
||||
video.addEventListener('loadedmetadata',()=>void apply()); video.addEventListener('error',()=>status(t[7]));
|
||||
video.addEventListener('ended',()=>{video.playbackRate=1;});
|
||||
const time=value=>`${Math.floor(value/60)}:${Math.floor(value%60).toString().padStart(2,'0')}`;
|
||||
const timer=setInterval(()=>{void apply();const duration=Number.isFinite(video.duration)?video.duration:0;$('seek').max=String(duration||1);if(!seeking)$('seek').value=String(video.currentTime);$('time').textContent=`${time(video.currentTime)} / ${time(duration)}`;},1000);
|
||||
const unsubscribe=api.room.subscribe(receive);receive(snapshot);
|
||||
addEventListener('pagehide',()=>{clearInterval(timer);unsubscribe();video.pause();video.removeAttribute('src');video.load();},{once:true});
|
||||
})();
|
||||
Reference in new issue
Block a user