@soffits/dsh-media-hub 0.0.0-stage → 0.7.0

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.
package/locale/zh.json ADDED
@@ -0,0 +1,276 @@
1
+ {
2
+ "meta": {
3
+ "title": "媒体",
4
+ "description": "跨来源搜索剧集、小说、电子书和论文。异地同步一起看,或把书按想要的格式下载到自己的书架。"
5
+ },
6
+ "ui": {
7
+ "panel": "媒体",
8
+ "title": "媒体",
9
+ "note": "找剧、小说、电子书和论文。一起看的时候进度同步,书可以按想要的格式下载。",
10
+ "source.all": "全部来源",
11
+ "search.sourceFailed": "{source} 没有回应:{message}",
12
+ "filter.label": "筛选",
13
+ "filter.labelActive": "筛选({n})",
14
+ "filter.any": "不限",
15
+ "filter.language": "语言",
16
+ "filter.format": "格式",
17
+ "filter.yearFrom": "起始年份",
18
+ "filter.yearTo": "截止年份",
19
+ "filter.size": "大小",
20
+ "filter.upTo": "不超过 {size}",
21
+ "book.format": "格式",
22
+ "book.download": "下载",
23
+ "book.downloadAs": "下载 {format}",
24
+ "book.fetching": "下载中…",
25
+ "book.converting": "下载并转换中…",
26
+ "book.converted": "转换",
27
+ "book.onShelf": "已在书架",
28
+ "book.save": "保存 {format}",
29
+ "shelf.title": "我的书",
30
+ "shelf.empty": "还没有书。在「发现」里找本书或小说下载吧。",
31
+ "shelf.usedOf": "已用 {used},共 {cap}",
32
+ "shelf.removed": "为了省空间已删掉文件,随时可以再下载。",
33
+ "shelf.again": "重新下载",
34
+ "shelf.delete": "删除",
35
+ "shelf.deleteQuestion": "从书架删除这本书?",
36
+ "chat.ask": "问问",
37
+ "chat.about": "聊聊这个",
38
+ "kind.novel": "小说",
39
+ "kind.ebook": "电子书",
40
+ "kind.paper": "论文",
41
+ "tab.watching": "正在看",
42
+ "tab.library": "片库",
43
+ "tab.discover": "发现",
44
+ "discover.source": "来源",
45
+ "discover.kind": "分类",
46
+ "discover.back": "返回",
47
+ "discover.workFailed": "没能加载这部作品:{message}",
48
+ "search.openWork": "打开这部作品",
49
+ "search.more": "加载更多",
50
+ "sort.label": "排序",
51
+ "sort.default": "默认",
52
+ "sort.plays": "播放量",
53
+ "sort.newest": "最新",
54
+ "search.inLibrary": "已在片库",
55
+ "search.offline": "已离线",
56
+ "search.joinRoom": "加入房间",
57
+ "search.continue": "继续看",
58
+ "search.open": "打开",
59
+ "link.invalid": "请粘贴视频或播放列表页面的链接。",
60
+ "watching.continue": "继续看",
61
+ "watching.emptyTitle": "现在没有人在看。",
62
+ "watching.emptyHint": "从片库接着看,或者去发现新的。",
63
+ "search.label": "搜索",
64
+ "search.placeholder": "搜索{source}",
65
+ "search.go": "搜索",
66
+ "search.none": "没有找到。",
67
+ "search.episodes.one": "{n} 集",
68
+ "search.episodes.other": "{n} 集",
69
+ "search.chapters.one": "{n} 章",
70
+ "search.chapters.other": "{n} 章",
71
+ "search.score": "★ {score}",
72
+ "search.finished": "已完结",
73
+ "search.ongoing": "连载中",
74
+ "search.watch": "观看",
75
+ "search.save": "存进片库",
76
+ "search.saveHint": "先存最前面的几集({n} 集),看到哪下到哪",
77
+ "search.saveAll": "全部下载(离线)",
78
+ "search.saveAllHint": "把每一集都存在本地,离线也能看",
79
+ "search.saveAllQuestion": "全部 {n} 集,大约 {size}?",
80
+ "search.loading": "正在搜索…",
81
+ "search.opening": "正在开房间…",
82
+ "search.saving": "正在添加…",
83
+ "search.saved": "已存入,前几集正在下载",
84
+ "search.savedAll": "正在下载整部",
85
+ "search.stopped": "已停更",
86
+ "search.details": "详情",
87
+ "search.hideDetails": "收起",
88
+ "search.latest": "最新:{title}",
89
+ "search.related": "其他季与相关作品",
90
+ "search.relatedLoading": "正在找其他季…",
91
+ "search.noRelated": "没有找到其他季或相关作品。",
92
+ "relation.season": "其他季",
93
+ "relation.same-title": "同名",
94
+ "relation.related": "相关",
95
+ "pop.plays": "{n}次播放",
96
+ "pop.readers": "{n}人读过",
97
+ "pop.listeners": "{n}人在听",
98
+ "pop.viewers": "{n}人看过",
99
+ "pop.followers": "{n}人关注",
100
+ "pop.heat": "{n}热度",
101
+ "meta.heat": "热度",
102
+ "meta.followers": "关注",
103
+ "meta.cast": "演员",
104
+ "meta.duration": "时长",
105
+ "meta.updated": "更新",
106
+ "meta.publisher": "出品方",
107
+ "meta.narrator": "主播",
108
+ "meta.words": "字数",
109
+ "meta.studio": "出品",
110
+ "kind.drama": "短剧",
111
+ "kind.audio": "有声书",
112
+ "rooms.heading": "正在进行的房间",
113
+ "room.tab.episodes": "选集",
114
+ "room.tab.about": "简介",
115
+ "room.nextSeason": "下一季:{title}",
116
+ "room.state.playing": "播放中",
117
+ "room.state.paused": "已暂停",
118
+ "follow.follow": "追剧",
119
+ "follow.following": "追剧中",
120
+ "follow.stop": "取消追剧",
121
+ "follow.hint": "关注它的下一季,新的一季会自动加进片库",
122
+ "follow.season": "第 {n} 季,共 {total} 季",
123
+ "follow.newEpisodes.one": "更新了 {n} 集",
124
+ "follow.newEpisodes.other": "更新了 {n} 集",
125
+ "follow.newSeason": "新一季上线",
126
+ "follow.newSeasonOf": "{title} 新一季上线",
127
+ "follow.news": "有更新",
128
+ "follow.dismiss": "知道了",
129
+ "rooms.emptySince": "{time} 起没人在看",
130
+ "rooms.unopened": "还没人进来过",
131
+ "rooms.join": "加入",
132
+ "rooms.watching": "{names} 在看",
133
+ "rooms.episode": "第 {n} 集,共 {total} 集",
134
+ "rooms.preparing": "{n} 集准备中",
135
+ "rooms.openedBy": "{name} 开的",
136
+ "rooms.closeQuestion": "关闭这个房间?",
137
+ "rooms.closeQuestionBusy": "{names} 还在里面,关闭?",
138
+ "start.library": "片库",
139
+ "start.libraryEmpty": "片库还是空的。可以去「发现」找一部存进来,或者让助手准备。",
140
+ "library.episodes.one": "{n} 集",
141
+ "library.episodes.other": "{n} 集",
142
+ "library.cachedOf": "已缓存 {n}/{total} 集",
143
+ "library.offline": "离线",
144
+ "library.notCached": "未缓存",
145
+ "library.episodeN": "第 {n} 集",
146
+ "library.offlineCopy": "来源没有回应,显示的是 {date} 保存的副本。",
147
+ "library.playFromFetch": "从这一集开始看(先下载它)",
148
+ "library.downloadAll": "全部下载(离线)",
149
+ "library.stopOffline": "不再离线保存",
150
+ "library.downloadAllQuestion": "还有 {n} 集,大约 {size}?",
151
+ "library.downloading": "下载中",
152
+ "library.queued": "等待下载",
153
+ "library.downloadFailed": "下载中断:{message}",
154
+ "library.inRoom": "房间里正在放",
155
+ "library.deletesOn": "{date} 删除",
156
+ "library.deletesIn": "{n} 天后删除",
157
+ "library.deletesInDay": "明天删除",
158
+ "library.deletesSoon": "即将删除",
159
+ "library.watchedAll": "已看完",
160
+ "library.startCountdown": "{n} 天后删除",
161
+ "library.restartCountdown": "重新计时({n} 天)",
162
+ "library.kept": "已保留",
163
+ "library.watchedCount": "看过 {n}/{total}",
164
+ "library.continueFrom": "从第 {n} 集继续",
165
+ "library.continueFromAt": "从第 {n} 集 {time} 继续",
166
+ "library.viewerStopped": "{name} 停在第 {n} 集 {time}",
167
+ "watch.watched": "看过",
168
+ "watch.stoppedAt": "停在 {time}",
169
+ "library.watch": "观看",
170
+ "library.continue": "继续看",
171
+ "library.more": "更多",
172
+ "library.rename": "重命名",
173
+ "library.keep": "保留",
174
+ "library.retry": "重新下载",
175
+ "library.stopDownload": "停止下载",
176
+ "library.inUseError": "有房间正在放这部,先关掉房间。",
177
+ "library.deleteQuestion": "删除({size})?",
178
+ "library.deleteEpisodeQuestion": "删除?",
179
+ "library.deleteEpisode": "删除 {episode}",
180
+ "library.episodesToggle": "剧集",
181
+ "library.playFrom": "从这一集开始看",
182
+ "library.free": "剩余 {size}",
183
+ "action.cancel": "取消",
184
+ "action.delete": "删除",
185
+ "action.save": "保存",
186
+ "room.back": "媒体",
187
+ "room.copy": "复制链接",
188
+ "room.copied": "链接已复制",
189
+ "room.close": "关闭房间",
190
+ "room.closeConfirm": "为所有人关闭?",
191
+ "room.closed": "这个房间已经关闭了。",
192
+ "room.episodes": "剧集",
193
+ "room.connecting": "正在连接…",
194
+ "room.reconnecting": "正在重新连接…",
195
+ "room.episodeN": "第 {n} 集",
196
+ "room.notCached": "还没下载,选它时会先下载",
197
+ "room.preparing": "正在准备…",
198
+ "room.preparingProgress": "正在准备… {n}%",
199
+ "room.failed": "没能准备好。",
200
+ "room.tapToJoin": "加入播放",
201
+ "room.tapToContinue": "点一下继续加载",
202
+ "room.you": "你",
203
+ "room.viewers": "正在看的人",
204
+ "room.waitingFor": "正在等 {names}…",
205
+ "room.loading": "正在加载…",
206
+ "room.wait.loading": "加载中",
207
+ "room.wait.ready": "准备好了",
208
+ "room.wait.skipped": "随后跟上",
209
+ "room.startWithout": "不等 {names},先开始",
210
+ "toast.play": "{name} 开始播放",
211
+ "toast.pause": "{name} 暂停在 {time}",
212
+ "toast.seek": "{name} 跳到了 {time}",
213
+ "toast.select": "{name} 切到了 {episode}",
214
+ "toast.ended": "下一集:{episode}",
215
+ "toast.rate": "{name} 把速度调成 {rate}×",
216
+ "toast.joined": "{name} 来了",
217
+ "toast.left": "{name} 离开了",
218
+ "toast.skip": "{name} 没等 {names} 先开始了",
219
+ "guest": "访客",
220
+ "assistant": "助手",
221
+ "source.name.fanqie": "番茄",
222
+ "source.name.bookfetch": "图书",
223
+ "link.placeholder": "粘贴视频或播放列表链接",
224
+ "link.go": "打开",
225
+ "source.name.link": "链接",
226
+ "meta.site": "网站",
227
+ "quality.label": "画质",
228
+ "quality.auto": "自动",
229
+ "quality.audio": "仅音频",
230
+ "quality.height": "{n}p",
231
+ "error.blocked": "网站拒绝了这次请求,可能屏蔽了媒体中心所用的网络,稍后再试。",
232
+ "error.sign_in": "这个视频需要登录账号才能看,请让管理媒体中心的人添加一个。",
233
+ "error.not_found": "这个地址没有可播放的内容,检查一下链接。",
234
+ "error.proxy_down": "这个网站要走的线路现在不通,过一会儿再试。",
235
+ "error.failed": "网站没给出这个视频,稍后再试。",
236
+ "error.status": "服务器没能完成(HTTP {status}),再试一次。",
237
+ "error.network": "连不上服务器,检查网络后再试。",
238
+ "progress.downloading": "下载中",
239
+ "progress.downloadingPercent": "下载中 {n}%",
240
+ "progress.of": "{done} / {total}",
241
+ "progress.speed": "{speed}/秒",
242
+ "progress.left": "还剩 {time}",
243
+ "link.account": "使用 {name} 的账号",
244
+ "link.accountHint": "读取这个网站时用的账号,能选哪些画质由它决定",
245
+ "caption.auto": "{name}(自动)",
246
+ "room.watchTogether": "一起看",
247
+ "room.togetherCopied": "链接已复制,打开链接的人会从这里和你一起看",
248
+ "continue.inRoomOne": "{names}正在房间里",
249
+ "continue.inRoomMany": "{names}正在房间里",
250
+ "continue.episode": "第 {n} 集",
251
+ "continue.score": "★ {score}",
252
+ "continue.from": "来自{source}",
253
+ "continue.watched.one": "已看 {n} 集",
254
+ "continue.watched.other": "已看 {n} 集",
255
+ "continue.onDisk.one": "后 {n} 集已下载",
256
+ "continue.onDisk.other": "后 {n} 集已下载",
257
+ "continue.join": "加入{names} · 第 {n} 集",
258
+ "continue.continue": "继续 · 第 {n} 集",
259
+ "continue.recap": "前情 · 无剧透",
260
+ "ratings.heading": "看得怎么样?",
261
+ "ratings.hint": "点一下,记进观看记录",
262
+ "ratings.finished": "{when}看完",
263
+ "ratings.removed": "{when}从媒体库移除",
264
+ "ratings.loved": "很喜欢",
265
+ "ratings.fine": "还行",
266
+ "ratings.not-for-me": "不太喜欢",
267
+ "ratings.unfinished": "没看完",
268
+ "picks.heading": "推荐",
269
+ "picks.hint": "每部都写了推荐理由",
270
+ "continue.joinOne": "加入{names}",
271
+ "continue.continueAt": "从 {time} 继续",
272
+ "continue.play": "播放",
273
+ "library.continueAt": "从 {time} 继续",
274
+ "library.viewerStoppedAt": "{name}看到 {time}"
275
+ }
276
+ }
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "@soffits/dsh-media-hub",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "A media hub for DeepSeek Harness: search shows, novels, ebooks and papers across sources, watch together in sync, and download books in the format you want onto your own shelf.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Sakina",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/soffits/dsh-media-hub.git"
11
+ },
12
+ "keywords": [
13
+ "dsh",
14
+ "dsh-plugin",
15
+ "deepseek-harness",
16
+ "watch-together",
17
+ "video",
18
+ "sync",
19
+ "ebooks",
20
+ "epub",
21
+ "novels",
22
+ "books"
23
+ ],
24
+ "main": "./dist/index.js",
25
+ "exports": {
26
+ ".": "./dist/index.js",
27
+ "./tools": "./dist/tools.js",
28
+ "./client": "./client.js",
29
+ "./locale/*.json": "./locale/*.json",
30
+ "./icon": "./icon.svg",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "client.js",
35
+ "web/*.js",
36
+ "web/*.css",
37
+ "cordis.patch.yml",
38
+ "locale/*.json",
39
+ "icon.svg",
40
+ "README.md",
41
+ "CHANGELOG.md",
42
+ "LICENSE",
43
+ "dist/*",
44
+ "src/sync.js",
45
+ "src/formats.js",
46
+ "src/i18n.js",
47
+ "src/captions.js"
48
+ ],
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ },
53
+ "client": {
54
+ "platform": "web",
55
+ "immediately": true,
56
+ "inject": [
57
+ "@deepseek-ai/dsh-client-locale",
58
+ "@soffits/dsh-ui-actions",
59
+ "@soffits/dsh-ui-kit",
60
+ "@deepseek-ai/dsh-client-ui-layout",
61
+ "@deepseek-ai/dsh-client-ui-sidebar"
62
+ ]
63
+ }
64
+ },
65
+ "engines": {
66
+ "node": ">=22"
67
+ },
68
+ "scripts": {
69
+ "check": "for f in index.js tools.js client.js scripts/*.mjs src/*.js src/sources/*.js web/*.js test/*.js test/fixtures/*.mjs; do node --check \"$f\" || exit 1; done",
70
+ "test": "node --import ./test/fixtures/web-modules.mjs --test test/*.test.js",
71
+ "test:browsers": "node scripts/build.mjs && node test/browsers/run.js",
72
+ "build": "node scripts/build.mjs"
73
+ },
74
+ "devDependencies": {
75
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.1",
76
+ "@deepseek-ai/schemastery": "^3.19.0",
77
+ "@soffits/dsh-ui-kit": "0.2.0",
78
+ "esbuild": "^0.28.2",
79
+ "hls.js": "^1.7.4",
80
+ "https-proxy-agent": "^9.1.0",
81
+ "playwright-core": "^1.65.1",
82
+ "socks-proxy-agent": "^10.1.0",
83
+ "ws": "^8.23.0"
84
+ }
85
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Captions for any source: which language a track is in, which tracks are
3
+ * worth fetching, and which one a viewer starts with. Pure; runs in Node and
4
+ * in the browser (served as `captions.js`).
5
+ *
6
+ * A track is known by its label: a language tag, then optional marks, as in
7
+ * `ep1.zh-Hans.auto.vtt` (label `zh-Hans.auto`). `auto` marks a track made by
8
+ * a machine (speech recognition or translation), `original` one in the
9
+ * video's own language. Labels that name no language (`forced`, a site's own
10
+ * code) stay as they are and are never chosen for anyone.
11
+ */
12
+ import { BASE, bestTag } from './i18n.js'
13
+
14
+ export const MARKS = Object.freeze(['auto', 'original'])
15
+
16
+ const known = new Intl.DisplayNames([BASE], { type: 'language', fallback: 'none' })
17
+
18
+ /** The language a tag names (`jpn` → `ja`, `en-orig` → `en`), or null when it names none. */
19
+ export function captionLanguage(tag) {
20
+ try {
21
+ const { language } = new Intl.Locale(tag)
22
+ return language === 'und' || known.of(language) === undefined ? null : language
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ /** A track's label from its tag and marks. */
29
+ export const captionLabel = ({ tag, auto = false, original = false }) => [tag, ...(auto ? ['auto'] : []), ...(original ? ['original'] : [])].join('.')
30
+
31
+ /** What a label says: its tag, the language it names (or null), and its marks. */
32
+ export function parseCaption(label) {
33
+ const parts = String(label ?? '').split('.')
34
+ const marks = new Set()
35
+ while (parts.length > 1 && MARKS.includes(parts.at(-1))) marks.add(parts.pop())
36
+ const tag = parts.join('.')
37
+ return { tag, language: captionLanguage(tag), auto: marks.has('auto'), original: marks.has('original') }
38
+ }
39
+
40
+ /**
41
+ * The track a viewer starts with, as an index into `labels`, or -1 for none: one in the viewer's
42
+ * language (a person's own over a machine's), else one in the video's own language that no machine
43
+ * translated, else none. A machine translation into a third language is never started.
44
+ */
45
+ export function defaultCaption(labels, viewer) {
46
+ const tracks = labels.map(parseCaption)
47
+ const wanted = captionLanguage(viewer)
48
+ const pickFrom = (list) => {
49
+ if (list.length === 0) return -1
50
+ const tag = bestTag(list.map(track => track.tag), viewer) ?? list[0].tag
51
+ return tracks.indexOf(list.find(track => track.tag === tag))
52
+ }
53
+ if (wanted !== null) {
54
+ const mine = tracks.filter(track => track.language === wanted)
55
+ const at = pickFrom(mine.filter(track => !track.auto))
56
+ if (at >= 0) return at
57
+ const machine = pickFrom(mine)
58
+ if (machine >= 0) return machine
59
+ }
60
+ const own = tracks.filter(track => track.original && track.language !== null)
61
+ return tracks.indexOf(own.find(track => !track.auto) ?? own[0])
62
+ }
63
+
64
+ /** A track's name for the picker: its language in that language (日本語, English), else its label as it is. */
65
+ export function captionName(label) {
66
+ const track = parseCaption(label)
67
+ if (track.language === null) return track.tag
68
+ try {
69
+ return new Intl.DisplayNames([track.tag], { type: 'language', fallback: 'none' }).of(track.tag)
70
+ ?? new Intl.DisplayNames([track.language], { type: 'language', fallback: 'none' }).of(track.language) ?? track.tag
71
+ } catch {
72
+ return track.tag
73
+ }
74
+ }
package/src/formats.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Book formats a converter can write and read, and what a work is offered
3
+ * in (pure; also served to the page as /media-hub/web/formats.js).
4
+ */
5
+
6
+ /** What a converter (Calibre's ebook-convert) can write, and the source formats it best starts from, most faithful first. */
7
+ export const CONVERT_TARGETS = Object.freeze(['epub', 'azw3', 'mobi', 'pdf', 'txt', 'docx', 'fb2'])
8
+ export const CONVERT_INPUTS = Object.freeze(['epub', 'azw3', 'mobi', 'fb2', 'docx', 'txt', 'pdf'])
9
+
10
+ /**
11
+ * The formats a work is offered in: the source's own, then (with a converter) every target it can be converted to.
12
+ * @returns {{ format: string, bytes: number | null, converted: boolean }[]}
13
+ */
14
+ export function offeredFormats(formats, canConvert) {
15
+ const own = (formats ?? []).map(entry => ({ format: entry.format, bytes: entry.bytes ?? null, converted: false }))
16
+ if (!canConvert || !own.some(entry => CONVERT_INPUTS.includes(entry.format))) return own
17
+ const have = new Set(own.map(entry => entry.format))
18
+ return [...own, ...CONVERT_TARGETS.filter(format => !have.has(format)).map(format => ({ format, bytes: null, converted: true }))]
19
+ }
20
+
21
+ /** The source format to convert from: the most faithful one the work has. */
22
+ export function convertBase(formats) {
23
+ const have = new Set((formats ?? []).map(entry => entry.format))
24
+ return CONVERT_INPUTS.find(format => have.has(format)) ?? null
25
+ }
package/src/i18n.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Text for people in their language, without naming any language in code: words live in
3
+ * `locale/<tag>.json`, one file per language, and a text that config gives per language is a
4
+ * `{ <tag>: text }` map. Pure; runs in Node and in the browser (served as `i18n.js`).
5
+ */
6
+
7
+ /** The language every lookup ends at, and the table every other locale file is checked against. */
8
+ export const BASE = 'en'
9
+
10
+ /** A BCP 47-style tag as DSH accepts it (`en`, `zh`, `pt-BR`, `zh-Hant-TW`). */
11
+ export const TAG = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i
12
+
13
+ /** The tags to try for `tag`, most specific first: the tag, each shorter prefix, then the base. */
14
+ export function chain(tag) {
15
+ const parts = String(tag ?? '').toLowerCase().split('-').filter(Boolean)
16
+ const tags = parts.map((_, i) => parts.slice(0, parts.length - i).join('-'))
17
+ return tags.includes(BASE) ? tags : [...tags, BASE]
18
+ }
19
+
20
+ /**
21
+ * The text for `tag` from a string or a `{ <tag>: text }` map: the exact tag, then its primary
22
+ * subtag, then the base language, else the map's first text. Tags compare case-insensitively.
23
+ */
24
+ export function pick(value, tag) {
25
+ if (typeof value === 'string') return value
26
+ if (value === null || typeof value !== 'object') return ''
27
+ const byTag = new Map(Object.entries(value).map(([key, text]) => [key.toLowerCase(), text]))
28
+ for (const candidate of chain(tag)) {
29
+ const text = byTag.get(candidate)
30
+ if (typeof text === 'string' && text !== '') return text
31
+ }
32
+ return Object.values(value).find(text => typeof text === 'string' && text !== '') ?? ''
33
+ }
34
+
35
+ /**
36
+ * The languages a language filter offers, one per primary subtag: the viewer's own, the one picked,
37
+ * then every language the results are in. Taken from the data, so no language is listed in code.
38
+ */
39
+ export function languageChoices(viewer, results, picked = '') {
40
+ const codes = [viewer, picked, ...results.map(result => result.language)]
41
+ .filter(code => typeof code === 'string' && code !== '')
42
+ .map(code => chain(code).at(-2) ?? BASE)
43
+ return [...new Set(codes)]
44
+ }
45
+
46
+ /** A tag's likely full form (language, script, region), or null for what is not a tag. */
47
+ export function localeOf(tag) {
48
+ try {
49
+ return new Intl.Locale(tag).maximize()
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+
55
+ /** The listed tag that best stands for `wanted`: the same tag, else the same language and script, else the same language. */
56
+ export function bestTag(tags, wanted) {
57
+ if (!wanted) return null
58
+ const target = localeOf(wanted)
59
+ let best = null
60
+ let score = 0
61
+ for (const tag of tags) {
62
+ const locale = localeOf(tag)
63
+ const value = tag.toLowerCase() === wanted.toLowerCase() ? 3
64
+ : locale && target && locale.language === target.language && locale.script === target.script ? 2
65
+ : locale && target && locale.language === target.language ? 1 : 0
66
+ if (value > score) [best, score] = [tag, value]
67
+ }
68
+ return best
69
+ }
package/src/sync.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Sync math shared by the server, the browser player and the tests. Pure:
3
+ * no I/O, no timers, no Node or DOM APIs.
4
+ *
5
+ * Times are milliseconds on the server clock unless named otherwise;
6
+ * positions are seconds of media time.
7
+ */
8
+
9
+ /** Drift bands, in seconds. */
10
+ export const DRIFT = Object.freeze({
11
+ /** Below this the players count as together. */
12
+ ignore: 0.3,
13
+ /** Above this a player jumps instead of catching up by rate. */
14
+ seek: 2,
15
+ /** A player already catching up by rate keeps at it until this close. */
16
+ settle: 0.1,
17
+ /** Rate change while catching up, as a fraction of the room's rate. */
18
+ nudge: 0.05,
19
+ })
20
+
21
+ /**
22
+ * Where the room's media is at a server time.
23
+ * @param {{ playing: boolean, position: number, rate: number, updatedAt: number, duration?: number | null }} state
24
+ * @param {number} serverNow
25
+ * @returns {number} seconds
26
+ */
27
+ export function expectedPosition(state, serverNow) {
28
+ let position = state.position
29
+ if (state.playing) position += Math.max(0, serverNow - state.updatedAt) / 1000 * state.rate
30
+ if (typeof state.duration === 'number' && state.duration > 0) position = Math.min(position, state.duration)
31
+ return Math.max(0, position)
32
+ }
33
+
34
+ /**
35
+ * Clock offset from ping samples, NTP style: the sample with the shortest
36
+ * round trip has the smallest error, so its offset is taken.
37
+ * @param {{ sent: number, received: number, server: number }[]} samples - client send and receive times (client clock) and the server time in the reply.
38
+ * @returns {{ offset: number, rtt: number } | null} offset to add to the client clock to get server time
39
+ */
40
+ export function clockOffset(samples) {
41
+ let best = null
42
+ for (const { sent, received, server } of samples) {
43
+ const rtt = received - sent
44
+ if (!(rtt >= 0)) continue
45
+ if (best === null || rtt < best.rtt) best = { offset: server - (sent + received) / 2, rtt }
46
+ }
47
+ return best
48
+ }
49
+
50
+ /**
51
+ * What a player should do about its drift from the room.
52
+ *
53
+ * @param {object} input
54
+ * @param {number} input.local - the player's position, seconds
55
+ * @param {number} input.expected - the room's position, seconds
56
+ * @param {number} input.rate - the room's rate
57
+ * @param {boolean} [input.nudging=false] - whether the player is catching up by rate now
58
+ * @returns {{ action: 'none', rate: number, drift: number } | { action: 'rate', rate: number, drift: number } | { action: 'seek', to: number, rate: number, drift: number }}
59
+ * drift is local minus expected (positive: ahead)
60
+ */
61
+ export function correction({ local, expected, rate, nudging = false }) {
62
+ const drift = local - expected
63
+ const size = Math.abs(drift)
64
+ if (size > DRIFT.seek) return { action: 'seek', to: expected, rate, drift }
65
+ if (size >= DRIFT.ignore || (nudging && size > DRIFT.settle)) {
66
+ const factor = drift > 0 ? 1 - DRIFT.nudge : 1 + DRIFT.nudge
67
+ return { action: 'rate', rate: rate * factor, drift }
68
+ }
69
+ return { action: 'none', rate, drift }
70
+ }
71
+
72
+ /** The next episode starts loading this long before the current one ends (seconds). */
73
+ export const PRELOAD_BEFORE_END_S = 30
74
+ /** Episodes shorter than this preload the next one from the start. */
75
+ export const SHORT_EPISODE_S = 120
76
+
77
+ /**
78
+ * Whether the next episode should be loading in the background by now.
79
+ * @param {{ duration: number | null, position: number }} state - the current episode's length and position (seconds)
80
+ */
81
+ export function preloadDue({ duration, position }) {
82
+ if (!Number.isFinite(duration) || duration <= 0) return false
83
+ return duration <= SHORT_EPISODE_S || duration - position <= PRELOAD_BEFORE_END_S
84
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * About a show in a room: its cover, score, popularity, tags and everything
3
+ * the source gave (web/details.js), kept with the show so no request goes to
4
+ * the source. A related work opens in Discover in a new tab, so the room is
5
+ * never left by accident.
6
+ */
7
+ import { Cover, WorkDetails, glance } from './details.js'
8
+ import { writeNav } from './nav.js'
9
+ import { FollowButton } from './follow.js'
10
+ import { fill, h } from './ui.js'
11
+
12
+ /** The Discover URL of a work. */
13
+ export const discoverLink = (source, work) => `${location.origin}${location.pathname}${writeNav('', { tab: 'discover', source, kind: work.kind ?? null, work: work.id })}`
14
+
15
+ /** The next season of a work: a related season whose title extends this one's ("X" then "X第二季"). */
16
+ export function nextSeason(work) {
17
+ if (!work?.title) return null
18
+ return (work.related ?? []).find(other => other.relation === 'season' && other.title !== work.title && other.title.startsWith(work.title)) ?? null
19
+ }
20
+
21
+ export function About({ t, work, source, workId }) {
22
+ return h('div', { className: 'vsync-about' },
23
+ h('div', { className: 'vsync-aboutHead' },
24
+ h(Cover, { result: work }),
25
+ h('div', { className: 'vsync-aboutTitle' },
26
+ h('strong', null, work.title),
27
+ work.score && h('span', { className: 'vsync-score' }, fill(t('search.score'), { score: work.score.toFixed(1) })),
28
+ h('span', { className: 'vsync-rowMeta' }, glance(t, work).map((part, n) => h('span', { key: n }, part))),
29
+ work.tags?.length > 0 && h('span', { className: 'vsync-tags' }, work.tags.slice(0, 6).map(tag => h('span', { key: tag, className: 'vsync-tag' }, tag))),
30
+ h('span', { className: 'vsync-actions' }, h(FollowButton, { t, source, work: { id: workId } })))),
31
+ h(WorkDetails, { t, info: work, source, onFocus: other => window.open(discoverLink(source, other), '_blank', 'noopener') }))
32
+ }