@nitrimandylis/flick 0.0.0-stage → 0.1.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/dist/flick.js ADDED
@@ -0,0 +1,3597 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.tsx
4
+ import { render } from "ink";
5
+ import { realpathSync } from "node:fs";
6
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
7
+
8
+ // src/couch.ts
9
+ import { randomBytes } from "node:crypto";
10
+
11
+ // src/room.ts
12
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
13
+ import { createServer } from "node:http";
14
+ import { dirname, extname, join as join2, normalize } from "node:path";
15
+ import { Readable } from "node:stream";
16
+ import { fileURLToPath } from "node:url";
17
+ import { WebSocketServer } from "ws";
18
+
19
+ // src/titles.ts
20
+ var IMDB_SUGGEST = "https://v2.sg.media-imdb.com/suggestion";
21
+ var IMDB_GRAPHQL = "https://api.graphql.imdb.com/";
22
+ var UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36";
23
+ var KINDS = new Set(["movie", "tvSeries", "tvMovie", "tvMiniSeries"]);
24
+ function isSeries(t) {
25
+ return t.kind === "tvSeries" || t.kind === "tvMiniSeries";
26
+ }
27
+ function parseSuggestions(list) {
28
+ return (list ?? []).filter((x) => typeof x?.id === "string" && x.id.startsWith("tt") && KINDS.has(x.qid)).map((x) => ({
29
+ id: x.id,
30
+ name: x.l ?? "",
31
+ year: typeof x.y === "number" ? x.y : null,
32
+ kind: x.qid,
33
+ poster: x.i?.imageUrl ?? "",
34
+ cast: typeof x.s === "string" ? x.s : ""
35
+ }));
36
+ }
37
+ async function searchTitles(query, signal) {
38
+ const q = query.toLowerCase().trim();
39
+ if (!q)
40
+ return [];
41
+ const first = q.replace(/[^a-z0-9]/g, "")[0] ?? "x";
42
+ try {
43
+ const res = await fetch(`${IMDB_SUGGEST}/${first}/${encodeURIComponent(q)}.json`, {
44
+ headers: { "User-Agent": UA },
45
+ signal
46
+ });
47
+ if (!res.ok)
48
+ return [];
49
+ return parseSuggestions((await res.json()).d ?? []);
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+ async function graphql(query) {
55
+ try {
56
+ const res = await fetch(IMDB_GRAPHQL, {
57
+ method: "POST",
58
+ headers: {
59
+ "Content-Type": "application/json",
60
+ "User-Agent": UA,
61
+ "x-imdb-client-name": "imdb-web-next",
62
+ Origin: "https://www.imdb.com"
63
+ },
64
+ body: JSON.stringify({ query })
65
+ });
66
+ return res.ok ? await res.json() : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ function parseTrending(json) {
72
+ const edges = json?.data?.advancedTitleSearch?.edges ?? [];
73
+ return edges.map((e) => e.node?.title).filter((t) => typeof t?.id === "string" && t.id.startsWith("tt")).map((t) => ({
74
+ id: t.id,
75
+ name: t.titleText?.text ?? "",
76
+ year: t.releaseYear?.year ?? null,
77
+ kind: t.titleType?.id ?? "",
78
+ poster: t.primaryImage?.url ?? "",
79
+ cast: ""
80
+ }));
81
+ }
82
+ async function trending(kind) {
83
+ const json = await graphql(`query { advancedTitleSearch(first: 20, sort: {sortBy: POPULARITY, sortOrder: ASC}, constraints: {titleTypeConstraint: {anyTitleTypeIds: ["${kind}"]}}) { edges { node { title { id titleText { text } releaseYear { year } titleType { id } primaryImage { url } } } } } }`);
84
+ return parseTrending(json);
85
+ }
86
+ function parseDetails(json) {
87
+ const t = json?.data?.title;
88
+ const people = (category) => (t?.principalCredits ?? []).find((c) => c.category?.id === category)?.credits?.map((c) => c.name?.nameText?.text).filter(Boolean) ?? [];
89
+ return {
90
+ plot: t?.plot?.plotText?.plainText ?? "",
91
+ minutes: t?.runtime?.seconds ? Math.round(t.runtime.seconds / 60) : 0,
92
+ genres: (t?.genres?.genres ?? []).map((g) => g.text),
93
+ directors: people("director"),
94
+ cast: people("cast")
95
+ };
96
+ }
97
+ async function details(id) {
98
+ return parseDetails(await graphql(`query { title(id: "${id}") { runtime { seconds } plot { plotText { plainText } } genres { genres { text } } principalCredits { category { id } credits(limit: 3) { name { nameText { text } } } } } }`));
99
+ }
100
+ function parseSeasons(json) {
101
+ return (json?.data?.title?.episodes?.seasons ?? []).map((s) => s.number).filter((n) => typeof n === "number").sort((a, b) => a - b);
102
+ }
103
+ function parseEpisodes(json) {
104
+ return (json?.data?.title?.episodes?.episodes?.edges ?? []).map((e) => {
105
+ const node = e.node ?? {};
106
+ const at = node.series?.episodeNumber ?? {};
107
+ const d = node.releaseDate;
108
+ return {
109
+ season: at.seasonNumber ?? 0,
110
+ number: at.episodeNumber ?? 0,
111
+ name: node.titleText?.text ?? "",
112
+ plot: node.plot?.plotText?.plainText ?? "",
113
+ date: d?.year ? [d.year, d.month, d.day].filter(Boolean).map((n) => String(n).padStart(2, "0")).join("-") : "",
114
+ minutes: node.runtime?.seconds ? Math.round(node.runtime.seconds / 60) : 0
115
+ };
116
+ }).filter((e) => e.number > 0).sort((a, b) => a.number - b.number);
117
+ }
118
+ async function seasons(id) {
119
+ return parseSeasons(await graphql(`query { title(id: "${id}") { episodes { seasons { number } } } }`));
120
+ }
121
+ async function episodes(id, season) {
122
+ return parseEpisodes(await graphql(`query { title(id: "${id}") { episodes { episodes(first: 100, filter: {includeSeasons: ["${season}"]}) { edges { node { titleText { text } plot { plotText { plainText } } releaseDate { year month day } runtime { seconds } series { episodeNumber { seasonNumber episodeNumber } } } } } } } }`));
123
+ }
124
+ function sxxeyy(season, episode) {
125
+ return `S${String(season).padStart(2, "0")}E${String(episode).padStart(2, "0")}`;
126
+ }
127
+
128
+ // src/details.ts
129
+ var cache = new Map;
130
+ async function filmDetails(imdb) {
131
+ const known = cache.get(imdb);
132
+ if (known)
133
+ return known;
134
+ const out = { imdb, title: null, year: null, runtime: null, genres: [], tagline: null, plot: null, poster: null, directors: [], writers: [], stars: [], about: null };
135
+ let wiki = null;
136
+ try {
137
+ const sparql = `SELECT ?article (MIN(YEAR(?date)) AS ?year) (SAMPLE(?mins) AS ?runtime)
138
+ (GROUP_CONCAT(DISTINCT ?dirLabel; separator="|") AS ?dirs)
139
+ (GROUP_CONCAT(DISTINCT ?genreLabel; separator="|") AS ?genres) WHERE {
140
+ ?f wdt:P345 "${imdb}".
141
+ OPTIONAL { ?article schema:about ?f; schema:isPartOf <https://en.wikipedia.org/> }
142
+ OPTIONAL { ?f wdt:P577 ?date }
143
+ OPTIONAL { ?f wdt:P2047 ?mins }
144
+ OPTIONAL { ?f wdt:P57 ?dir. ?dir rdfs:label ?dirLabel. FILTER(LANG(?dirLabel) = "en") }
145
+ OPTIONAL { ?f wdt:P136 ?genre. ?genre rdfs:label ?genreLabel. FILTER(LANG(?genreLabel) = "en") }
146
+ } GROUP BY ?article LIMIT 1`;
147
+ const res = await fetch(`https://query.wikidata.org/sparql?format=json&query=${encodeURIComponent(sparql)}`, {
148
+ headers: { "User-Agent": "flick (https://github.com/nitrimandylis/flick)" },
149
+ signal: AbortSignal.timeout(1e4)
150
+ });
151
+ const row = (await res.json()).results.bindings[0];
152
+ if (row) {
153
+ wiki = row.article?.value ?? null;
154
+ out.year = row.year ? Number(row.year.value) : null;
155
+ out.runtime = row.runtime ? Number(row.runtime.value) * 60 : null;
156
+ out.directors = row.dirs?.value ? row.dirs.value.split("|") : [];
157
+ out.genres = ((row.genres?.value) ? row.genres.value.split("|") : []).slice(0, 3).map((g) => g.replace(/ film$/, "")).map((g) => g.charAt(0).toUpperCase() + g.slice(1));
158
+ }
159
+ } catch {}
160
+ try {
161
+ const query = `{ title(id: "${imdb}") { titleText { text } releaseYear { year } runtime { seconds } plot { plotText { plainText } } primaryImage { url } genres { genres { text } } taglines(first: 1) { edges { node { text } } } principalCredits { category { text } credits(limit: 4) { name { nameText { text } } } } } }`;
162
+ const res = await fetch("https://api.graphql.imdb.com/", {
163
+ method: "POST",
164
+ headers: { "content-type": "application/json", "user-agent": UA, "x-imdb-client-name": "imdb-web-next", origin: "https://www.imdb.com" },
165
+ body: JSON.stringify({ query }),
166
+ signal: AbortSignal.timeout(1e4)
167
+ });
168
+ const t = (await res.json()).data?.title;
169
+ if (t) {
170
+ out.title = t.titleText?.text ?? out.title;
171
+ out.year = t.releaseYear?.year ?? out.year;
172
+ out.runtime = t.runtime?.seconds ?? out.runtime;
173
+ out.plot = t.plot?.plotText?.plainText ?? null;
174
+ out.poster = t.primaryImage?.url ?? null;
175
+ if (t.genres?.genres?.length)
176
+ out.genres = t.genres.genres.map((g) => g.text);
177
+ out.tagline = t.taglines?.edges?.[0]?.node?.text ?? null;
178
+ for (const group of t.principalCredits ?? []) {
179
+ const names = group.credits.map((c) => c.name.nameText.text);
180
+ const category = group.category.text;
181
+ if (category.startsWith("Director"))
182
+ out.directors = names;
183
+ else if (category.startsWith("Writer"))
184
+ out.writers = names;
185
+ else if (category.startsWith("Star"))
186
+ out.stars = names;
187
+ }
188
+ }
189
+ } catch {}
190
+ if (wiki) {
191
+ try {
192
+ const page = wiki.split("/wiki/")[1];
193
+ const res = await fetch(`https://en.wikipedia.org/api/rest_v1/page/summary/${page}`, {
194
+ headers: { "User-Agent": "flick (https://github.com/nitrimandylis/flick)" },
195
+ signal: AbortSignal.timeout(1e4)
196
+ });
197
+ const w = await res.json();
198
+ out.about = w.extract ?? null;
199
+ out.title ??= w.title ?? null;
200
+ out.poster ??= w.originalimage?.source ?? null;
201
+ } catch {}
202
+ }
203
+ if (out.title)
204
+ cache.set(imdb, out);
205
+ return out;
206
+ }
207
+
208
+ // src/store.ts
209
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
210
+ import { homedir } from "node:os";
211
+ import { join } from "node:path";
212
+ var CONFIG_DIR = join(homedir(), ".config", "flick");
213
+ var CACHE_DIR = join(homedir(), ".cache", "flick");
214
+ var FILMS_DIR = join(CACHE_DIR, "films");
215
+ var SUBS_DIR = join(CACHE_DIR, "subs");
216
+ var CONFIG_PATH = join(CONFIG_DIR, "config.json");
217
+ var HISTORY_PATH = join(CONFIG_DIR, "history.json");
218
+ function readJson(path, fallback) {
219
+ try {
220
+ return JSON.parse(readFileSync(path, "utf-8"));
221
+ } catch {
222
+ return fallback;
223
+ }
224
+ }
225
+ function writeJson(path, value) {
226
+ mkdirSync(CONFIG_DIR, { recursive: true });
227
+ writeFileSync(path, JSON.stringify(value, null, 2) + `
228
+ `);
229
+ }
230
+ function loadConfig() {
231
+ return readJson(CONFIG_PATH, {});
232
+ }
233
+ function saveConfig(config) {
234
+ writeJson(CONFIG_PATH, config);
235
+ }
236
+ var HISTORY_CAP = 40;
237
+ function loadHistory() {
238
+ const list = readJson(HISTORY_PATH, []);
239
+ return Array.isArray(list) ? list : [];
240
+ }
241
+ function recordPlay(entry, episodeTag) {
242
+ const list = loadHistory();
243
+ const old = list.find((w) => w.id === entry.id);
244
+ const seen = new Set(old?.seen ?? []);
245
+ if (episodeTag)
246
+ seen.add(episodeTag);
247
+ const rest = list.filter((w) => w.id !== entry.id);
248
+ rest.unshift({ ...entry, seen: [...seen], at: Date.now() });
249
+ writeJson(HISTORY_PATH, rest.slice(0, HISTORY_CAP));
250
+ }
251
+ function folderSize(path) {
252
+ let total = 0;
253
+ for (const name of readdirSync(path)) {
254
+ const full = join(path, name);
255
+ const info = statSync(full);
256
+ total += info.isDirectory() ? folderSize(full) : info.size;
257
+ }
258
+ return total;
259
+ }
260
+ function touchFilm(folderName) {
261
+ const path = join(FILMS_DIR, folderName);
262
+ if (!existsSync(path))
263
+ return;
264
+ const now = new Date;
265
+ utimesSync(path, now, now);
266
+ }
267
+ function trimCache(capGB, keep, dir = FILMS_DIR) {
268
+ if (!existsSync(dir))
269
+ return [];
270
+ const cap = capGB * 1024 ** 3;
271
+ const films = readdirSync(dir).map((name) => {
272
+ const path = join(dir, name);
273
+ const info = statSync(path);
274
+ return { name, path, at: info.mtimeMs, bytes: info.isDirectory() ? folderSize(path) : info.size };
275
+ }).sort((a, b) => a.at - b.at);
276
+ let total = films.reduce((sum, f) => sum + f.bytes, 0);
277
+ const removed = [];
278
+ for (const film of films) {
279
+ if (total <= cap)
280
+ break;
281
+ if (film.name === keep)
282
+ continue;
283
+ rmSync(film.path, { recursive: true, force: true });
284
+ total -= film.bytes;
285
+ removed.push(film.name);
286
+ }
287
+ return removed;
288
+ }
289
+
290
+ // src/room.ts
291
+ var ROOMS_DIR = join2(CONFIG_DIR, "rooms");
292
+ var ASSETS = join2(dirname(fileURLToPath(import.meta.url)), "..", "room");
293
+ var TYPES = {
294
+ ".html": "text/html; charset=utf-8",
295
+ ".js": "text/javascript; charset=utf-8",
296
+ ".css": "text/css; charset=utf-8",
297
+ ".svg": "image/svg+xml",
298
+ ".woff2": "font/woff2"
299
+ };
300
+ function emptyState() {
301
+ return { film: null, src: null, playing: false, time: 0, at: 0, ended: false, ratings: {}, last: null };
302
+ }
303
+ function currentTime(s, now = Date.now()) {
304
+ return s.playing ? s.time + (now - s.at) / 1000 : s.time;
305
+ }
306
+ function applySet(s, playing, time, now = Date.now()) {
307
+ if (!s.film || s.ended)
308
+ return null;
309
+ if (playing === s.playing && Math.abs(time - currentTime(s, now)) < 2)
310
+ return null;
311
+ const action = playing !== s.playing ? playing ? "play" : "pause" : "seek";
312
+ s.playing = playing;
313
+ s.time = Math.max(0, time);
314
+ s.at = now;
315
+ return action;
316
+ }
317
+ function crossedToggle(last, by, seen) {
318
+ return last !== null && last.by !== by && seen < last.rev;
319
+ }
320
+
321
+ class Room {
322
+ id;
323
+ state;
324
+ seats = new Map;
325
+ sockets = new Set;
326
+ lastPos = null;
327
+ lastToggle = null;
328
+ rev = 0;
329
+ filmUrl = null;
330
+ vtt = null;
331
+ server;
332
+ sentBytes = 0;
333
+ lastChange = null;
334
+ onChange = () => {};
335
+ statePath;
336
+ constructor(id) {
337
+ this.id = id;
338
+ this.statePath = join2(ROOMS_DIR, `${id}.json`);
339
+ const saved = existsSync2(this.statePath) ? JSON.parse(readFileSync2(this.statePath, "utf-8")) : {};
340
+ this.state = { ...emptyState(), ...saved, src: null, playing: false };
341
+ const wss = new WebSocketServer({ noServer: true });
342
+ this.server = createServer((req, res) => this.http(req, res));
343
+ this.server.on("upgrade", (req, socket, head) => {
344
+ if (req.url !== `/r/${this.id}/ws`)
345
+ return socket.destroy();
346
+ wss.handleUpgrade(req, socket, head, (ws) => this.connect(ws));
347
+ });
348
+ }
349
+ listen(port = 0) {
350
+ return new Promise((resolve) => {
351
+ this.server.listen(port, "127.0.0.1", () => {
352
+ const address = this.server.address();
353
+ resolve(address && typeof address === "object" ? address.port : 0);
354
+ });
355
+ });
356
+ }
357
+ close() {
358
+ for (const ws of this.sockets)
359
+ ws.close();
360
+ this.server.close();
361
+ }
362
+ people() {
363
+ return [...this.seats.values()].map((s) => s.name);
364
+ }
365
+ seated() {
366
+ return [...this.seats.values()];
367
+ }
368
+ setFilm(film, filmUrl, vtt) {
369
+ const s = this.state;
370
+ this.filmUrl = filmUrl;
371
+ this.vtt = vtt;
372
+ const key = Date.now().toString(36);
373
+ s.src = { url: `/r/${this.id}/film.mp4?v=${key}`, subs: vtt ? `/r/${this.id}/subs.vtt?v=${key}` : null };
374
+ let action = "source";
375
+ if (!s.film || s.film.id !== film.id || s.ended) {
376
+ s.film = film;
377
+ s.playing = false;
378
+ s.time = 0;
379
+ s.at = Date.now();
380
+ s.ended = false;
381
+ s.ratings = {};
382
+ action = "load";
383
+ }
384
+ this.save();
385
+ this.broadcast(this.stateMessage(action, null));
386
+ }
387
+ stopFilm() {
388
+ const s = this.state;
389
+ this.filmUrl = null;
390
+ if (!s.src)
391
+ return;
392
+ s.src = null;
393
+ if (s.playing) {
394
+ s.time = this.lastPos ?? currentTime(s);
395
+ s.playing = false;
396
+ s.at = Date.now();
397
+ }
398
+ this.save();
399
+ this.broadcast(this.stateMessage("source-off", null));
400
+ }
401
+ connect(ws) {
402
+ this.sockets.add(ws);
403
+ ws.send(JSON.stringify(this.stateMessage(null, null)));
404
+ ws.on("message", (raw) => this.message(ws, String(raw)));
405
+ ws.on("close", () => this.leave(ws));
406
+ ws.on("error", () => this.leave(ws));
407
+ }
408
+ message(ws, raw) {
409
+ let msg;
410
+ try {
411
+ msg = JSON.parse(raw);
412
+ } catch {
413
+ return;
414
+ }
415
+ const s = this.state;
416
+ if (msg.type === "hello") {
417
+ const seat = { id: String(msg.id || "").slice(0, 64), name: String(msg.name || "").trim().slice(0, 24) || "Someone", since: Date.now() };
418
+ this.seats.set(ws, seat);
419
+ ws.send(JSON.stringify(this.stateMessage("join", seat)));
420
+ this.broadcast({ type: "peers", peers: [...this.seats.values()] });
421
+ this.onChange();
422
+ return;
423
+ }
424
+ const seat = this.seats.get(ws);
425
+ if (!seat)
426
+ return;
427
+ if (msg.type === "pos") {
428
+ this.lastPos = Number(msg.time) || 0;
429
+ this.toOthers(ws, { type: "pos", id: seat.id, name: seat.name, time: this.lastPos, playing: !!msg.playing });
430
+ return;
431
+ }
432
+ if (msg.type === "pull") {
433
+ const time = Math.max(0, Number(msg.time) || 0);
434
+ s.time = time;
435
+ s.at = Date.now();
436
+ this.save();
437
+ this.toOthers(ws, { type: "pull", name: seat.name, time, playing: !!msg.playing, now: Date.now() });
438
+ return;
439
+ }
440
+ let action = null;
441
+ if (msg.type === "set") {
442
+ if (!!msg.playing !== s.playing && crossedToggle(this.lastToggle, seat.id, Number(msg.rev) || 0)) {
443
+ ws.send(JSON.stringify(this.stateMessage(null, null)));
444
+ return;
445
+ }
446
+ action = applySet(s, !!msg.playing, Number(msg.time) || 0);
447
+ if (action === "play" || action === "pause")
448
+ this.lastToggle = { by: seat.id, rev: this.rev + 1 };
449
+ } else if (msg.type === "ended" && s.film && !s.ended) {
450
+ s.ended = true;
451
+ s.playing = false;
452
+ action = "ended";
453
+ } else if (msg.type === "rate" && s.ended) {
454
+ const stars = Math.round(Number(msg.stars));
455
+ if (stars >= 1 && stars <= 5) {
456
+ s.ratings[seat.id] = { name: seat.name, stars };
457
+ action = "rate";
458
+ }
459
+ } else if (msg.type === "done" && s.ended && s.film) {
460
+ s.last = { title: s.film.title, finished: Date.now() };
461
+ s.film = null;
462
+ s.src = null;
463
+ s.ended = false;
464
+ s.ratings = {};
465
+ action = "done";
466
+ }
467
+ if (!action)
468
+ return;
469
+ this.lastChange = { action, by: seat.name };
470
+ this.save();
471
+ this.broadcast(this.stateMessage(action, seat));
472
+ this.onChange();
473
+ }
474
+ leave(ws) {
475
+ if (!this.sockets.delete(ws))
476
+ return;
477
+ this.seats.delete(ws);
478
+ this.broadcast({ type: "peers", peers: [...this.seats.values()] });
479
+ if (this.seats.size === 0 && this.state.playing) {
480
+ this.state.time = this.lastPos ?? currentTime(this.state);
481
+ this.state.playing = false;
482
+ this.state.at = Date.now();
483
+ this.save();
484
+ }
485
+ this.onChange();
486
+ }
487
+ stateMessage(action, seat) {
488
+ if (action)
489
+ this.rev++;
490
+ const ratings = Object.values(this.state.ratings);
491
+ const revealed = ratings.length >= 2;
492
+ return {
493
+ type: "state",
494
+ state: { ...this.state, ratings: ratings.map((r) => ({ name: r.name, stars: revealed ? r.stars : null })) },
495
+ raters: Object.keys(this.state.ratings),
496
+ action,
497
+ rev: this.rev,
498
+ by: seat?.name ?? null,
499
+ byId: seat?.id ?? null,
500
+ now: Date.now()
501
+ };
502
+ }
503
+ broadcast(msg) {
504
+ const text = JSON.stringify(msg);
505
+ for (const ws of this.sockets)
506
+ if (ws.readyState === ws.OPEN)
507
+ ws.send(text);
508
+ }
509
+ toOthers(from, msg) {
510
+ const text = JSON.stringify(msg);
511
+ for (const [ws] of this.seats)
512
+ if (ws !== from && ws.readyState === ws.OPEN)
513
+ ws.send(text);
514
+ }
515
+ save() {
516
+ mkdirSync2(ROOMS_DIR, { recursive: true });
517
+ const { src, ...rest } = this.state;
518
+ writeFileSync2(this.statePath, JSON.stringify(rest));
519
+ }
520
+ async http(req, res) {
521
+ const path = new URL(req.url ?? "/", "http://room").pathname;
522
+ const room = `/r/${this.id}`;
523
+ try {
524
+ if (path === room || path === `${room}/`)
525
+ return this.file(res, "room.html");
526
+ if (path === `${room}/film.mp4`)
527
+ return await this.film(req, res);
528
+ if (path === `${room}/subs.vtt` && this.vtt) {
529
+ res.writeHead(200, { "content-type": "text/vtt; charset=utf-8", "cache-control": "no-store" });
530
+ return res.end(this.vtt);
531
+ }
532
+ const details = path.match(/^\/api\/film\/(tt\d+)$/);
533
+ if (details) {
534
+ res.writeHead(200, { "content-type": "application/json" });
535
+ return res.end(JSON.stringify(await filmDetails(details[1])));
536
+ }
537
+ if (/^\/(style\.css|room\.js|favicon\.svg|fonts\/[a-z0-9-]+\.woff2)$/.test(path))
538
+ return this.file(res, path.slice(1));
539
+ } catch {
540
+ if (!res.headersSent)
541
+ res.writeHead(500);
542
+ return res.end();
543
+ }
544
+ res.writeHead(404, { "content-type": "text/plain" });
545
+ res.end("not here");
546
+ }
547
+ file(res, name) {
548
+ const full = normalize(join2(ASSETS, name));
549
+ if (!full.startsWith(ASSETS) || !existsSync2(full)) {
550
+ res.writeHead(404);
551
+ return res.end();
552
+ }
553
+ res.writeHead(200, { "content-type": TYPES[extname(full)] ?? "application/octet-stream", "cache-control": "no-cache" });
554
+ res.end(readFileSync2(full));
555
+ }
556
+ async film(req, res) {
557
+ if (!this.filmUrl) {
558
+ res.writeHead(404);
559
+ return res.end();
560
+ }
561
+ const abort = new AbortController;
562
+ req.on("close", () => abort.abort());
563
+ const range = req.headers.range;
564
+ const upstream = await fetch(this.filmUrl, { headers: range ? { range } : {}, signal: abort.signal });
565
+ const headers = { "content-type": "video/mp4", "accept-ranges": "bytes", "cache-control": "no-store" };
566
+ for (const name of ["content-range", "content-length"]) {
567
+ const value = upstream.headers.get(name);
568
+ if (value)
569
+ headers[name] = value;
570
+ }
571
+ res.writeHead(upstream.status, headers);
572
+ if (!upstream.body || req.method === "HEAD")
573
+ return res.end();
574
+ const body = Readable.fromWeb(upstream.body);
575
+ body.on("data", (chunk) => this.sentBytes += chunk.length);
576
+ body.on("error", () => res.destroy());
577
+ body.pipe(res);
578
+ }
579
+ }
580
+
581
+ // src/subtitles.ts
582
+ import { spawnSync } from "node:child_process";
583
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readdirSync as readdirSync2, readFileSync as readFileSync3, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
584
+ import { join as join3 } from "node:path";
585
+ var YIFY = "https://yifysubtitles.ch";
586
+ function srtToVtt(srt) {
587
+ const body = srt.replace(/^/, "").replace(/\r\n?/g, `
588
+ `).replace(/(\d{2}:\d{2}:\d{2}),(\d{3})/g, "$1.$2").trim();
589
+ return `WEBVTT
590
+
591
+ ` + body + `
592
+ `;
593
+ }
594
+ function parseYifyEnglish(html) {
595
+ for (const row of html.split(/<tr\b/i)) {
596
+ if (/sub-lang">\s*English\b/i.test(row)) {
597
+ const link = row.match(/href="\/subtitles\/([^"]+)"/);
598
+ if (link)
599
+ return link[1];
600
+ }
601
+ }
602
+ return null;
603
+ }
604
+ async function fromYify(imdbId) {
605
+ const srt = join3(SUBS_DIR, `${imdbId}.srt`);
606
+ if (existsSync3(srt))
607
+ return srt;
608
+ try {
609
+ const page = await fetch(`${YIFY}/movie-imdb/${imdbId}`, {
610
+ headers: { "User-Agent": UA },
611
+ signal: AbortSignal.timeout(15000)
612
+ });
613
+ if (!page.ok)
614
+ return null;
615
+ const slug = parseYifyEnglish(await page.text());
616
+ if (!slug)
617
+ return null;
618
+ const zip = await fetch(`${YIFY}/subtitle/${slug}.zip`, {
619
+ headers: { "User-Agent": UA, Referer: `${YIFY}/subtitles/${slug}` },
620
+ signal: AbortSignal.timeout(20000)
621
+ });
622
+ if (!zip.ok)
623
+ return null;
624
+ mkdirSync3(SUBS_DIR, { recursive: true });
625
+ const zipPath = join3(SUBS_DIR, `${imdbId}.zip`);
626
+ const unpacked = join3(SUBS_DIR, imdbId);
627
+ writeFileSync3(zipPath, new Uint8Array(await zip.arrayBuffer()));
628
+ spawnSync("unzip", ["-o", "-j", zipPath, "-d", unpacked], { stdio: "ignore" });
629
+ rmSync2(zipPath, { force: true });
630
+ const file = existsSync3(unpacked) ? readdirSync2(unpacked).find((f) => f.toLowerCase().endsWith(".srt")) : undefined;
631
+ if (file)
632
+ renameSync(join3(unpacked, file), srt);
633
+ rmSync2(unpacked, { recursive: true, force: true });
634
+ return file ? srt : null;
635
+ } catch {
636
+ return null;
637
+ }
638
+ }
639
+ async function englishSubtitles(imdbId, torrentSub) {
640
+ let path = null;
641
+ if (torrentSub && /\.srt$/i.test(torrentSub.name)) {
642
+ try {
643
+ const text = await (await fetch(torrentSub.url)).text();
644
+ mkdirSync3(SUBS_DIR, { recursive: true });
645
+ path = join3(SUBS_DIR, `${imdbId}-torrent.srt`);
646
+ writeFileSync3(path, text);
647
+ } catch {
648
+ path = null;
649
+ }
650
+ }
651
+ if (!path && /^tt\d+$/.test(imdbId))
652
+ path = await fromYify(imdbId);
653
+ if (!path)
654
+ return null;
655
+ return { path, vtt: srtToVtt(readFileSync3(path, "utf-8")) };
656
+ }
657
+
658
+ // src/system.ts
659
+ import { spawn } from "node:child_process";
660
+ import { existsSync as existsSync4 } from "node:fs";
661
+ import { delimiter, join as join4 } from "node:path";
662
+ function which(program) {
663
+ const extensions = process.platform === "win32" ? [".exe", ".cmd", ""] : [""];
664
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
665
+ for (const ext of extensions) {
666
+ const candidate = join4(dir, program + ext);
667
+ if (existsSync4(candidate))
668
+ return candidate;
669
+ }
670
+ }
671
+ return null;
672
+ }
673
+ function openUrl(url) {
674
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
675
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
676
+ spawn(command, args, { stdio: "ignore", detached: true }).unref();
677
+ }
678
+
679
+ // src/torrents.ts
680
+ var TRACKERS = [
681
+ "udp://tracker.opentrackr.org:1337/announce",
682
+ "udp://open.demonii.com:1337/announce",
683
+ "udp://tracker.openbittorrent.com:6969/announce",
684
+ "udp://exodus.desync.com:6969/announce"
685
+ ];
686
+ function magnetFromHash(hash, name) {
687
+ const trackers = TRACKERS.map((t) => `&tr=${encodeURIComponent(t)}`).join("");
688
+ return `magnet:?xt=urn:btih:${hash.toLowerCase()}&dn=${encodeURIComponent(name)}${trackers}`;
689
+ }
690
+ function withTrackers(magnet) {
691
+ const missing = TRACKERS.filter((t) => !magnet.includes(encodeURIComponent(t)) && !magnet.includes(t));
692
+ return magnet + missing.map((t) => `&tr=${encodeURIComponent(t)}`).join("");
693
+ }
694
+ function hashOf(magnet) {
695
+ return magnet.match(/btih:([a-z0-9]+)/i)?.[1]?.toLowerCase() ?? "";
696
+ }
697
+ function humanSize(bytes) {
698
+ if (!bytes || bytes < 0)
699
+ return "?";
700
+ const units = ["B", "KB", "MB", "GB", "TB"];
701
+ let i = 0;
702
+ let n = bytes;
703
+ while (n >= 1024 && i < units.length - 1) {
704
+ n /= 1024;
705
+ i++;
706
+ }
707
+ return `${n.toFixed(n < 10 && i > 0 ? 1 : 0)} ${units[i]}`;
708
+ }
709
+ function parseQuality(name) {
710
+ const res = name.match(/\b(2160p|1080p|720p|480p)\b/i)?.[1].toLowerCase() ?? (/\b(4k|uhd)\b/i.test(name) ? "2160p" : "");
711
+ const hdr = /\b(dolby\s*vision|dv)\b/i.test(name) ? "DV" : /\bhdr10\+?\b|\bhdr\b/i.test(name) ? "HDR" : "";
712
+ const codec = /\b(x265|h\.?\s?265|hevc)\b/i.test(name) ? "x265" : /\b(x264|h\.?\s?264|avc)\b/i.test(name) ? "x264" : /\bav1\b/i.test(name) ? "AV1" : "";
713
+ const raw = name.match(/\b(REMUX|BluRay|BDRip|BRRip|WEB[- .]?DL|WEBRip|WEB|HDTV|DVDRip|HDCAM|CAM)\b/i)?.[1] ?? "";
714
+ const src = /^web[- .]?dl$/i.test(raw) ? "WEB-DL" : /^web$/i.test(raw) ? "WEB" : raw;
715
+ return { res, hdr, codec, src };
716
+ }
717
+ function browserPlayable(name) {
718
+ return whyNotCouch(name) === null;
719
+ }
720
+ function whyNotCouch(name) {
721
+ if (/\b(x265|h\.?\s?265|hevc)\b/i.test(name))
722
+ return "HEVC video";
723
+ if (/\b10.?bit\b/i.test(name))
724
+ return "10-bit video";
725
+ if (/\bav1\b/i.test(name))
726
+ return "AV1 video";
727
+ if (/\b(yts|yify)\b/i.test(name))
728
+ return null;
729
+ if (!/\b(x264|h\.?\s?264|avc)\b/i.test(name))
730
+ return "no H.264 in the name";
731
+ if (!/\bmp4\b/i.test(name))
732
+ return "most likely MKV, browsers need MP4";
733
+ return null;
734
+ }
735
+ function matchesShow(name, title, tag) {
736
+ const words = name.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
737
+ const at = tag ? words.indexOf(tag.toLowerCase()) : -1;
738
+ if (at < 0)
739
+ return true;
740
+ const before = words.slice(0, at).trim().split(/\s+/).filter(Boolean);
741
+ if (before.length && /^(19|20)\d\d$/.test(before[before.length - 1]))
742
+ before.pop();
743
+ const show = title.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
744
+ if (!before.length || !show.length)
745
+ return true;
746
+ if (before.length > show.length)
747
+ return false;
748
+ return before.every((word, i) => word === show[i]);
749
+ }
750
+ async function getJson(url, init = {}) {
751
+ const res = await fetch(url, {
752
+ ...init,
753
+ headers: { "User-Agent": UA, ...init.headers ?? {} },
754
+ signal: AbortSignal.timeout(12000)
755
+ });
756
+ if (!res.ok)
757
+ throw new Error(`${new URL(url).host} answered ${res.status}`);
758
+ return res.json();
759
+ }
760
+ var YTS_HOSTS = ["movies-api.accel.li", "yts.mx", "yts.am"];
761
+ async function yts(imdbId) {
762
+ for (const host of YTS_HOSTS) {
763
+ try {
764
+ const json = await getJson(`https://${host}/api/v2/list_movies.json?query_term=${imdbId}`);
765
+ const film = (json.data?.movies ?? []).find((m) => m.imdb_code === imdbId);
766
+ if (!film)
767
+ return [];
768
+ return (film.torrents ?? []).map((t) => {
769
+ const name = `${film.title_long} [${[t.quality, t.type, t.video_codec].filter(Boolean).join(" ")}] [YTS]`;
770
+ return {
771
+ name,
772
+ infoHash: String(t.hash).toLowerCase(),
773
+ magnet: magnetFromHash(t.hash, name),
774
+ seeders: t.seeds ?? 0,
775
+ bytes: t.size_bytes ?? 0,
776
+ source: "YTS"
777
+ };
778
+ });
779
+ } catch {}
780
+ }
781
+ return [];
782
+ }
783
+ async function eztv(imdbId, season, episode) {
784
+ const id = imdbId.replace(/^tt/, "");
785
+ const out = [];
786
+ for (let page = 1;page <= 5; page++) {
787
+ const json = await getJson(`https://eztvx.to/api/get-torrents?imdb_id=${id}&limit=100&page=${page}`);
788
+ const rows = json.torrents ?? [];
789
+ for (const t of rows) {
790
+ if (Number(t.season) !== season || Number(t.episode) !== episode || !t.hash)
791
+ continue;
792
+ out.push({
793
+ name: t.title ?? t.filename ?? "",
794
+ infoHash: String(t.hash).toLowerCase(),
795
+ magnet: t.magnet_url || magnetFromHash(t.hash, t.title ?? ""),
796
+ seeders: Number(t.seeds) || 0,
797
+ bytes: Number(t.size_bytes) || 0,
798
+ source: "EZTV"
799
+ });
800
+ }
801
+ if (rows.length < 100)
802
+ break;
803
+ }
804
+ return out;
805
+ }
806
+ async function piratebay(query) {
807
+ const rows = await getJson(`https://apibay.org/q.php?q=${encodeURIComponent(query)}&cat=0`);
808
+ return rows.filter((r) => r.info_hash && !/^0+$/.test(r.info_hash) && String(r.category).startsWith("2")).map((r) => ({
809
+ name: r.name,
810
+ infoHash: String(r.info_hash).toLowerCase(),
811
+ magnet: magnetFromHash(r.info_hash, r.name),
812
+ seeders: Number(r.seeders) || 0,
813
+ bytes: Number(r.size) || 0,
814
+ source: "TPB"
815
+ }));
816
+ }
817
+ async function knaben(query) {
818
+ const json = await getJson("https://api.knaben.org/v1", {
819
+ method: "POST",
820
+ headers: { "Content-Type": "application/json" },
821
+ body: JSON.stringify({ query, order_by: "seeders", order_direction: "desc", size: 50 })
822
+ });
823
+ return (json.hits ?? []).filter((h) => h.hash || h.magnetUrl).map((h) => ({
824
+ name: h.title ?? "",
825
+ infoHash: String(h.hash ?? hashOf(h.magnetUrl ?? "")).toLowerCase(),
826
+ magnet: h.magnetUrl || magnetFromHash(h.hash, h.title ?? ""),
827
+ seeders: Number(h.seeders) || 0,
828
+ bytes: Number(h.bytes) || 0,
829
+ source: h.tracker ?? "Knaben"
830
+ }));
831
+ }
832
+ async function nyaa(query) {
833
+ const res = await fetch(`https://nyaa.si/?page=rss&c=1_2&f=0&q=${encodeURIComponent(query)}`, {
834
+ headers: { "User-Agent": UA },
835
+ signal: AbortSignal.timeout(12000)
836
+ });
837
+ if (!res.ok)
838
+ throw new Error(`nyaa answered ${res.status}`);
839
+ const items = (await res.text()).match(/<item>[\s\S]*?<\/item>/g) ?? [];
840
+ return items.map((item) => {
841
+ const name = (item.match(/<title>([\s\S]*?)<\/title>/)?.[1] ?? "").replace(/&amp;/g, "&").trim();
842
+ const hash = item.match(/<nyaa:infoHash>([\s\S]*?)<\/nyaa:infoHash>/)?.[1]?.trim() ?? "";
843
+ const size = item.match(/<nyaa:size>([\d.]+)\s*(KiB|MiB|GiB)<\/nyaa:size>/);
844
+ const scale = size ? { KiB: 1024, MiB: 1024 ** 2, GiB: 1024 ** 3 }[size[2]] : 0;
845
+ return {
846
+ name,
847
+ infoHash: hash.toLowerCase(),
848
+ magnet: hash ? magnetFromHash(hash, name) : "",
849
+ seeders: Number(item.match(/<nyaa:seeders>(\d+)<\/nyaa:seeders>/)?.[1]) || 0,
850
+ bytes: size ? Math.round(Number(size[1]) * scale) : 0,
851
+ source: "Nyaa"
852
+ };
853
+ }).filter((t) => t.infoHash);
854
+ }
855
+ async function findSources(wanted, onUpdate = () => {}) {
856
+ const jobs = [];
857
+ const t = wanted.title;
858
+ if (wanted.kind === "film") {
859
+ const query = t.year ? `${t.name} ${t.year}` : t.name;
860
+ jobs.push({ name: "YTS", run: () => yts(t.id) });
861
+ jobs.push({ name: "TPB", run: () => piratebay(query) });
862
+ jobs.push({ name: "Knaben", run: () => knaben(query) });
863
+ } else if (wanted.kind === "episode") {
864
+ const query = `${t.name} ${sxxeyy(wanted.season, wanted.episode)}`;
865
+ jobs.push({ name: "EZTV", run: () => eztv(t.id, wanted.season, wanted.episode) });
866
+ jobs.push({ name: "TPB", run: () => piratebay(query) });
867
+ jobs.push({ name: "Knaben", run: () => knaben(query) });
868
+ } else {
869
+ for (const query of wanted.queries.slice(0, 4)) {
870
+ jobs.push({ name: "Nyaa", run: () => nyaa(query) });
871
+ }
872
+ }
873
+ const sites = [];
874
+ const left = new Map;
875
+ const failed = new Map;
876
+ for (const job of jobs) {
877
+ if (!left.has(job.name))
878
+ sites.push({ name: job.name, state: "asking", found: 0 });
879
+ left.set(job.name, (left.get(job.name) ?? 0) + 1);
880
+ }
881
+ const seen = new Map;
882
+ const torrents = [];
883
+ const report = () => ({ torrents: relevantSorted(torrents, wanted), sites: sites.map((x) => ({ ...x })) });
884
+ await Promise.all(jobs.map(async (job) => {
885
+ const site = sites.find((x) => x.name === job.name);
886
+ try {
887
+ for (const torrent of await job.run()) {
888
+ if (!torrent.infoHash)
889
+ continue;
890
+ const at = seen.get(torrent.infoHash);
891
+ if (at === undefined) {
892
+ seen.set(torrent.infoHash, torrents.length);
893
+ torrents.push(torrent);
894
+ site.found++;
895
+ } else if (idMatched(torrent) && !idMatched(torrents[at])) {
896
+ torrents[at] = torrent;
897
+ site.found++;
898
+ }
899
+ }
900
+ } catch {
901
+ failed.set(job.name, (failed.get(job.name) ?? 0) + 1);
902
+ }
903
+ const remaining = left.get(job.name) - 1;
904
+ left.set(job.name, remaining);
905
+ if (remaining === 0)
906
+ site.state = site.found === 0 && failed.has(job.name) ? "offline" : "done";
907
+ onUpdate(report());
908
+ }));
909
+ return report();
910
+ }
911
+ function relevantSorted(torrents, wanted) {
912
+ let kept = torrents;
913
+ if (wanted.kind !== "anime") {
914
+ const tag = wanted.kind === "episode" ? sxxeyy(wanted.season, wanted.episode) : String(wanted.title.year ?? "");
915
+ const relevant = torrents.filter((x) => idMatched(x) || matchesShow(x.name, wanted.title.name, tag));
916
+ if (relevant.length)
917
+ kept = relevant;
918
+ }
919
+ return [...kept].sort((a, b) => b.seeders - a.seeders);
920
+ }
921
+ function idMatched(t) {
922
+ return t.source === "YTS" || t.source === "EZTV";
923
+ }
924
+ var PICK_MAX_BYTES = 6 * 1024 ** 3;
925
+ function pickBest(torrents) {
926
+ for (const t of torrents) {
927
+ const q = parseQuality(t.name);
928
+ if (q.res === "1080p" && q.codec === "x264" && t.bytes > 0 && t.bytes < PICK_MAX_BYTES && t.seeders > 0)
929
+ return t;
930
+ }
931
+ return null;
932
+ }
933
+ function qualityGroups(torrents) {
934
+ const order = ["2160p", "1080p", "720p", "480p", ""];
935
+ return order.map((res) => ({
936
+ label: res || "other",
937
+ torrents: torrents.filter((t) => parseQuality(t.name).res === res)
938
+ })).filter((group) => group.torrents.length > 0);
939
+ }
940
+ function audioLabel(name) {
941
+ const parts = [];
942
+ if (/truehd/i.test(name))
943
+ parts.push("TrueHD");
944
+ if (/dts[- .]?hd[- .]?ma/i.test(name))
945
+ parts.push("DTS-HD MA");
946
+ else if (/\bdts\b/i.test(name))
947
+ parts.push("DTS");
948
+ if (/\b(ddp|dd\+|e-?ac-?3)/i.test(name))
949
+ parts.push("DD+");
950
+ else if (/\b(dd|ac-?3)[ .]?\d/i.test(name) || /\bac3\b/i.test(name))
951
+ parts.push("DD");
952
+ if (/\baac/i.test(name))
953
+ parts.push("AAC");
954
+ const channels = name.match(/(?:^|\D)([2578])[ .]([01])(?!\d)/);
955
+ if (channels)
956
+ parts.push(`${channels[1]}.${channels[2]}`);
957
+ if (/atmos/i.test(name))
958
+ parts.push("Atmos");
959
+ return parts.join(" ");
960
+ }
961
+
962
+ // src/tunnel.ts
963
+ import { spawn as spawn2 } from "node:child_process";
964
+ import { existsSync as existsSync5 } from "node:fs";
965
+ import { bin, install } from "cloudflared";
966
+ async function cloudflaredBinary() {
967
+ if (!existsSync5(bin))
968
+ await install(bin);
969
+ return bin;
970
+ }
971
+ function run(cmd) {
972
+ return new Promise((resolve) => {
973
+ const child = spawn2(cmd[0], cmd.slice(1), { stdio: ["ignore", "pipe", "ignore"] });
974
+ let out = "";
975
+ child.stdout.on("data", (d) => out += d);
976
+ child.on("close", () => resolve(out.trim()));
977
+ child.on("error", () => resolve(""));
978
+ });
979
+ }
980
+ async function quickTunnelAnswers(url) {
981
+ const host = new URL(url).hostname;
982
+ const nameserver = (await run(["dig", "+short", "NS", "trycloudflare.com"])).split(`
983
+ `)[0];
984
+ if (!nameserver)
985
+ return false;
986
+ const ip = (await run(["dig", "+short", `@${nameserver}`, host, "A"])).split(`
987
+ `)[0];
988
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(ip))
989
+ return false;
990
+ const code = await run(["curl", "-s", "-o", "/dev/null", "-m", "5", "-w", "%{http_code}", "--resolve", `${host}:443:${ip}`, url]);
991
+ return code === "200";
992
+ }
993
+ function addressFromLog(child) {
994
+ return new Promise((resolve) => {
995
+ let log = "";
996
+ const timer = setTimeout(() => resolve(null), 30000);
997
+ child.stderr?.on("data", (chunk) => {
998
+ log += chunk;
999
+ const found = log.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
1000
+ if (found) {
1001
+ clearTimeout(timer);
1002
+ resolve(found[0]);
1003
+ }
1004
+ });
1005
+ child.on("exit", () => resolve(null));
1006
+ });
1007
+ }
1008
+ async function openTunnel(port, roomPath, named) {
1009
+ const binary = await cloudflaredBinary();
1010
+ if (named) {
1011
+ const child = spawn2(binary, ["tunnel", "--no-autoupdate", "run", "--token", named.token], { stdio: "ignore" });
1012
+ const url = `https://${named.host}`;
1013
+ for (let i = 0;i < 30; i++) {
1014
+ try {
1015
+ if ((await fetch(url + roomPath, { signal: AbortSignal.timeout(4000) })).ok)
1016
+ return { url, stop: () => child.kill() };
1017
+ } catch {}
1018
+ await sleep(1000);
1019
+ }
1020
+ child.kill();
1021
+ throw new Error(`the named tunnel to ${named.host} didn't answer; check its route points at this computer`);
1022
+ }
1023
+ const child = spawn2(binary, ["tunnel", "--no-autoupdate", "--url", `http://127.0.0.1:${port}`], { stdio: ["ignore", "ignore", "pipe"] });
1024
+ const url = await addressFromLog(child);
1025
+ if (!url) {
1026
+ child.kill();
1027
+ throw new Error("cloudflared didn't open a tunnel; check the internet connection");
1028
+ }
1029
+ for (let i = 0;i < 40; i++) {
1030
+ if (await quickTunnelAnswers(url + roomPath))
1031
+ return { url, stop: () => child.kill() };
1032
+ await sleep(1000);
1033
+ }
1034
+ child.kill();
1035
+ throw new Error("the tunnel opened but never answered; try again");
1036
+ }
1037
+ function sleep(ms) {
1038
+ return new Promise((resolve) => setTimeout(resolve, ms));
1039
+ }
1040
+
1041
+ // src/couch.ts
1042
+ var NAMED_PORT = 8765;
1043
+ function newRoomId() {
1044
+ return [...randomBytes(10)].map((b) => (b % 36).toString(36)).join("");
1045
+ }
1046
+
1047
+ class Couch {
1048
+ room;
1049
+ link = null;
1050
+ error = null;
1051
+ tunnel = null;
1052
+ stream = null;
1053
+ onUpdate = () => {};
1054
+ constructor(room) {
1055
+ this.room = room;
1056
+ room.onChange = () => {
1057
+ if (room.state.ended && this.stream) {
1058
+ this.stream.stop();
1059
+ this.stream = null;
1060
+ }
1061
+ this.onUpdate();
1062
+ };
1063
+ }
1064
+ static start() {
1065
+ const config = loadConfig();
1066
+ if (!config.room)
1067
+ saveConfig({ ...config, room: newRoomId() });
1068
+ const { room: id, tunnelToken, tunnelHost } = loadConfig();
1069
+ const couch = new Couch(new Room(id));
1070
+ const named = tunnelToken && tunnelHost ? { token: tunnelToken, host: tunnelHost } : undefined;
1071
+ couch.room.listen(named ? NAMED_PORT : 0).then((port) => openTunnel(port, `/r/${id}`, named)).then((tunnel) => {
1072
+ couch.tunnel = tunnel;
1073
+ couch.link = `${tunnel.url}/r/${id}`;
1074
+ openUrl(couch.link);
1075
+ couch.onUpdate();
1076
+ }).catch((error) => {
1077
+ couch.error = error instanceof Error ? error.message : String(error);
1078
+ couch.onUpdate();
1079
+ });
1080
+ return couch;
1081
+ }
1082
+ async play(engine, title, torrent, onStatus) {
1083
+ await this.stopFilm();
1084
+ onStatus("finding peers…");
1085
+ const stream = await engine.open(withTrackers(torrent.magnet));
1086
+ const video = stream.videos[0];
1087
+ if (!video || !/\.mp4$/i.test(video.name)) {
1088
+ await stream.stop();
1089
+ throw new Error(video ? `that source is .${video.name.split(".").pop()}, not .mp4; pick another` : "no video in that torrent");
1090
+ }
1091
+ onStatus("looking for English subtitles…");
1092
+ const sub = stream.subtitles[0];
1093
+ const subs = await englishSubtitles(title.id, sub ? { url: stream.urlOf(sub), name: sub.name } : null);
1094
+ this.stream = stream;
1095
+ recordPlay({ id: title.id, name: title.name, year: title.year, kind: title.kind, poster: title.poster });
1096
+ touchFilm(stream.folder);
1097
+ trimCache(loadConfig().cacheGB ?? 10, stream.folder);
1098
+ this.room.setFilm({ id: title.id, title: title.name, year: title.year ?? undefined }, stream.urlOf(video), subs?.vtt ?? null);
1099
+ onStatus(`on in the room${subs ? ", English subtitles available" : ""}`);
1100
+ }
1101
+ async progress() {
1102
+ return this.stream ? this.stream.progress() : null;
1103
+ }
1104
+ async stopFilm() {
1105
+ if (!this.stream)
1106
+ return;
1107
+ const stream = this.stream;
1108
+ this.stream = null;
1109
+ this.room.stopFilm();
1110
+ await stream.stop();
1111
+ }
1112
+ async close() {
1113
+ await this.stopFilm();
1114
+ this.tunnel?.stop();
1115
+ this.room.close();
1116
+ }
1117
+ }
1118
+
1119
+ // src/engines.ts
1120
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
1121
+ import { mkdirSync as mkdirSync4 } from "node:fs";
1122
+ import WebTorrent from "webtorrent";
1123
+ var VIDEO = /\.(mkv|mp4|avi|webm|mov|m4v|ts)$/i;
1124
+ var SUBTITLE = /\.(srt|vtt|ass|ssa)$/i;
1125
+ function pickVideos(files) {
1126
+ return files.filter((f) => VIDEO.test(f.name) && f.bytes >= 50000000 && !/sample/i.test(f.name)).sort((a, b) => b.bytes - a.bytes);
1127
+ }
1128
+ function pickSubtitles(files) {
1129
+ const english = (name) => /\b(en|eng|english)\b/i.test(name) || /\.en\./i.test(name);
1130
+ return files.filter((f) => SUBTITLE.test(f.name)).sort((a, b) => Number(english(b.name)) - Number(english(a.name)));
1131
+ }
1132
+ var RQBIT = "http://127.0.0.1:3041";
1133
+ async function rqbitUp() {
1134
+ try {
1135
+ return (await fetch(`${RQBIT}/`, { signal: AbortSignal.timeout(1000) })).ok;
1136
+ } catch {
1137
+ return false;
1138
+ }
1139
+ }
1140
+
1141
+ class Rqbit {
1142
+ name = "rqbit";
1143
+ child = null;
1144
+ async ensure() {
1145
+ if (await rqbitUp())
1146
+ return;
1147
+ mkdirSync4(FILMS_DIR, { recursive: true });
1148
+ this.child = spawn3("rqbit", ["--http-api-listen-addr", "127.0.0.1:3041", "--listen-port", "4247", "--disable-dht-persistence", "server", "start", "--disable-persistence", FILMS_DIR], { stdio: "ignore" });
1149
+ for (let i = 0;i < 25; i++) {
1150
+ if (await rqbitUp())
1151
+ return;
1152
+ await sleep2(200);
1153
+ }
1154
+ throw new Error("rqbit didn't start");
1155
+ }
1156
+ async open(magnet) {
1157
+ await this.ensure();
1158
+ const res = await fetch(`${RQBIT}/torrents?overwrite=true`, {
1159
+ method: "POST",
1160
+ body: magnet,
1161
+ signal: AbortSignal.timeout(45000)
1162
+ });
1163
+ if (!res.ok)
1164
+ throw new Error("rqbit couldn't add that torrent (no seeds?)");
1165
+ const json = await res.json();
1166
+ const id = json.id;
1167
+ for (let i = 0;i < 150; i++) {
1168
+ const stats = await fetch(`${RQBIT}/torrents/${id}/stats/v1`).then((r) => r.json()).catch(() => ({}));
1169
+ if (stats.state === "live" || stats.finished)
1170
+ break;
1171
+ await sleep2(200);
1172
+ }
1173
+ const files = (json.details?.files ?? []).map((f, index) => ({
1174
+ index,
1175
+ name: f.name ?? (f.components ?? []).join("/"),
1176
+ bytes: f.length ?? 0
1177
+ }));
1178
+ return {
1179
+ folder: json.details?.name ?? "",
1180
+ videos: pickVideos(files),
1181
+ subtitles: pickSubtitles(files),
1182
+ urlOf: (file) => `${RQBIT}/torrents/${id}/stream/${file.index}`,
1183
+ progress: async () => {
1184
+ try {
1185
+ const s = await (await fetch(`${RQBIT}/torrents/${id}/stats/v1`)).json();
1186
+ return {
1187
+ percent: s.total_bytes ? Math.floor(100 * s.progress_bytes / s.total_bytes) : 0,
1188
+ downBytesPerSec: (s.live?.download_speed?.mbps ?? 0) * 1024 * 1024,
1189
+ peers: s.live?.snapshot?.peer_stats?.live ?? 0
1190
+ };
1191
+ } catch {
1192
+ return { percent: 0, downBytesPerSec: 0, peers: 0 };
1193
+ }
1194
+ },
1195
+ stop: async () => {
1196
+ await fetch(`${RQBIT}/torrents/${id}/forget`, { method: "POST" }).catch(() => {});
1197
+ }
1198
+ };
1199
+ }
1200
+ async shutdown() {
1201
+ this.child?.kill();
1202
+ this.child = null;
1203
+ spawnSync2("pkill", ["-f", "^rqbit --http-api-listen-addr 127.0.0.1:3041"], { stdio: "ignore" });
1204
+ }
1205
+ }
1206
+
1207
+ class Webtorrent {
1208
+ name = "webtorrent";
1209
+ client = null;
1210
+ base = "";
1211
+ async ensure() {
1212
+ if (this.client)
1213
+ return;
1214
+ this.client = new WebTorrent;
1215
+ const server = this.client.createServer({ hostname: "127.0.0.1" });
1216
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
1217
+ this.base = `http://127.0.0.1:${server.server.address().port}/webtorrent`;
1218
+ }
1219
+ async open(magnet) {
1220
+ await this.ensure();
1221
+ mkdirSync4(FILMS_DIR, { recursive: true });
1222
+ const torrent = await new Promise((resolve, reject) => {
1223
+ const timer = setTimeout(() => reject(new Error("no peers sent the torrent's metadata (no seeds?)")), 45000);
1224
+ this.client.add(magnet, { path: FILMS_DIR }, (t) => {
1225
+ clearTimeout(timer);
1226
+ resolve(t);
1227
+ });
1228
+ });
1229
+ const files = torrent.files.map((f, index) => ({ index, name: f.path, bytes: f.length }));
1230
+ return {
1231
+ folder: torrent.name,
1232
+ videos: pickVideos(files),
1233
+ subtitles: pickSubtitles(files),
1234
+ urlOf: (file) => {
1235
+ const path = torrent.files[file.index].path.replace(/\\/g, "/").split("/").map(encodeURIComponent).join("/");
1236
+ return `${this.base}/${torrent.infoHash}/${path}`;
1237
+ },
1238
+ progress: async () => ({
1239
+ percent: Math.floor(torrent.progress * 100),
1240
+ downBytesPerSec: torrent.downloadSpeed,
1241
+ peers: torrent.numPeers
1242
+ }),
1243
+ stop: async () => {
1244
+ await new Promise((resolve) => torrent.destroy({ destroyStore: false }, () => resolve()));
1245
+ }
1246
+ };
1247
+ }
1248
+ async shutdown() {
1249
+ if (!this.client)
1250
+ return;
1251
+ await new Promise((resolve) => this.client.destroy(() => resolve()));
1252
+ this.client = null;
1253
+ }
1254
+ }
1255
+ function pickEngine(choice) {
1256
+ if (choice === "webtorrent")
1257
+ return new Webtorrent;
1258
+ if (choice === "rqbit" || which("rqbit"))
1259
+ return new Rqbit;
1260
+ return new Webtorrent;
1261
+ }
1262
+ function sleep2(ms) {
1263
+ return new Promise((resolve) => setTimeout(resolve, ms));
1264
+ }
1265
+
1266
+ // src/players.ts
1267
+ import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
1268
+ import { existsSync as existsSync6 } from "node:fs";
1269
+ import { createServer as createServer2 } from "node:http";
1270
+ import { homedir as homedir2 } from "node:os";
1271
+ import { join as join5 } from "node:path";
1272
+ function appBinary(program, app, inside) {
1273
+ const onPath = which(program);
1274
+ if (onPath)
1275
+ return onPath;
1276
+ for (const root of ["/Applications", join5(homedir2(), "Applications")]) {
1277
+ const path = join5(root, app, inside);
1278
+ if (existsSync6(path))
1279
+ return path;
1280
+ }
1281
+ return null;
1282
+ }
1283
+ function iinaBinary() {
1284
+ return appBinary("iina", "IINA.app", "Contents/MacOS/iina-cli");
1285
+ }
1286
+ function vlcBinary() {
1287
+ return appBinary("vlc", "VLC.app", "Contents/MacOS/VLC");
1288
+ }
1289
+ function installedPlayers() {
1290
+ const list = [];
1291
+ if (iinaBinary())
1292
+ list.push("iina");
1293
+ if (which("mpv"))
1294
+ list.push("mpv");
1295
+ if (vlcBinary())
1296
+ list.push("vlc");
1297
+ list.push("browser");
1298
+ return list;
1299
+ }
1300
+ function pickPlayer(choice) {
1301
+ const installed = installedPlayers();
1302
+ return installed.includes(choice) ? choice : installed[0];
1303
+ }
1304
+ function play(player, film) {
1305
+ if (player === "browser")
1306
+ return playInBrowser(film);
1307
+ const args = [];
1308
+ let binary;
1309
+ if (player === "iina") {
1310
+ binary = iinaBinary();
1311
+ args.push("--no-stdin", `--mpv-force-media-title=${film.title}`);
1312
+ if (film.subtitle)
1313
+ args.push(`--mpv-sub-files=${film.subtitle}`);
1314
+ } else if (player === "mpv") {
1315
+ binary = which("mpv");
1316
+ args.push(`--force-media-title=${film.title}`);
1317
+ if (film.subtitle)
1318
+ args.push(`--sub-file=${film.subtitle}`);
1319
+ } else {
1320
+ binary = vlcBinary();
1321
+ args.push(`--meta-title=${film.title}`);
1322
+ if (film.subtitle)
1323
+ args.push(`--sub-file=${film.subtitle}`);
1324
+ }
1325
+ args.push(film.url);
1326
+ const child = spawn4(binary, args, { stdio: "ignore" });
1327
+ const closed = player === "iina" ? waitForAppToQuit("IINA") : new Promise((resolve) => child.on("exit", () => resolve()));
1328
+ return {
1329
+ closed,
1330
+ stop: () => {
1331
+ if (player === "iina")
1332
+ spawnSync3("osascript", ["-e", 'quit app "IINA"']);
1333
+ else
1334
+ child.kill();
1335
+ }
1336
+ };
1337
+ }
1338
+ async function waitForAppToQuit(name) {
1339
+ await sleep3(3000);
1340
+ while (spawnSync3("pgrep", ["-x", name]).status === 0)
1341
+ await sleep3(2000);
1342
+ }
1343
+ function playerPage(title, hasSubtitles) {
1344
+ const safe = title.replace(/[<&"]/g, "");
1345
+ const track = hasSubtitles ? '<track kind="subtitles" srclang="en" label="English" src="/subs.vtt" default>' : "";
1346
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${safe}</title>
1347
+ <style>html,body{margin:0;height:100%;background:#000}video{width:100%;height:100%}</style></head>
1348
+ <body><video src="/film" controls autoplay>${track}</video></body></html>`;
1349
+ }
1350
+ function playInBrowser(film) {
1351
+ const server = createServer2((req, res) => {
1352
+ if (req.url === "/") {
1353
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1354
+ res.end(playerPage(film.title, Boolean(film.vtt)));
1355
+ } else if (req.url === "/film") {
1356
+ res.writeHead(302, { location: film.url });
1357
+ res.end();
1358
+ } else if (req.url === "/subs.vtt" && film.vtt) {
1359
+ res.writeHead(200, { "content-type": "text/vtt; charset=utf-8" });
1360
+ res.end(film.vtt);
1361
+ } else {
1362
+ res.writeHead(404);
1363
+ res.end();
1364
+ }
1365
+ });
1366
+ let finish = () => {};
1367
+ const closed = new Promise((resolve) => finish = resolve);
1368
+ server.listen(0, "127.0.0.1", () => {
1369
+ const address = server.address();
1370
+ if (address && typeof address === "object")
1371
+ openUrl(`http://127.0.0.1:${address.port}/`);
1372
+ });
1373
+ return {
1374
+ closed,
1375
+ stop: () => {
1376
+ server.close();
1377
+ finish();
1378
+ }
1379
+ };
1380
+ }
1381
+ function sleep3(ms) {
1382
+ return new Promise((resolve) => setTimeout(resolve, ms));
1383
+ }
1384
+
1385
+ // src/ui.tsx
1386
+ import { Box as Box2, Text as Text2, useApp, useInput, usePaste, useWindowSize } from "ink";
1387
+ import { useEffect as useEffect2, useRef, useState as useState2 } from "react";
1388
+
1389
+ // src/anime.ts
1390
+ function parseAnime(m) {
1391
+ if (!m)
1392
+ return null;
1393
+ const romaji = m.title?.romaji || m.title?.english || "";
1394
+ const aired = typeof m.nextAiringEpisode?.episode === "number" ? m.nextAiringEpisode.episode - 1 : 0;
1395
+ const episodes = typeof m.episodes === "number" ? m.episodes : aired;
1396
+ const episodeNames = {};
1397
+ for (const ep of m.streamingEpisodes ?? []) {
1398
+ const match = String(ep?.title ?? "").match(/Episode\s+(\d+)\s*[-–:]\s*(.+)/i);
1399
+ if (match)
1400
+ episodeNames[Number(match[1])] = match[2].trim();
1401
+ }
1402
+ if (!romaji || episodes <= 0)
1403
+ return null;
1404
+ const english = m.title?.english && m.title.english !== romaji ? m.title.english : undefined;
1405
+ const synonyms = Array.isArray(m.synonyms) && m.synonyms.length ? m.synonyms : undefined;
1406
+ return { romaji, episodes, episodeNames, english, synonyms };
1407
+ }
1408
+ function normKey(s) {
1409
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "");
1410
+ }
1411
+ function animeMatches(a, title) {
1412
+ const want = normKey(title);
1413
+ return want !== "" && [a.romaji, a.english ?? "", ...a.synonyms ?? []].some((t) => normKey(t) === want);
1414
+ }
1415
+ async function findAnime(title) {
1416
+ try {
1417
+ const res = await fetch("https://graphql.anilist.co", {
1418
+ method: "POST",
1419
+ headers: { "Content-Type": "application/json", "User-Agent": UA },
1420
+ body: JSON.stringify({
1421
+ query: "query($q:String){Page(perPage:5){media(search:$q,type:ANIME){episodes synonyms title{romaji english} nextAiringEpisode{episode} streamingEpisodes{title}}}}",
1422
+ variables: { q: title }
1423
+ })
1424
+ });
1425
+ if (!res.ok)
1426
+ return null;
1427
+ const list = (await res.json()).data?.Page?.media ?? [];
1428
+ for (const entry of list) {
1429
+ const anime = parseAnime(entry);
1430
+ if (anime && animeMatches(anime, title))
1431
+ return anime;
1432
+ }
1433
+ return null;
1434
+ } catch {
1435
+ return null;
1436
+ }
1437
+ }
1438
+ var NON_LATIN = /[Ѐ-ۿ֐-׿฀-๿぀-ヿ㐀-鿿가-힯]/;
1439
+ function plainTitle(romaji) {
1440
+ return romaji.replace(/\b(\d+(?:st|nd|rd|th)\s+season|season\s+\d+|part\s+\d+|cour\s+\d+)\b/gi, "").replace(/\s+/g, " ").trim();
1441
+ }
1442
+ function animeTitles(a) {
1443
+ const seen = new Set;
1444
+ const out = [];
1445
+ for (const t of [a.romaji, a.english ?? "", ...a.synonyms ?? []]) {
1446
+ const clean = plainTitle(t);
1447
+ const key = clean.toLowerCase();
1448
+ if (clean && !NON_LATIN.test(clean) && /[a-z]/i.test(clean) && !seen.has(key)) {
1449
+ seen.add(key);
1450
+ out.push(clean);
1451
+ }
1452
+ }
1453
+ return out.slice(0, 4);
1454
+ }
1455
+ function animeQueries(titles, episode, dub) {
1456
+ const padded = String(episode).padStart(2, "0");
1457
+ const numbers = padded === String(episode) ? [padded] : [padded, String(episode)];
1458
+ const out = [];
1459
+ for (const t of titles) {
1460
+ for (const n of numbers)
1461
+ out.push(dub ? `${t} ${n} dual audio` : `${t} ${n}`);
1462
+ }
1463
+ return out.slice(0, 12);
1464
+ }
1465
+
1466
+ // src/look.tsx
1467
+ import { Box, Text } from "ink";
1468
+ import { useEffect, useState } from "react";
1469
+ import { jsx, jsxs } from "react/jsx-runtime";
1470
+ var C = {
1471
+ accent: "#3DF5FF",
1472
+ bright: "#9FFBFF",
1473
+ deep: "#1B6FA8",
1474
+ text: "#E8F1F5",
1475
+ mute: "#7D8A9A",
1476
+ rule: "#4A5A6E",
1477
+ bulb: "#FFD27A",
1478
+ good: "#7BE3A8",
1479
+ warn: "#FFB86B",
1480
+ bad: "#FF3DCB",
1481
+ ink: "#060A12"
1482
+ };
1483
+ function mix(from, to, t) {
1484
+ let out = "#";
1485
+ for (let i = 1;i < 7; i += 2) {
1486
+ const a = parseInt(from.slice(i, i + 2), 16);
1487
+ const b = parseInt(to.slice(i, i + 2), 16);
1488
+ out += Math.round(a + (b - a) * t).toString(16).padStart(2, "0");
1489
+ }
1490
+ return out;
1491
+ }
1492
+ function useTick(ms, on, limit = Infinity) {
1493
+ const [tick, setTick] = useState(0);
1494
+ useEffect(() => {
1495
+ if (!on)
1496
+ return;
1497
+ let count = 0;
1498
+ const timer = setInterval(() => {
1499
+ count++;
1500
+ setTick((n) => n + 1);
1501
+ if (count >= limit)
1502
+ clearInterval(timer);
1503
+ }, ms);
1504
+ return () => clearInterval(timer);
1505
+ }, [ms, on, limit]);
1506
+ return tick;
1507
+ }
1508
+ var WORD = ["█▀▀ █ █ █▀▀ █▄▀", "█▀ █▄▄ █ █▄▄ █ █"];
1509
+ var MARQUEE_WIDTH = WORD[0].length + 6;
1510
+ function bulbPath(width) {
1511
+ const path = [];
1512
+ for (let col = 0;col < width; col += 2)
1513
+ path.push([0, col]);
1514
+ path.push([1, width - 1], [2, width - 1]);
1515
+ for (let col = width - 1;col >= 0; col -= 2)
1516
+ path.push([3, col]);
1517
+ path.push([2, 0], [1, 0]);
1518
+ return path;
1519
+ }
1520
+ function Marquee({ chase = false }) {
1521
+ const tick = useTick(350, chase, 9);
1522
+ const lit = new Map;
1523
+ bulbPath(MARQUEE_WIDTH).forEach(([row, col], i) => lit.set(`${row},${col}`, (i + (chase ? tick : 0)) % 3 === 0));
1524
+ const bulb = (row, col) => {
1525
+ const on = lit.get(`${row},${col}`);
1526
+ return /* @__PURE__ */ jsx(Text, {
1527
+ color: on ? C.bulb : C.rule,
1528
+ children: on ? "●" : "○"
1529
+ }, col);
1530
+ };
1531
+ const edge = (row) => {
1532
+ const cells = [];
1533
+ for (let col = 0;col < MARQUEE_WIDTH; col++)
1534
+ cells.push(col % 2 === 0 || col === MARQUEE_WIDTH - 1 ? bulb(row, col) : /* @__PURE__ */ jsx(Text, {
1535
+ children: " "
1536
+ }, col));
1537
+ return /* @__PURE__ */ jsx(Text, {
1538
+ children: cells
1539
+ });
1540
+ };
1541
+ return /* @__PURE__ */ jsxs(Box, {
1542
+ flexDirection: "column",
1543
+ flexShrink: 0,
1544
+ children: [
1545
+ edge(0),
1546
+ WORD.map((line, i) => /* @__PURE__ */ jsxs(Text, {
1547
+ children: [
1548
+ bulb(i + 1, 0),
1549
+ " ",
1550
+ /* @__PURE__ */ jsx(Text, {
1551
+ bold: true,
1552
+ color: i === 0 ? C.bright : C.accent,
1553
+ children: line
1554
+ }),
1555
+ " ",
1556
+ bulb(i + 1, MARQUEE_WIDTH - 1)
1557
+ ]
1558
+ }, i)),
1559
+ edge(3)
1560
+ ]
1561
+ });
1562
+ }
1563
+ function FilmStrip({ percent, width, rolling }) {
1564
+ const tick = useTick(400, rolling);
1565
+ const frames = Math.max(4, Math.floor(width / 3));
1566
+ const filled = Math.round(Math.max(0, Math.min(100, percent)) / 100 * frames);
1567
+ const shift = rolling ? tick % 3 : 0;
1568
+ const holes = " ▪ ".repeat(frames + 1).slice(shift, shift + frames * 3);
1569
+ const cells = [];
1570
+ for (let i = 0;i < frames; i++) {
1571
+ const color = i < filled ? mix(C.deep, C.accent, i / Math.max(1, frames - 1)) : C.rule;
1572
+ cells.push(/* @__PURE__ */ jsxs(Text, {
1573
+ color,
1574
+ children: [
1575
+ i < filled ? "██" : "░░",
1576
+ " "
1577
+ ]
1578
+ }, i));
1579
+ }
1580
+ return /* @__PURE__ */ jsxs(Box, {
1581
+ flexDirection: "column",
1582
+ flexShrink: 0,
1583
+ children: [
1584
+ /* @__PURE__ */ jsx(Text, {
1585
+ color: C.mute,
1586
+ children: holes
1587
+ }),
1588
+ /* @__PURE__ */ jsx(Text, {
1589
+ children: cells
1590
+ }),
1591
+ /* @__PURE__ */ jsx(Text, {
1592
+ color: C.mute,
1593
+ children: holes
1594
+ })
1595
+ ]
1596
+ });
1597
+ }
1598
+ function Hints({ hints, message }) {
1599
+ if (message) {
1600
+ return /* @__PURE__ */ jsx(Text, {
1601
+ color: C.accent,
1602
+ wrap: "truncate",
1603
+ children: message
1604
+ });
1605
+ }
1606
+ return /* @__PURE__ */ jsx(Text, {
1607
+ wrap: "truncate",
1608
+ children: hints.map(([keys, label], i) => /* @__PURE__ */ jsxs(Text, {
1609
+ children: [
1610
+ i ? " " : "",
1611
+ /* @__PURE__ */ jsx(Text, {
1612
+ color: C.accent,
1613
+ bold: true,
1614
+ children: keys
1615
+ }),
1616
+ /* @__PURE__ */ jsxs(Text, {
1617
+ color: C.mute,
1618
+ children: [
1619
+ " ",
1620
+ label
1621
+ ]
1622
+ })
1623
+ ]
1624
+ }, keys + label))
1625
+ });
1626
+ }
1627
+ function Badge({ text, color }) {
1628
+ return /* @__PURE__ */ jsx(Text, {
1629
+ backgroundColor: color,
1630
+ color: C.ink,
1631
+ bold: true,
1632
+ children: ` ${text} `
1633
+ });
1634
+ }
1635
+ var SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
1636
+ function Spinner({ color = C.accent }) {
1637
+ const tick = useTick(90, true);
1638
+ return /* @__PURE__ */ jsx(Text, {
1639
+ color,
1640
+ children: SPINNER[tick % SPINNER.length]
1641
+ });
1642
+ }
1643
+ function spaced(label) {
1644
+ return label.toUpperCase().split("").join(" ");
1645
+ }
1646
+ function thumbRows(total, from, visible, height) {
1647
+ const rows = new Array(height).fill(false);
1648
+ if (total <= visible || height <= 0)
1649
+ return rows;
1650
+ const size = Math.max(1, Math.round(visible / total * height));
1651
+ const start = Math.min(height - size, Math.round(from / (total - visible) * (height - size)));
1652
+ for (let i = start;i < start + size; i++)
1653
+ rows[i] = true;
1654
+ return rows;
1655
+ }
1656
+ function Scrollbar({ total, from, visible, height }) {
1657
+ const thumb = thumbRows(total, from, visible, height);
1658
+ if (!thumb.some(Boolean))
1659
+ return null;
1660
+ return /* @__PURE__ */ jsx(Box, {
1661
+ flexDirection: "column",
1662
+ marginLeft: 1,
1663
+ flexShrink: 0,
1664
+ children: thumb.map((on, i) => /* @__PURE__ */ jsx(Text, {
1665
+ color: on ? C.accent : C.rule,
1666
+ children: on ? "┃" : "│"
1667
+ }, i))
1668
+ });
1669
+ }
1670
+
1671
+ // src/poster.ts
1672
+ import { spawn as spawn5 } from "node:child_process";
1673
+ import { createHash } from "node:crypto";
1674
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
1675
+ import { join as join6 } from "node:path";
1676
+ var POSTER_DIR = join6(CACHE_DIR, "posters");
1677
+ var POSTERS = process.platform === "darwin" && !process.env.TMUX && (process.env.TERM_PROGRAM === "ghostty" || process.env.TERM === "xterm-kitty" || Boolean(process.env.KITTY_WINDOW_ID));
1678
+ function posterSize(rows) {
1679
+ return { cols: Math.round(rows * 4 / 3), rows };
1680
+ }
1681
+ var CELL = "\uDBFB\uDEEE";
1682
+ var MARKS = [
1683
+ 773,
1684
+ 781,
1685
+ 782,
1686
+ 784,
1687
+ 786,
1688
+ 829,
1689
+ 830,
1690
+ 831,
1691
+ 838,
1692
+ 842,
1693
+ 843,
1694
+ 844,
1695
+ 848,
1696
+ 849,
1697
+ 850,
1698
+ 855,
1699
+ 859,
1700
+ 867,
1701
+ 868,
1702
+ 869,
1703
+ 870,
1704
+ 871,
1705
+ 872,
1706
+ 873,
1707
+ 874,
1708
+ 875,
1709
+ 876,
1710
+ 877,
1711
+ 878,
1712
+ 879
1713
+ ].map((code) => String.fromCodePoint(code));
1714
+ function placeholderLines(id, cols, rows) {
1715
+ const colour = `\x1B[38;2;${id >> 16 & 255};${id >> 8 & 255};${id & 255}m`;
1716
+ const lines = [];
1717
+ for (let row = 0;row < rows; row++) {
1718
+ lines.push(colour + CELL + MARKS[row] + MARKS[0] + CELL.repeat(cols - 1) + "\x1B[39m");
1719
+ }
1720
+ return lines;
1721
+ }
1722
+ var shown = new Map;
1723
+ var loading = new Set;
1724
+ var nextId = 1 + Math.floor(Math.random() * 16773120);
1725
+ function posterId(url, cols, rows) {
1726
+ return shown.get(`${url}|${cols}|${rows}`) ?? null;
1727
+ }
1728
+ var tints = new Map;
1729
+ function posterTint(url) {
1730
+ return tints.get(url) ?? null;
1731
+ }
1732
+ var posterEvents = { onReady: () => {} };
1733
+ async function loadPoster(url, cols, rows) {
1734
+ const key = `${url}|${cols}|${rows}`;
1735
+ if (!POSTERS || !url || shown.has(key) || loading.has(key))
1736
+ return;
1737
+ loading.add(key);
1738
+ try {
1739
+ const png = await posterPng(url);
1740
+ if (!tints.has(url))
1741
+ tints.set(url, await posterColour(png));
1742
+ const id = nextId++;
1743
+ sendPicture(id, readFileSync4(png), cols, rows);
1744
+ shown.set(key, id);
1745
+ posterEvents.onReady();
1746
+ } catch {} finally {
1747
+ loading.delete(key);
1748
+ }
1749
+ }
1750
+ async function posterColour(png) {
1751
+ const saved = png.replace(/\.png$/, ".tint");
1752
+ if (existsSync7(saved))
1753
+ return readFileSync4(saved, "utf-8");
1754
+ const bmp = png.replace(/\.png$/, ".bmp");
1755
+ await run2("sips", ["-s", "format", "bmp", "-z", "1", "1", png, "--out", bmp]);
1756
+ const data = readFileSync4(bmp);
1757
+ rmSync3(bmp, { force: true });
1758
+ const at = data.readUInt32LE(10);
1759
+ const tint = tintFrom(data[at + 2], data[at + 1], data[at]);
1760
+ writeFileSync4(saved, tint);
1761
+ return tint;
1762
+ }
1763
+ function tintFrom(r, g, b) {
1764
+ const [rf, gf, bf] = [r / 255, g / 255, b / 255];
1765
+ const max = Math.max(rf, gf, bf);
1766
+ const min = Math.min(rf, gf, bf);
1767
+ let l = (max + min) / 2;
1768
+ let s = 0;
1769
+ let h = 0;
1770
+ if (max !== min) {
1771
+ const d = max - min;
1772
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
1773
+ if (max === rf)
1774
+ h = (gf - bf) / d + (gf < bf ? 6 : 0);
1775
+ else if (max === gf)
1776
+ h = (bf - rf) / d + 2;
1777
+ else
1778
+ h = (rf - gf) / d + 4;
1779
+ h /= 6;
1780
+ }
1781
+ l = Math.min(0.8, Math.max(0.62, l));
1782
+ if (s > 0.08)
1783
+ s = Math.max(0.5, s);
1784
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
1785
+ const p = 2 * l - q;
1786
+ const channel = (t) => {
1787
+ if (t < 0)
1788
+ t += 1;
1789
+ if (t > 1)
1790
+ t -= 1;
1791
+ if (t < 1 / 6)
1792
+ return p + (q - p) * 6 * t;
1793
+ if (t < 1 / 2)
1794
+ return q;
1795
+ if (t < 2 / 3)
1796
+ return p + (q - p) * (2 / 3 - t) * 6;
1797
+ return p;
1798
+ };
1799
+ const hex = (x) => Math.round(x * 255).toString(16).padStart(2, "0");
1800
+ return `#${hex(channel(h + 1 / 3))}${hex(channel(h))}${hex(channel(h - 1 / 3))}`.toUpperCase();
1801
+ }
1802
+ async function posterPng(url) {
1803
+ mkdirSync5(POSTER_DIR, { recursive: true });
1804
+ const sized = url.replace(/\._V1_.*\.jpg$/, "._V1_SX400.jpg");
1805
+ const name = createHash("sha1").update(sized).digest("hex");
1806
+ const png = join6(POSTER_DIR, `${name}.png`);
1807
+ if (!existsSync7(png)) {
1808
+ const res = await fetch(sized);
1809
+ if (!res.ok)
1810
+ throw new Error(`poster ${res.status}`);
1811
+ const jpg = join6(POSTER_DIR, `${name}.jpg`);
1812
+ writeFileSync4(jpg, Buffer.from(await res.arrayBuffer()));
1813
+ await run2("sips", ["-s", "format", "png", jpg, "--out", png]);
1814
+ rmSync3(jpg, { force: true });
1815
+ }
1816
+ return png;
1817
+ }
1818
+ function sendPicture(id, png, cols, rows) {
1819
+ const data = png.toString("base64");
1820
+ let out = "";
1821
+ for (let i = 0;i < data.length; i += 4096) {
1822
+ const more = i + 4096 < data.length ? 1 : 0;
1823
+ const head = i === 0 ? `a=t,f=100,i=${id},q=2,m=${more}` : `m=${more}`;
1824
+ out += `\x1B_G${head};${data.slice(i, i + 4096)}\x1B\\`;
1825
+ }
1826
+ out += `\x1B_Ga=p,U=1,i=${id},c=${cols},r=${rows},q=2\x1B\\`;
1827
+ process.stdout.write(out);
1828
+ }
1829
+ function run2(program, args) {
1830
+ return new Promise((resolve, reject) => {
1831
+ const child = spawn5(program, args, { stdio: "ignore" });
1832
+ child.on("error", reject);
1833
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`${program} exited ${code}`)));
1834
+ });
1835
+ }
1836
+
1837
+ // src/watch.ts
1838
+ async function watch(options) {
1839
+ const { title, engine, onStatus } = options;
1840
+ onStatus("finding peers…");
1841
+ const stream = await engine.open(withTrackers(options.torrent.magnet));
1842
+ const video = stream.videos[0];
1843
+ if (!video) {
1844
+ await stream.stop();
1845
+ throw new Error("this torrent has no video file in it, pick another source");
1846
+ }
1847
+ onStatus("looking for English subtitles…");
1848
+ const torrentSub = stream.subtitles[0] ? { url: stream.urlOf(stream.subtitles[0]), name: stream.subtitles[0].name } : null;
1849
+ const subs = await englishSubtitles(title?.id ?? "", torrentSub);
1850
+ if (title) {
1851
+ recordPlay({ id: title.id, name: title.name, year: title.year, kind: title.kind, poster: title.poster, season: options.episode?.season, episode: options.episode?.number }, options.episode?.tag);
1852
+ }
1853
+ touchFilm(stream.folder);
1854
+ trimCache(options.cacheGB, stream.folder);
1855
+ onStatus(`playing in ${options.player}${subs ? ", English subtitles on" : ""}`);
1856
+ const playing = play(options.player, { url: stream.urlOf(video), title: options.name, subtitle: subs?.path ?? null, vtt: subs?.vtt ?? null });
1857
+ const timer = setInterval(async () => options.onProgress(await stream.progress()), 2000);
1858
+ const closed = playing.closed.then(async () => {
1859
+ clearInterval(timer);
1860
+ await stream.stop();
1861
+ });
1862
+ return { closed, stop: () => playing.stop() };
1863
+ }
1864
+
1865
+ // src/ui.tsx
1866
+ import { jsx as jsx2, jsxs as jsxs2, Fragment } from "react/jsx-runtime";
1867
+ var RES_COLOR = { "2160p": "#FFB86B", "1080p": "#3DF5FF", "720p": "#7D8A9A", "480p": "#4A5A6E" };
1868
+ function resolutionLabel(res) {
1869
+ return res === "2160p" ? "4K" : res || "SD";
1870
+ }
1871
+ var SOURCE_COLOR = { YTS: C.good, EZTV: C.warn, TPB: "#6FC8FF", Nyaa: "#C9A7FF" };
1872
+ var SECTIONS = ["Continue", "Now showing", "Shows"];
1873
+ function App(props) {
1874
+ const { exit } = useApp();
1875
+ const { rows: height, columns: width } = useWindowSize();
1876
+ const [splash, setSplash] = useState2(!props.initialQuery);
1877
+ const [query, setQuery] = useState2(props.initialQuery);
1878
+ const [section, setSection] = useState2("Continue");
1879
+ const [home, setHome] = useState2({ Continue: [], "Now showing": [], Shows: [] });
1880
+ const [results, setResults] = useState2([]);
1881
+ const [selected, setSelected] = useState2(0);
1882
+ const [screen, setScreen] = useState2({ kind: "browse" });
1883
+ const [busy, setBusy] = useState2("");
1884
+ const [toast, setToast] = useState2(null);
1885
+ const toastTimer = useRef(undefined);
1886
+ const [showHelp, setShowHelp] = useState2(false);
1887
+ const session = useRef(null);
1888
+ const searchId = useRef(0);
1889
+ const sourcesId = useRef(0);
1890
+ const moved = useRef(false);
1891
+ const selectedHash = useRef("");
1892
+ const uploads = useRef([]);
1893
+ const couch = props.couch;
1894
+ const [, redraw] = useState2(0);
1895
+ function showToast(text, kind = "ok") {
1896
+ setToast({ text, kind });
1897
+ clearTimeout(toastTimer.current);
1898
+ toastTimer.current = setTimeout(() => setToast(null), 2500);
1899
+ }
1900
+ useEffect2(() => {
1901
+ posterEvents.onReady = () => redraw((n) => n + 1);
1902
+ }, []);
1903
+ useEffect2(() => {
1904
+ if (!couch)
1905
+ return;
1906
+ let before = couch.room.people();
1907
+ couch.onUpdate = () => {
1908
+ const now = couch.room.people();
1909
+ for (const name of now)
1910
+ if (!before.includes(name))
1911
+ showToast(`${name} joined`);
1912
+ for (const name of before)
1913
+ if (!now.includes(name))
1914
+ showToast(`${name} left`);
1915
+ before = now;
1916
+ redraw((n) => n + 1);
1917
+ };
1918
+ const timer = setInterval(() => {
1919
+ const now = Date.now();
1920
+ uploads.current = [...uploads.current, [now, couch.room.sentBytes]].filter(([at]) => now - at <= 30000);
1921
+ redraw((n) => n + 1);
1922
+ }, 2000);
1923
+ return () => clearInterval(timer);
1924
+ }, [couch]);
1925
+ useEffect2(() => {
1926
+ const history = continueRows(loadHistory());
1927
+ setHome((h) => ({ ...h, Continue: history }));
1928
+ if (!history.length)
1929
+ setSection("Now showing");
1930
+ Promise.all([trending("movie"), trending("tvSeries")]).then(([films, shows]) => {
1931
+ setHome((h) => ({ ...h, "Now showing": films.map((title) => ({ title, note: "" })), Shows: shows.map((title) => ({ title, note: "" })) }));
1932
+ });
1933
+ }, []);
1934
+ useEffect2(() => {
1935
+ const id = ++searchId.current;
1936
+ if (!query.trim())
1937
+ return;
1938
+ const timer = setTimeout(async () => {
1939
+ setBusy("searching…");
1940
+ const found = await searchTitles(query);
1941
+ if (id !== searchId.current)
1942
+ return;
1943
+ setResults(found.map((title) => ({ title, note: "" })));
1944
+ setSelected(0);
1945
+ setBusy("");
1946
+ }, 250);
1947
+ return () => clearTimeout(timer);
1948
+ }, [query]);
1949
+ const rows = query.trim() ? results : home[section];
1950
+ async function openTitle(title) {
1951
+ if (couch && isSeries(title)) {
1952
+ showToast("couch plays films only", "no");
1953
+ return;
1954
+ }
1955
+ if (!isSeries(title))
1956
+ return openSources({ kind: "film", title }, `${title.name}${title.year ? ` (${title.year})` : ""}`);
1957
+ setBusy(`loading ${title.name}…`);
1958
+ const anime = await findAnime(title.name);
1959
+ if (anime) {
1960
+ const list = Array.from({ length: anime.episodes }, (_, i) => ({
1961
+ season: 1,
1962
+ number: i + 1,
1963
+ name: anime.episodeNames[i + 1] ?? "",
1964
+ plot: "",
1965
+ date: "",
1966
+ minutes: 0
1967
+ }));
1968
+ setScreen({ kind: "episodes", title, anime, seasons: [1], season: 1, list });
1969
+ } else {
1970
+ const all = await seasons(title.id);
1971
+ const last = loadHistory().find((w) => w.id === title.id);
1972
+ const season = last?.season && all.includes(last.season) ? last.season : all[0] ?? 1;
1973
+ setScreen({ kind: "episodes", title, anime: null, seasons: all, season, list: await episodes(title.id, season) });
1974
+ }
1975
+ setSelected(resumeIndex(title.id));
1976
+ setBusy("");
1977
+ }
1978
+ async function openSources(wanted, label, episodeTag) {
1979
+ const id = ++sourcesId.current;
1980
+ moved.current = false;
1981
+ setScreen({ kind: "sources", wanted, label, episodeTag, report: null, hidden: 0 });
1982
+ setSelected(0);
1983
+ await findSources(wanted, (report) => {
1984
+ if (id !== sourcesId.current)
1985
+ return;
1986
+ const torrents = couch ? report.torrents.filter((t) => browserPlayable(t.name)) : report.torrents;
1987
+ const next = sourceEntries(torrents);
1988
+ setScreen((s) => s.kind === "sources" ? { ...s, report: { ...report, torrents }, hidden: report.torrents.length - torrents.length } : s);
1989
+ const keep = moved.current ? next.findIndex((e) => ("torrent" in e) && e.torrent.infoHash === selectedHash.current) : -1;
1990
+ setSelected(keep >= 0 ? keep : firstRow(next));
1991
+ });
1992
+ }
1993
+ async function startWatching(torrent, title, label, episode) {
1994
+ setSplash(false);
1995
+ setScreen({ kind: "playing", label, title, torrent, status: "starting…", progress: null, error: null });
1996
+ const update = (change) => setScreen((s) => s.kind === "playing" ? { ...s, ...change } : s);
1997
+ if (couch) {
1998
+ if (!title)
1999
+ return update({ error: "couch needs a film picked from search (it shows its details at the end)" });
2000
+ try {
2001
+ await couch.play(props.engine, title, torrent, (status) => update({ status }));
2002
+ const timer = setInterval(async () => {
2003
+ const progress = await couch.progress();
2004
+ if (progress)
2005
+ update({ progress });
2006
+ else
2007
+ clearInterval(timer);
2008
+ }, 2000);
2009
+ } catch (error) {
2010
+ update({ error: error instanceof Error ? error.message : String(error) });
2011
+ }
2012
+ return;
2013
+ }
2014
+ try {
2015
+ const current = await watch({
2016
+ title,
2017
+ name: label,
2018
+ episode,
2019
+ torrent,
2020
+ engine: props.engine,
2021
+ player: props.player,
2022
+ cacheGB: props.cacheGB,
2023
+ onStatus: (status) => update({ status }),
2024
+ onProgress: (progress) => update({ progress })
2025
+ });
2026
+ session.current = current;
2027
+ await current.closed;
2028
+ session.current = null;
2029
+ setScreen({ kind: "browse" });
2030
+ setQuery("");
2031
+ } catch (error) {
2032
+ update({ error: error instanceof Error ? error.message : String(error) });
2033
+ }
2034
+ }
2035
+ usePaste((text) => {
2036
+ const hash = hashOf(text.trim());
2037
+ if (!hash || screen.kind === "playing") {
2038
+ if (screen.kind === "browse") {
2039
+ setSplash(false);
2040
+ setQuery((q) => q + text.replace(/\s+/g, " "));
2041
+ }
2042
+ return;
2043
+ }
2044
+ const name = decodeURIComponent(text.match(/[?&]dn=([^&]+)/)?.[1] ?? "pasted magnet").replace(/\+/g, " ");
2045
+ const magnet = text.startsWith("magnet:") ? text.trim() : magnetFromHash(hash, name);
2046
+ startWatching({ name, infoHash: hash, magnet, seeders: 0, bytes: 0, source: "pasted" }, null, name);
2047
+ });
2048
+ const sourceList = screen.kind === "sources" && screen.report ? sourceEntries(screen.report.torrents) : [];
2049
+ const picked = sourceList[selected];
2050
+ selectedHash.current = picked && "torrent" in picked ? picked.torrent.infoHash : "";
2051
+ useInput((input, key) => {
2052
+ if (key.ctrl && input === "c")
2053
+ return quit();
2054
+ if (showHelp)
2055
+ return setShowHelp(false);
2056
+ if (splash) {
2057
+ if (key.return) {
2058
+ setSplash(false);
2059
+ return setSelected(0);
2060
+ }
2061
+ if (key.escape)
2062
+ return query ? setQuery("") : quit();
2063
+ if (key.backspace || key.delete)
2064
+ return setQuery((q) => q.slice(0, -1));
2065
+ if (input && !key.ctrl && !key.meta) {
2066
+ setSplash(false);
2067
+ return setQuery((q) => q + input);
2068
+ }
2069
+ return;
2070
+ }
2071
+ if (screen.kind === "playing") {
2072
+ if (input === "c" && couch?.link) {
2073
+ copyToClipboard(couch.link);
2074
+ showToast("room link copied");
2075
+ return;
2076
+ }
2077
+ if (key.escape || input === "q" || key.return) {
2078
+ if (couch) {
2079
+ couch.stopFilm();
2080
+ setScreen({ kind: "browse" });
2081
+ } else if (session.current)
2082
+ session.current.stop();
2083
+ else
2084
+ setScreen({ kind: "browse" });
2085
+ }
2086
+ return;
2087
+ }
2088
+ if (screen.kind === "browse" && (key.leftArrow || key.rightArrow || key.upArrow || key.downArrow)) {
2089
+ const step = key.leftArrow || key.upArrow ? -1 : 1;
2090
+ return setSelected((i) => Math.max(0, Math.min(rows.length - 1, i + step)));
2091
+ }
2092
+ if (key.upArrow || key.downArrow) {
2093
+ const step = key.upArrow ? -1 : 1;
2094
+ if (screen.kind === "sources") {
2095
+ moved.current = true;
2096
+ return setSelected((i) => nextRow(sourceList, i, step));
2097
+ }
2098
+ if (screen.kind === "episodes")
2099
+ return setSelected((i) => Math.max(0, Math.min(screen.list.length - 1, i + step)));
2100
+ }
2101
+ if (screen.kind === "browse") {
2102
+ const row = rows[selected];
2103
+ if (key.tab) {
2104
+ const next = query ? section : SECTIONS[(SECTIONS.indexOf(section) + (key.shift ? SECTIONS.length - 1 : 1)) % SECTIONS.length];
2105
+ setQuery("");
2106
+ setSection(next);
2107
+ return setSelected(0);
2108
+ }
2109
+ if (key.return && row)
2110
+ return void openTitle(row.title);
2111
+ if (key.escape) {
2112
+ if (query)
2113
+ return setQuery("");
2114
+ return setSplash(true);
2115
+ }
2116
+ if (key.backspace || key.delete)
2117
+ return setQuery((q) => q.slice(0, -1));
2118
+ if (input === "?" && !query)
2119
+ return setShowHelp(true);
2120
+ if (input && !key.ctrl && !key.meta)
2121
+ return setQuery((q) => q + input);
2122
+ return;
2123
+ }
2124
+ if (key.escape || input === "q") {
2125
+ sourcesId.current++;
2126
+ setSelected(0);
2127
+ return setScreen({ kind: "browse" });
2128
+ }
2129
+ if (input === "?")
2130
+ return setShowHelp(true);
2131
+ if (screen.kind === "episodes") {
2132
+ const at = screen.seasons.indexOf(screen.season);
2133
+ const step = key.leftArrow ? -1 : key.rightArrow ? 1 : 0;
2134
+ const next = screen.seasons[at + step];
2135
+ if (step && next !== undefined) {
2136
+ episodes(screen.title.id, next).then((list) => setScreen({ ...screen, season: next, list }));
2137
+ return setSelected(0);
2138
+ }
2139
+ const ep = screen.list[selected];
2140
+ if (key.return && ep) {
2141
+ const tag = sxxeyy(ep.season, ep.number);
2142
+ const label = `${screen.title.name} ${screen.anime ? `episode ${ep.number}` : tag}`;
2143
+ const wanted = screen.anime ? { kind: "anime", title: screen.title, queries: animeQueries(animeTitles(screen.anime), ep.number, props.dub) } : { kind: "episode", title: screen.title, season: ep.season, episode: ep.number };
2144
+ return void openSources(wanted, label, tag);
2145
+ }
2146
+ return;
2147
+ }
2148
+ if (screen.kind === "sources" && key.return && picked && "torrent" in picked) {
2149
+ const ep = screen.wanted.kind === "episode" ? { season: screen.wanted.season, number: screen.wanted.episode, tag: screen.episodeTag ?? "" } : undefined;
2150
+ const animeEp = screen.wanted.kind === "anime" && screen.episodeTag ? { season: 1, number: Number(screen.episodeTag.slice(4)), tag: screen.episodeTag } : undefined;
2151
+ return void startWatching(picked.torrent, screen.wanted.title, screen.label, ep ?? animeEp);
2152
+ }
2153
+ });
2154
+ function resumeIndex(id) {
2155
+ const last = loadHistory().find((w) => w.id === id);
2156
+ return last?.episode ? Math.max(0, last.episode) : 0;
2157
+ }
2158
+ async function quit() {
2159
+ session.current?.stop();
2160
+ await couch?.close();
2161
+ await props.engine.shutdown();
2162
+ exit();
2163
+ }
2164
+ const searchText = query ? /* @__PURE__ */ jsxs2(Text2, {
2165
+ color: C.text,
2166
+ children: [
2167
+ query,
2168
+ /* @__PURE__ */ jsx2(Text2, {
2169
+ color: C.accent,
2170
+ children: "▌"
2171
+ })
2172
+ ]
2173
+ }) : /* @__PURE__ */ jsx2(Text2, {
2174
+ color: C.mute,
2175
+ children: "Search films and shows, or paste a magnet link…"
2176
+ });
2177
+ if (splash && !showHelp) {
2178
+ const boxWidth = Math.min(76, width - 4);
2179
+ const nowShowing = home["Now showing"].slice(0, 3).map((row) => row.title.name);
2180
+ return /* @__PURE__ */ jsxs2(Box2, {
2181
+ flexDirection: "column",
2182
+ height,
2183
+ alignItems: "center",
2184
+ justifyContent: "center",
2185
+ children: [
2186
+ /* @__PURE__ */ jsx2(Marquee, {
2187
+ chase: true
2188
+ }),
2189
+ /* @__PURE__ */ jsx2(Box2, {
2190
+ marginTop: 1,
2191
+ flexShrink: 0,
2192
+ children: /* @__PURE__ */ jsx2(Text2, {
2193
+ color: C.text,
2194
+ children: "Films and shows, streamed from torrents, played right away."
2195
+ })
2196
+ }),
2197
+ /* @__PURE__ */ jsxs2(Box2, {
2198
+ flexShrink: 0,
2199
+ height: 1,
2200
+ children: [
2201
+ /* @__PURE__ */ jsx2(Text2, {
2202
+ color: C.bulb,
2203
+ children: nowShowing.length ? "now showing " : " "
2204
+ }),
2205
+ /* @__PURE__ */ jsx2(Text2, {
2206
+ color: C.mute,
2207
+ children: nowShowing.join(" · ")
2208
+ })
2209
+ ]
2210
+ }),
2211
+ /* @__PURE__ */ jsxs2(Box2, {
2212
+ marginTop: 2,
2213
+ flexShrink: 0,
2214
+ flexDirection: "column",
2215
+ width: boxWidth,
2216
+ children: [
2217
+ /* @__PURE__ */ jsxs2(Text2, {
2218
+ children: [
2219
+ /* @__PURE__ */ jsx2(Text2, {
2220
+ color: C.accent,
2221
+ children: "⌕ "
2222
+ }),
2223
+ searchText
2224
+ ]
2225
+ }),
2226
+ /* @__PURE__ */ jsx2(Text2, {
2227
+ color: C.accent,
2228
+ children: "▔".repeat(boxWidth)
2229
+ })
2230
+ ]
2231
+ }),
2232
+ /* @__PURE__ */ jsx2(Box2, {
2233
+ marginTop: 1,
2234
+ children: /* @__PURE__ */ jsx2(Hints, {
2235
+ hints: [["⏎", "search"], ["empty ⏎", "browse"], ["^c", "quit"]],
2236
+ message: couch?.link ? `couch: ${couch.link}` : undefined
2237
+ })
2238
+ })
2239
+ ]
2240
+ });
2241
+ }
2242
+ const inner = width - 2;
2243
+ const big = posterSize(Math.max(8, Math.min(22, height - 19)));
2244
+ const small = posterSize(Math.round(big.rows * 0.6));
2245
+ const stageHeight = height - 5;
2246
+ const hints = screen.kind === "browse" ? [["←→", "browse"], ["⏎", "sources"], ["tab", "section"], ["type", "search"], ["esc", query ? "clear" : "home"]] : screen.kind === "episodes" ? [["↑↓", "episode"], ["←→", "season"], ["⏎", "sources"], ["esc", "back"]] : screen.kind === "sources" ? [["↑↓", "move"], ["⏎", couch ? "put it on in the room" : "play"], ["esc", "back"]] : couch ? [["c", "copy the room link"], ["esc", "take the film off"]] : [["esc", "stop"]];
2247
+ let body = null;
2248
+ if (showHelp) {
2249
+ body = /* @__PURE__ */ jsx2(Help, {});
2250
+ } else if (screen.kind === "browse") {
2251
+ const label = query.trim() ? busy ? "searching…" : `${rows.length} results` : `${rows.length} ${section === "Shows" ? "shows" : section === "Continue" ? "to continue" : "films"}`;
2252
+ body = /* @__PURE__ */ jsx2(Lobby, {
2253
+ rows,
2254
+ selected,
2255
+ width: inner,
2256
+ big,
2257
+ small,
2258
+ label,
2259
+ empty: query.trim() ? "Nothing found." : "Loading…"
2260
+ });
2261
+ } else if (screen.kind === "episodes") {
2262
+ body = /* @__PURE__ */ jsx2(Stage, {
2263
+ poster: screen.title.poster,
2264
+ big,
2265
+ children: /* @__PURE__ */ jsx2(EpisodeList, {
2266
+ screen,
2267
+ selected,
2268
+ height: stageHeight
2269
+ })
2270
+ });
2271
+ } else if (screen.kind === "sources") {
2272
+ body = /* @__PURE__ */ jsx2(Stage, {
2273
+ poster: screen.wanted.title.poster,
2274
+ big,
2275
+ children: /* @__PURE__ */ jsx2(SourceList, {
2276
+ screen,
2277
+ entries: sourceList,
2278
+ selected,
2279
+ height: stageHeight,
2280
+ couch: Boolean(couch),
2281
+ picked
2282
+ })
2283
+ });
2284
+ } else {
2285
+ body = /* @__PURE__ */ jsx2(Stage, {
2286
+ poster: screen.title?.poster ?? "",
2287
+ big,
2288
+ children: /* @__PURE__ */ jsx2(Playing, {
2289
+ screen,
2290
+ couch,
2291
+ upload: uploadRate(uploads.current),
2292
+ barWidth: Math.min(60, inner - big.cols - 6)
2293
+ })
2294
+ });
2295
+ }
2296
+ return /* @__PURE__ */ jsxs2(Box2, {
2297
+ flexDirection: "column",
2298
+ paddingX: 1,
2299
+ height,
2300
+ children: [
2301
+ /* @__PURE__ */ jsxs2(Box2, {
2302
+ justifyContent: "space-between",
2303
+ flexShrink: 0,
2304
+ children: [
2305
+ screen.kind !== "browse" ? /* @__PURE__ */ jsxs2(Text2, {
2306
+ wrap: "truncate",
2307
+ children: [
2308
+ /* @__PURE__ */ jsx2(Text2, {
2309
+ color: C.accent,
2310
+ bold: true,
2311
+ children: "flick"
2312
+ }),
2313
+ " ",
2314
+ trail(screen, query, section).map((part, i, all) => /* @__PURE__ */ jsxs2(Text2, {
2315
+ children: [
2316
+ i ? /* @__PURE__ */ jsx2(Text2, {
2317
+ color: C.rule,
2318
+ children: " › "
2319
+ }) : null,
2320
+ /* @__PURE__ */ jsx2(Text2, {
2321
+ color: i === all.length - 1 ? C.text : C.mute,
2322
+ children: part
2323
+ })
2324
+ ]
2325
+ }, i))
2326
+ ]
2327
+ }) : /* @__PURE__ */ jsxs2(Text2, {
2328
+ wrap: "truncate",
2329
+ children: [
2330
+ /* @__PURE__ */ jsx2(Text2, {
2331
+ color: C.accent,
2332
+ bold: true,
2333
+ children: "flick"
2334
+ }),
2335
+ " ",
2336
+ SECTIONS.map((name) => {
2337
+ const on = screen.kind === "browse" && !query.trim() && name === section;
2338
+ return /* @__PURE__ */ jsxs2(Text2, {
2339
+ children: [
2340
+ /* @__PURE__ */ jsx2(Text2, {
2341
+ color: on ? C.accent : C.mute,
2342
+ bold: on,
2343
+ underline: on,
2344
+ children: name.toLowerCase()
2345
+ }),
2346
+ " "
2347
+ ]
2348
+ }, name);
2349
+ })
2350
+ ]
2351
+ }),
2352
+ screen.kind === "browse" ? /* @__PURE__ */ jsxs2(Text2, {
2353
+ children: [
2354
+ /* @__PURE__ */ jsx2(Text2, {
2355
+ color: C.accent,
2356
+ children: "⌕ "
2357
+ }),
2358
+ query ? /* @__PURE__ */ jsxs2(Text2, {
2359
+ color: C.text,
2360
+ children: [
2361
+ query,
2362
+ /* @__PURE__ */ jsx2(Text2, {
2363
+ color: C.accent,
2364
+ children: "▌"
2365
+ })
2366
+ ]
2367
+ }) : /* @__PURE__ */ jsx2(Text2, {
2368
+ color: C.mute,
2369
+ children: "type to search"
2370
+ })
2371
+ ]
2372
+ }) : null
2373
+ ]
2374
+ }),
2375
+ /* @__PURE__ */ jsx2(Box2, {
2376
+ marginTop: 1,
2377
+ flexGrow: 1,
2378
+ flexDirection: "column",
2379
+ overflow: "hidden",
2380
+ children: body
2381
+ }),
2382
+ /* @__PURE__ */ jsxs2(Box2, {
2383
+ justifyContent: "space-between",
2384
+ flexShrink: 0,
2385
+ children: [
2386
+ /* @__PURE__ */ jsx2(Hints, {
2387
+ hints,
2388
+ message: busy && screen.kind !== "browse" ? busy : undefined
2389
+ }),
2390
+ toast ? /* @__PURE__ */ jsx2(Text2, {
2391
+ backgroundColor: toast.kind === "ok" ? C.accent : C.warn,
2392
+ color: C.ink,
2393
+ bold: true,
2394
+ children: ` ${toast.kind === "ok" ? "✓" : "–"} ${toast.text} `
2395
+ }) : width >= 100 || couch ? /* @__PURE__ */ jsx2(Status, {
2396
+ couch,
2397
+ engine: props.engine.name,
2398
+ player: props.player,
2399
+ playing: screen.kind === "playing"
2400
+ }) : null
2401
+ ]
2402
+ })
2403
+ ]
2404
+ });
2405
+ }
2406
+ function trail(screen, query, section) {
2407
+ const from = query.trim() ? `⌕ ${query.trim()}` : section.toLowerCase();
2408
+ if (screen.kind === "episodes")
2409
+ return [from, screen.title.name, screen.anime ? "episodes" : `season ${screen.season}`];
2410
+ if (screen.kind === "sources") {
2411
+ if (screen.wanted.kind === "film")
2412
+ return [from, screen.label];
2413
+ return [from, screen.wanted.title.name, screen.episodeTag ?? "", "sources"].filter(Boolean);
2414
+ }
2415
+ if (screen.kind === "playing")
2416
+ return screen.title ? [from, screen.label] : ["pasted magnet", screen.label];
2417
+ return [from];
2418
+ }
2419
+ function clip(text, width, lines) {
2420
+ const out = [];
2421
+ let line = "";
2422
+ for (const word of text.split(/\s+/).filter(Boolean)) {
2423
+ if (!line)
2424
+ line = word;
2425
+ else if (line.length + 1 + word.length <= width)
2426
+ line += " " + word;
2427
+ else {
2428
+ out.push(line);
2429
+ line = word;
2430
+ }
2431
+ }
2432
+ if (line)
2433
+ out.push(line);
2434
+ if (out.length <= lines)
2435
+ return out;
2436
+ const kept = out.slice(0, lines);
2437
+ const last = kept[lines - 1].slice(0, width - 1).replace(/[\s.,;:]+$/, "");
2438
+ kept[lines - 1] = last + "…";
2439
+ return kept;
2440
+ }
2441
+ function windowOf(length, selected, height) {
2442
+ const start = Math.max(0, Math.min(selected - Math.floor(height / 2), length - height));
2443
+ return [start, Math.min(length, start + height)];
2444
+ }
2445
+ function nextRow(entries, from, step) {
2446
+ let i = from + step;
2447
+ while (i >= 0 && i < entries.length && "heading" in entries[i])
2448
+ i += step;
2449
+ return i >= 0 && i < entries.length ? i : from;
2450
+ }
2451
+ function firstRow(entries) {
2452
+ return Math.max(0, entries.findIndex((e) => !("heading" in e)));
2453
+ }
2454
+ function continueRows(history) {
2455
+ return history.map((w) => ({
2456
+ title: { id: w.id, name: w.name, year: w.year, kind: w.kind, poster: w.poster, cast: "" },
2457
+ note: w.episode ? `${sxxeyy(w.season ?? 1, w.episode + 1)} next` : "watched"
2458
+ }));
2459
+ }
2460
+ function sourceEntries(torrents) {
2461
+ const pick = pickBest(torrents);
2462
+ const entries = [];
2463
+ if (pick)
2464
+ entries.push({ heading: "best pick" }, { torrent: pick, pick: true });
2465
+ for (const group of qualityGroups(torrents.filter((t) => t !== pick))) {
2466
+ entries.push({ heading: `${group.label} · ${group.torrents.length}` });
2467
+ for (const torrent of group.torrents)
2468
+ entries.push({ torrent, pick: false });
2469
+ }
2470
+ return entries;
2471
+ }
2472
+ function sourceTag(source) {
2473
+ if (/pirate/i.test(source))
2474
+ return "TPB";
2475
+ if (/^yts|yify/i.test(source))
2476
+ return "YTS";
2477
+ if (/eztv/i.test(source))
2478
+ return "EZTV";
2479
+ if (/nyaa/i.test(source))
2480
+ return "Nyaa";
2481
+ return source.replace(/\s+/g, "").slice(0, 6);
2482
+ }
2483
+ function clock(seconds) {
2484
+ const s = Math.max(0, Math.floor(seconds));
2485
+ const h = Math.floor(s / 3600);
2486
+ const mm = String(Math.floor(s % 3600 / 60)).padStart(h ? 2 : 1, "0");
2487
+ const ss = String(s % 60).padStart(2, "0");
2488
+ return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
2489
+ }
2490
+ function uploadRate(samples) {
2491
+ if (samples.length < 2)
2492
+ return null;
2493
+ const [t0, b0] = samples[0];
2494
+ const [t1, b1] = samples[samples.length - 1];
2495
+ return t1 > t0 ? (b1 - b0) * 1000 / (t1 - t0) : null;
2496
+ }
2497
+ function copyToClipboard(text) {
2498
+ process.stdout.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`);
2499
+ }
2500
+ var detailsCache = new Map;
2501
+ function useDetails(id) {
2502
+ const [, bump] = useState2(0);
2503
+ useEffect2(() => {
2504
+ if (!id || detailsCache.has(id))
2505
+ return;
2506
+ const timer = setTimeout(() => {
2507
+ details(id).then((d) => {
2508
+ detailsCache.set(id, d);
2509
+ bump((n) => n + 1);
2510
+ });
2511
+ }, 150);
2512
+ return () => clearTimeout(timer);
2513
+ }, [id]);
2514
+ return id ? detailsCache.get(id) ?? null : null;
2515
+ }
2516
+ function Status({ couch, engine, player, playing }) {
2517
+ if (!couch) {
2518
+ return /* @__PURE__ */ jsxs2(Text2, {
2519
+ color: C.mute,
2520
+ children: [
2521
+ engine,
2522
+ " · ",
2523
+ player
2524
+ ]
2525
+ });
2526
+ }
2527
+ if (couch.error)
2528
+ return /* @__PURE__ */ jsxs2(Text2, {
2529
+ color: C.bad,
2530
+ children: [
2531
+ "couch: ",
2532
+ couch.error
2533
+ ]
2534
+ });
2535
+ const people = couch.room.people();
2536
+ const what = playing ? engine : people.length ? people.join(", ") : couch.link ?? "opening the room…";
2537
+ return /* @__PURE__ */ jsxs2(Text2, {
2538
+ wrap: "truncate",
2539
+ children: [
2540
+ /* @__PURE__ */ jsx2(Text2, {
2541
+ color: C.bulb,
2542
+ children: "couch"
2543
+ }),
2544
+ /* @__PURE__ */ jsxs2(Text2, {
2545
+ color: C.mute,
2546
+ children: [
2547
+ " · ",
2548
+ what
2549
+ ]
2550
+ })
2551
+ ]
2552
+ });
2553
+ }
2554
+ function Pointer({ on }) {
2555
+ return /* @__PURE__ */ jsx2(Text2, {
2556
+ color: C.accent,
2557
+ children: on ? "▸ " : " "
2558
+ });
2559
+ }
2560
+ function Columns({ children }) {
2561
+ return /* @__PURE__ */ jsx2(Box2, {
2562
+ flexShrink: 0,
2563
+ children: /* @__PURE__ */ jsx2(Text2, {
2564
+ color: C.mute,
2565
+ wrap: "truncate",
2566
+ children
2567
+ })
2568
+ });
2569
+ }
2570
+ function SectionHeading({ text }) {
2571
+ return /* @__PURE__ */ jsx2(Box2, {
2572
+ flexShrink: 0,
2573
+ children: /* @__PURE__ */ jsxs2(Text2, {
2574
+ color: C.mute,
2575
+ wrap: "truncate",
2576
+ children: [
2577
+ " ── ",
2578
+ text
2579
+ ]
2580
+ })
2581
+ });
2582
+ }
2583
+ function Poster({ url, size, name = "", on = false }) {
2584
+ const [, bump] = useState2(0);
2585
+ useEffect2(() => {
2586
+ if (!POSTERS || !url || posterId(url, size.cols, size.rows))
2587
+ return;
2588
+ const timer = setTimeout(() => loadPoster(url, size.cols, size.rows).then(() => bump((n) => n + 1)), 120);
2589
+ return () => clearTimeout(timer);
2590
+ }, [url, size.cols, size.rows]);
2591
+ const id = POSTERS && url ? posterId(url, size.cols, size.rows) : null;
2592
+ if (id) {
2593
+ return /* @__PURE__ */ jsx2(Box2, {
2594
+ flexDirection: "column",
2595
+ width: size.cols,
2596
+ height: size.rows,
2597
+ flexShrink: 0,
2598
+ children: placeholderLines(id, size.cols, size.rows).map((line, i) => /* @__PURE__ */ jsx2(Text2, {
2599
+ children: line
2600
+ }, i))
2601
+ });
2602
+ }
2603
+ return /* @__PURE__ */ jsx2(Box2, {
2604
+ width: size.cols,
2605
+ height: size.rows,
2606
+ flexShrink: 0,
2607
+ borderStyle: "round",
2608
+ borderColor: on ? C.accent : C.rule,
2609
+ justifyContent: "center",
2610
+ alignItems: "center",
2611
+ paddingX: 1,
2612
+ children: /* @__PURE__ */ jsx2(Box2, {
2613
+ flexDirection: "column",
2614
+ alignItems: "center",
2615
+ children: POSTERS ? null : clip(name, size.cols - 4, size.rows - 2).map((line, i) => /* @__PURE__ */ jsx2(Text2, {
2616
+ color: on ? C.text : C.mute,
2617
+ wrap: "truncate",
2618
+ children: line
2619
+ }, i))
2620
+ })
2621
+ });
2622
+ }
2623
+ function Lobby({ rows, selected, width, big, small, label, empty }) {
2624
+ const fit = Math.max(1, 1 + Math.floor((width - big.cols - 2) / (small.cols + 2)));
2625
+ if (!rows.length) {
2626
+ if (empty !== "Loading…")
2627
+ return /* @__PURE__ */ jsx2(Text2, {
2628
+ color: C.mute,
2629
+ children: empty
2630
+ });
2631
+ return /* @__PURE__ */ jsxs2(Box2, {
2632
+ flexDirection: "column",
2633
+ children: [
2634
+ /* @__PURE__ */ jsxs2(Text2, {
2635
+ color: C.mute,
2636
+ children: [
2637
+ /* @__PURE__ */ jsx2(Spinner, {}),
2638
+ " loading what's on"
2639
+ ]
2640
+ }),
2641
+ /* @__PURE__ */ jsx2(Box2, {
2642
+ marginTop: 1,
2643
+ children: Array.from({ length: fit }, (_, i) => {
2644
+ const size = i === 0 ? big : small;
2645
+ return /* @__PURE__ */ jsxs2(Box2, {
2646
+ flexDirection: "column",
2647
+ marginRight: 2,
2648
+ flexShrink: 0,
2649
+ children: [
2650
+ i === 0 ? null : /* @__PURE__ */ jsx2(Box2, {
2651
+ height: big.rows - small.rows
2652
+ }),
2653
+ /* @__PURE__ */ jsx2(Box2, {
2654
+ width: size.cols,
2655
+ height: size.rows,
2656
+ borderStyle: "round",
2657
+ borderColor: C.rule
2658
+ })
2659
+ ]
2660
+ }, i);
2661
+ })
2662
+ })
2663
+ ]
2664
+ });
2665
+ }
2666
+ const [from, to] = windowOf(rows.length, selected, fit);
2667
+ const shown = rows.slice(from, to);
2668
+ const row = rows[selected];
2669
+ return /* @__PURE__ */ jsxs2(Box2, {
2670
+ flexDirection: "column",
2671
+ children: [
2672
+ /* @__PURE__ */ jsxs2(Text2, {
2673
+ color: C.mute,
2674
+ children: [
2675
+ label,
2676
+ " ",
2677
+ /* @__PURE__ */ jsx2(Text2, {
2678
+ color: from > 0 ? C.accent : C.rule,
2679
+ children: "‹ "
2680
+ }),
2681
+ /* @__PURE__ */ jsx2(Text2, {
2682
+ color: C.rule,
2683
+ children: `${selected + 1} of ${rows.length}`
2684
+ }),
2685
+ /* @__PURE__ */ jsx2(Text2, {
2686
+ color: to < rows.length ? C.accent : C.rule,
2687
+ children: " ›"
2688
+ })
2689
+ ]
2690
+ }),
2691
+ /* @__PURE__ */ jsx2(Box2, {
2692
+ marginTop: 1,
2693
+ flexShrink: 0,
2694
+ children: shown.map((r, i) => {
2695
+ const on = from + i === selected;
2696
+ const size = on ? big : small;
2697
+ const name = clip(r.title.name, size.cols, 2);
2698
+ return /* @__PURE__ */ jsxs2(Box2, {
2699
+ flexDirection: "column",
2700
+ width: size.cols,
2701
+ marginRight: 2,
2702
+ flexShrink: 0,
2703
+ children: [
2704
+ on ? null : /* @__PURE__ */ jsx2(Box2, {
2705
+ height: big.rows - small.rows,
2706
+ flexShrink: 0
2707
+ }),
2708
+ /* @__PURE__ */ jsx2(Poster, {
2709
+ url: r.title.poster,
2710
+ size,
2711
+ name: on ? r.title.name : "",
2712
+ on
2713
+ }),
2714
+ on ? /* @__PURE__ */ jsx2(Text2, {
2715
+ color: tintOf(r.title.poster),
2716
+ children: "▔".repeat(size.cols)
2717
+ }) : /* @__PURE__ */ jsxs2(Fragment, {
2718
+ children: [
2719
+ /* @__PURE__ */ jsx2(Text2, {
2720
+ color: C.mute,
2721
+ children: name[0] ?? " "
2722
+ }),
2723
+ /* @__PURE__ */ jsx2(Text2, {
2724
+ color: C.mute,
2725
+ children: name[1] ?? " "
2726
+ }),
2727
+ /* @__PURE__ */ jsxs2(Text2, {
2728
+ color: C.rule,
2729
+ wrap: "truncate",
2730
+ children: [
2731
+ r.title.year ?? "",
2732
+ isSeries(r.title) ? " · series" : ""
2733
+ ]
2734
+ })
2735
+ ]
2736
+ })
2737
+ ]
2738
+ }, r.title.id + r.note);
2739
+ })
2740
+ }),
2741
+ /* @__PURE__ */ jsx2(About, {
2742
+ title: row.title,
2743
+ note: row.note,
2744
+ width
2745
+ })
2746
+ ]
2747
+ });
2748
+ }
2749
+ function tintOf(poster) {
2750
+ return poster && posterTint(poster) || C.accent;
2751
+ }
2752
+ function Skeleton({ width }) {
2753
+ return /* @__PURE__ */ jsx2(Text2, {
2754
+ color: C.rule,
2755
+ children: "━".repeat(Math.max(1, width))
2756
+ });
2757
+ }
2758
+ function About({ title, note, width }) {
2759
+ const d = useDetails(title.id);
2760
+ const facts = [title.year, d?.minutes ? `${d.minutes} min` : null, d?.genres.join(", ")].filter(Boolean);
2761
+ const box = Math.min(width, 110);
2762
+ return /* @__PURE__ */ jsxs2(Box2, {
2763
+ flexDirection: "column",
2764
+ marginTop: 1,
2765
+ width: box,
2766
+ flexShrink: 0,
2767
+ children: [
2768
+ /* @__PURE__ */ jsxs2(Text2, {
2769
+ wrap: "truncate",
2770
+ children: [
2771
+ /* @__PURE__ */ jsx2(Text2, {
2772
+ color: tintOf(title.poster),
2773
+ bold: true,
2774
+ children: title.name.toUpperCase()
2775
+ }),
2776
+ " ",
2777
+ isSeries(title) ? /* @__PURE__ */ jsx2(Badge, {
2778
+ text: "series",
2779
+ color: C.warn
2780
+ }) : null,
2781
+ isSeries(title) && note ? " " : null,
2782
+ note ? /* @__PURE__ */ jsx2(Badge, {
2783
+ text: note,
2784
+ color: C.good
2785
+ }) : null
2786
+ ]
2787
+ }),
2788
+ /* @__PURE__ */ jsx2(Text2, {
2789
+ color: C.mute,
2790
+ wrap: "truncate",
2791
+ children: facts.join(" · ")
2792
+ }),
2793
+ d ? /* @__PURE__ */ jsxs2(Fragment, {
2794
+ children: [
2795
+ /* @__PURE__ */ jsxs2(Text2, {
2796
+ wrap: "truncate",
2797
+ children: [
2798
+ /* @__PURE__ */ jsx2(Text2, {
2799
+ color: C.rule,
2800
+ children: spaced("director") + " "
2801
+ }),
2802
+ /* @__PURE__ */ jsx2(Text2, {
2803
+ color: C.text,
2804
+ children: d.directors.join(", ") || "-"
2805
+ })
2806
+ ]
2807
+ }),
2808
+ /* @__PURE__ */ jsxs2(Text2, {
2809
+ wrap: "truncate",
2810
+ children: [
2811
+ /* @__PURE__ */ jsx2(Text2, {
2812
+ color: C.rule,
2813
+ children: spaced("cast") + " "
2814
+ }),
2815
+ /* @__PURE__ */ jsx2(Text2, {
2816
+ color: C.text,
2817
+ children: d.cast.join(", ") || "-"
2818
+ })
2819
+ ]
2820
+ }),
2821
+ /* @__PURE__ */ jsx2(Box2, {
2822
+ marginTop: 1,
2823
+ flexDirection: "column",
2824
+ children: clip(d.plot, box, 2).map((line, i) => /* @__PURE__ */ jsx2(Text2, {
2825
+ color: C.text,
2826
+ italic: true,
2827
+ children: line
2828
+ }, i))
2829
+ })
2830
+ ]
2831
+ }) : /* @__PURE__ */ jsxs2(Fragment, {
2832
+ children: [
2833
+ /* @__PURE__ */ jsx2(Skeleton, {
2834
+ width: 24
2835
+ }),
2836
+ /* @__PURE__ */ jsx2(Skeleton, {
2837
+ width: 40
2838
+ }),
2839
+ /* @__PURE__ */ jsxs2(Box2, {
2840
+ marginTop: 1,
2841
+ flexDirection: "column",
2842
+ children: [
2843
+ /* @__PURE__ */ jsx2(Skeleton, {
2844
+ width: box - 10
2845
+ }),
2846
+ /* @__PURE__ */ jsx2(Skeleton, {
2847
+ width: Math.round(box * 0.6)
2848
+ })
2849
+ ]
2850
+ })
2851
+ ]
2852
+ })
2853
+ ]
2854
+ });
2855
+ }
2856
+ function Stage({ poster, big, children }) {
2857
+ return /* @__PURE__ */ jsxs2(Box2, {
2858
+ flexShrink: 0,
2859
+ children: [
2860
+ POSTERS && poster ? /* @__PURE__ */ jsx2(Box2, {
2861
+ marginRight: 3,
2862
+ flexShrink: 0,
2863
+ children: /* @__PURE__ */ jsx2(Poster, {
2864
+ url: poster,
2865
+ size: big,
2866
+ on: true
2867
+ })
2868
+ }) : null,
2869
+ /* @__PURE__ */ jsx2(Box2, {
2870
+ flexDirection: "column",
2871
+ flexGrow: 1,
2872
+ children
2873
+ })
2874
+ ]
2875
+ });
2876
+ }
2877
+ function EpisodeList({ screen, selected, height }) {
2878
+ const last = loadHistory().find((w) => w.id === screen.title.id);
2879
+ const seen = new Set(last?.seen ?? []);
2880
+ const next = last?.episode && (last.season ?? 1) === screen.season ? last.episode + 1 : 0;
2881
+ const [from, to] = windowOf(screen.list.length, selected, Math.max(3, height - 9));
2882
+ const ep = screen.list[selected];
2883
+ return /* @__PURE__ */ jsxs2(Box2, {
2884
+ flexDirection: "column",
2885
+ children: [
2886
+ /* @__PURE__ */ jsx2(Text2, {
2887
+ color: tintOf(screen.title.poster),
2888
+ bold: true,
2889
+ wrap: "truncate",
2890
+ children: screen.title.name.toUpperCase()
2891
+ }),
2892
+ /* @__PURE__ */ jsx2(Text2, {
2893
+ wrap: "truncate",
2894
+ children: screen.anime ? /* @__PURE__ */ jsxs2(Text2, {
2895
+ color: C.mute,
2896
+ children: [
2897
+ screen.anime.romaji,
2898
+ " · ",
2899
+ screen.anime.episodes,
2900
+ " episodes"
2901
+ ]
2902
+ }) : screen.seasons.map((s) => /* @__PURE__ */ jsxs2(Text2, {
2903
+ children: [
2904
+ /* @__PURE__ */ jsx2(Text2, {
2905
+ color: s === screen.season ? C.accent : C.mute,
2906
+ bold: s === screen.season,
2907
+ underline: s === screen.season,
2908
+ children: `season ${s}`
2909
+ }),
2910
+ " "
2911
+ ]
2912
+ }, s))
2913
+ }),
2914
+ /* @__PURE__ */ jsxs2(Box2, {
2915
+ marginTop: 1,
2916
+ children: [
2917
+ /* @__PURE__ */ jsx2(Box2, {
2918
+ flexDirection: "column",
2919
+ width: 64,
2920
+ flexShrink: 1,
2921
+ children: screen.list.slice(from, to).map((e, i) => {
2922
+ const on = from + i === selected;
2923
+ const tag = sxxeyy(e.season, e.number);
2924
+ const when = [e.date, e.minutes ? `${e.minutes} min` : ""].filter(Boolean).join(" ");
2925
+ return /* @__PURE__ */ jsxs2(Box2, {
2926
+ flexShrink: 0,
2927
+ children: [
2928
+ /* @__PURE__ */ jsx2(Pointer, {
2929
+ on
2930
+ }),
2931
+ /* @__PURE__ */ jsx2(Box2, {
2932
+ flexGrow: 1,
2933
+ minWidth: 0,
2934
+ children: /* @__PURE__ */ jsxs2(Text2, {
2935
+ wrap: "truncate",
2936
+ children: [
2937
+ /* @__PURE__ */ jsxs2(Text2, {
2938
+ color: C.mute,
2939
+ children: [
2940
+ screen.anime ? String(e.number).padStart(3) : tag,
2941
+ " "
2942
+ ]
2943
+ }),
2944
+ /* @__PURE__ */ jsx2(Text2, {
2945
+ color: seen.has(tag) ? C.good : C.mute,
2946
+ children: seen.has(tag) ? "✓ " : " "
2947
+ }),
2948
+ /* @__PURE__ */ jsx2(Text2, {
2949
+ color: on ? C.accent : C.text,
2950
+ bold: on,
2951
+ children: e.name || `Episode ${e.number}`
2952
+ }),
2953
+ e.number === next ? /* @__PURE__ */ jsx2(Text2, {
2954
+ color: C.good,
2955
+ children: " ▸ next"
2956
+ }) : null
2957
+ ]
2958
+ })
2959
+ }),
2960
+ /* @__PURE__ */ jsx2(Text2, {
2961
+ color: C.rule,
2962
+ children: when ? " " + when : ""
2963
+ })
2964
+ ]
2965
+ }, tag);
2966
+ })
2967
+ }),
2968
+ /* @__PURE__ */ jsx2(Scrollbar, {
2969
+ total: screen.list.length,
2970
+ from,
2971
+ visible: to - from,
2972
+ height: to - from
2973
+ })
2974
+ ]
2975
+ }),
2976
+ ep ? /* @__PURE__ */ jsxs2(Box2, {
2977
+ marginTop: 1,
2978
+ flexDirection: "column",
2979
+ flexShrink: 0,
2980
+ children: [
2981
+ /* @__PURE__ */ jsx2(Text2, {
2982
+ color: C.text,
2983
+ bold: true,
2984
+ wrap: "truncate",
2985
+ children: ep.name || `Episode ${ep.number}`
2986
+ }),
2987
+ clip(ep.plot, 64, 3).map((line, i) => /* @__PURE__ */ jsx2(Text2, {
2988
+ color: C.mute,
2989
+ italic: true,
2990
+ children: line
2991
+ }, i))
2992
+ ]
2993
+ }) : null
2994
+ ]
2995
+ });
2996
+ }
2997
+ function SiteLine({ sites, hidden }) {
2998
+ return /* @__PURE__ */ jsxs2(Text2, {
2999
+ wrap: "truncate",
3000
+ children: [
3001
+ sites.map((site, i) => /* @__PURE__ */ jsxs2(Text2, {
3002
+ children: [
3003
+ i ? /* @__PURE__ */ jsx2(Text2, {
3004
+ color: C.mute,
3005
+ children: " · "
3006
+ }) : null,
3007
+ /* @__PURE__ */ jsxs2(Text2, {
3008
+ color: C.text,
3009
+ children: [
3010
+ site.name,
3011
+ " "
3012
+ ]
3013
+ }),
3014
+ site.state === "asking" ? /* @__PURE__ */ jsx2(Spinner, {}) : null,
3015
+ site.state === "done" ? /* @__PURE__ */ jsxs2(Text2, {
3016
+ color: C.good,
3017
+ children: [
3018
+ "✓ ",
3019
+ site.found
3020
+ ]
3021
+ }) : null,
3022
+ site.state === "offline" ? /* @__PURE__ */ jsx2(Text2, {
3023
+ color: C.bad,
3024
+ children: "✗ offline"
3025
+ }) : null
3026
+ ]
3027
+ }, site.name)),
3028
+ hidden ? /* @__PURE__ */ jsx2(Text2, {
3029
+ color: C.mute,
3030
+ children: ` · ${hidden} hidden: not MP4`
3031
+ }) : null
3032
+ ]
3033
+ });
3034
+ }
3035
+ function SourceList({
3036
+ screen,
3037
+ entries,
3038
+ selected,
3039
+ height,
3040
+ couch,
3041
+ picked
3042
+ }) {
3043
+ const report = screen.report;
3044
+ const asking = !report || report.sites.some((s) => s.state === "asking");
3045
+ const [from, to] = windowOf(entries.length, selected, Math.max(3, height - 10));
3046
+ const t = picked && "torrent" in picked ? picked.torrent : null;
3047
+ const audio = t ? audioLabel(t.name) : "";
3048
+ return /* @__PURE__ */ jsxs2(Box2, {
3049
+ flexDirection: "column",
3050
+ children: [
3051
+ /* @__PURE__ */ jsx2(Text2, {
3052
+ color: tintOf(screen.wanted.title.poster),
3053
+ bold: true,
3054
+ wrap: "truncate",
3055
+ children: screen.label.toUpperCase()
3056
+ }),
3057
+ report ? /* @__PURE__ */ jsx2(SiteLine, {
3058
+ sites: report.sites,
3059
+ hidden: screen.hidden
3060
+ }) : /* @__PURE__ */ jsxs2(Text2, {
3061
+ color: C.mute,
3062
+ children: [
3063
+ /* @__PURE__ */ jsx2(Spinner, {}),
3064
+ " asking the sites"
3065
+ ]
3066
+ }),
3067
+ /* @__PURE__ */ jsx2(Box2, {
3068
+ marginTop: 1,
3069
+ children: /* @__PURE__ */ jsx2(Columns, {
3070
+ children: " Seeds Size Quality Src"
3071
+ })
3072
+ }),
3073
+ !entries.length && !asking ? /* @__PURE__ */ jsxs2(Text2, {
3074
+ color: C.warn,
3075
+ children: [
3076
+ couch ? "No release every browser can play (MP4, H.264) for this one; plain flick still plays it. " : "",
3077
+ "No sources found."
3078
+ ]
3079
+ }) : null,
3080
+ /* @__PURE__ */ jsxs2(Box2, {
3081
+ children: [
3082
+ /* @__PURE__ */ jsx2(Box2, {
3083
+ flexDirection: "column",
3084
+ width: 54,
3085
+ flexShrink: 1,
3086
+ children: entries.slice(from, to).map((entry, i) => {
3087
+ if ("heading" in entry)
3088
+ return /* @__PURE__ */ jsx2(SectionHeading, {
3089
+ text: entry.heading
3090
+ }, entry.heading);
3091
+ const on = from + i === selected;
3092
+ const s = entry.torrent;
3093
+ const tag = sourceTag(s.source);
3094
+ const sq = parseQuality(s.name);
3095
+ return /* @__PURE__ */ jsxs2(Box2, {
3096
+ flexShrink: 0,
3097
+ children: [
3098
+ /* @__PURE__ */ jsx2(Pointer, {
3099
+ on
3100
+ }),
3101
+ /* @__PURE__ */ jsxs2(Text2, {
3102
+ wrap: "truncate",
3103
+ children: [
3104
+ /* @__PURE__ */ jsx2(Text2, {
3105
+ color: s.seeders > 20 ? C.good : s.seeders > 0 ? C.warn : C.bad,
3106
+ children: String(s.seeders).padStart(5)
3107
+ }),
3108
+ /* @__PURE__ */ jsxs2(Text2, {
3109
+ color: C.mute,
3110
+ children: [
3111
+ humanSize(s.bytes).padStart(10),
3112
+ " "
3113
+ ]
3114
+ }),
3115
+ /* @__PURE__ */ jsx2(Badge, {
3116
+ text: resolutionLabel(sq.res).padEnd(5),
3117
+ color: RES_COLOR[sq.res] ?? C.rule
3118
+ }),
3119
+ sq.hdr ? /* @__PURE__ */ jsx2(Badge, {
3120
+ text: sq.hdr.padEnd(3),
3121
+ color: C.bad
3122
+ }) : " ",
3123
+ /* @__PURE__ */ jsx2(Text2, {
3124
+ color: on ? C.accent : C.text,
3125
+ bold: on,
3126
+ children: ` ${[sq.codec, sq.src].filter(Boolean).join(" ")}`.padEnd(14)
3127
+ }),
3128
+ /* @__PURE__ */ jsx2(Text2, {
3129
+ color: SOURCE_COLOR[tag] ?? C.mute,
3130
+ children: tag
3131
+ })
3132
+ ]
3133
+ })
3134
+ ]
3135
+ }, s.infoHash + (entry.pick ? "pick" : ""));
3136
+ })
3137
+ }),
3138
+ /* @__PURE__ */ jsx2(Scrollbar, {
3139
+ total: entries.length,
3140
+ from,
3141
+ visible: to - from,
3142
+ height: to - from
3143
+ })
3144
+ ]
3145
+ }),
3146
+ t ? /* @__PURE__ */ jsxs2(Box2, {
3147
+ marginTop: 1,
3148
+ flexDirection: "column",
3149
+ flexShrink: 0,
3150
+ children: [
3151
+ /* @__PURE__ */ jsx2(Text2, {
3152
+ color: C.text,
3153
+ wrap: "truncate",
3154
+ children: t.name
3155
+ }),
3156
+ /* @__PURE__ */ jsxs2(Text2, {
3157
+ wrap: "truncate",
3158
+ children: [
3159
+ /* @__PURE__ */ jsx2(Text2, {
3160
+ color: C.mute,
3161
+ children: audio ? `audio ${audio}` : "audio not in the name"
3162
+ }),
3163
+ couch ? null : whyNotCouch(t.name) === null ? /* @__PURE__ */ jsx2(Text2, {
3164
+ color: C.good,
3165
+ children: " · ✓ couch"
3166
+ }) : /* @__PURE__ */ jsx2(Text2, {
3167
+ color: C.rule,
3168
+ children: ` · ✗ couch: ${whyNotCouch(t.name)}`
3169
+ })
3170
+ ]
3171
+ }),
3172
+ picked && "pick" in picked && picked.pick ? /* @__PURE__ */ jsxs2(Text2, {
3173
+ wrap: "truncate",
3174
+ children: [
3175
+ /* @__PURE__ */ jsx2(Badge, {
3176
+ text: "PICK",
3177
+ color: C.accent
3178
+ }),
3179
+ /* @__PURE__ */ jsx2(Text2, {
3180
+ color: C.mute,
3181
+ children: " 1080p x264 under 6 GB, the most seeders"
3182
+ })
3183
+ ]
3184
+ }) : null
3185
+ ]
3186
+ }) : null
3187
+ ]
3188
+ });
3189
+ }
3190
+ function Playing({ screen, couch, upload, barWidth }) {
3191
+ const d = useDetails(screen.title?.id ?? null);
3192
+ const p = screen.progress;
3193
+ const t = screen.torrent;
3194
+ const q = parseQuality(t.name);
3195
+ const tag = sourceTag(t.source);
3196
+ const audio = audioLabel(t.name);
3197
+ return /* @__PURE__ */ jsxs2(Box2, {
3198
+ flexDirection: "column",
3199
+ flexShrink: 0,
3200
+ children: [
3201
+ /* @__PURE__ */ jsx2(Text2, {
3202
+ color: tintOf(screen.title?.poster ?? ""),
3203
+ bold: true,
3204
+ children: screen.label.toUpperCase()
3205
+ }),
3206
+ screen.error ? /* @__PURE__ */ jsxs2(Text2, {
3207
+ color: C.bad,
3208
+ children: [
3209
+ "✗ ",
3210
+ screen.error
3211
+ ]
3212
+ }) : /* @__PURE__ */ jsxs2(Text2, {
3213
+ color: C.text,
3214
+ children: [
3215
+ p ? /* @__PURE__ */ jsx2(Text2, {
3216
+ color: C.good,
3217
+ children: "●"
3218
+ }) : /* @__PURE__ */ jsx2(Spinner, {}),
3219
+ " ",
3220
+ screen.status
3221
+ ]
3222
+ }),
3223
+ p ? /* @__PURE__ */ jsxs2(Box2, {
3224
+ flexDirection: "column",
3225
+ marginTop: 1,
3226
+ children: [
3227
+ /* @__PURE__ */ jsx2(FilmStrip, {
3228
+ percent: p.percent,
3229
+ width: Math.max(12, barWidth),
3230
+ rolling: p.percent < 100 && p.downBytesPerSec > 0
3231
+ }),
3232
+ /* @__PURE__ */ jsx2(Text2, {
3233
+ color: C.mute,
3234
+ wrap: "truncate",
3235
+ children: downloadLine(p, t.bytes)
3236
+ })
3237
+ ]
3238
+ }) : null,
3239
+ /* @__PURE__ */ jsxs2(Box2, {
3240
+ marginTop: 1,
3241
+ flexDirection: "column",
3242
+ children: [
3243
+ /* @__PURE__ */ jsx2(Text2, {
3244
+ color: C.mute,
3245
+ wrap: "truncate",
3246
+ children: t.name
3247
+ }),
3248
+ q.res || q.codec || q.src || audio ? /* @__PURE__ */ jsxs2(Text2, {
3249
+ wrap: "truncate",
3250
+ children: [
3251
+ q.res ? /* @__PURE__ */ jsx2(Badge, {
3252
+ text: resolutionLabel(q.res),
3253
+ color: RES_COLOR[q.res] ?? C.rule
3254
+ }) : null,
3255
+ /* @__PURE__ */ jsx2(Text2, {
3256
+ color: C.mute,
3257
+ children: ` ${[q.codec, q.src].filter(Boolean).join(" ")}${audio ? ` · audio ${audio}` : ""}`
3258
+ }),
3259
+ t.source !== "pasted" ? /* @__PURE__ */ jsx2(Text2, {
3260
+ color: SOURCE_COLOR[tag] ?? C.mute,
3261
+ children: ` · ${tag}`
3262
+ }) : null
3263
+ ]
3264
+ }) : null
3265
+ ]
3266
+ }),
3267
+ couch && !screen.error ? /* @__PURE__ */ jsx2(RoomCard, {
3268
+ couch,
3269
+ torrent: t,
3270
+ minutes: d?.minutes ?? 0,
3271
+ upload
3272
+ }) : d ? /* @__PURE__ */ jsxs2(Box2, {
3273
+ marginTop: 1,
3274
+ flexDirection: "column",
3275
+ children: [
3276
+ /* @__PURE__ */ jsx2(Text2, {
3277
+ color: C.mute,
3278
+ wrap: "truncate",
3279
+ children: [screen.title?.year, d.minutes ? `${d.minutes} min` : null, d.genres.join(", ")].filter(Boolean).join(" · ")
3280
+ }),
3281
+ d.directors.length ? /* @__PURE__ */ jsxs2(Text2, {
3282
+ wrap: "truncate",
3283
+ children: [
3284
+ /* @__PURE__ */ jsx2(Text2, {
3285
+ color: C.rule,
3286
+ children: spaced("director") + " "
3287
+ }),
3288
+ /* @__PURE__ */ jsx2(Text2, {
3289
+ color: C.text,
3290
+ children: d.directors.join(", ")
3291
+ })
3292
+ ]
3293
+ }) : null,
3294
+ d.cast.length ? /* @__PURE__ */ jsxs2(Text2, {
3295
+ wrap: "truncate",
3296
+ children: [
3297
+ /* @__PURE__ */ jsx2(Text2, {
3298
+ color: C.rule,
3299
+ children: spaced("cast") + " "
3300
+ }),
3301
+ /* @__PURE__ */ jsx2(Text2, {
3302
+ color: C.text,
3303
+ children: d.cast.join(", ")
3304
+ })
3305
+ ]
3306
+ }) : null,
3307
+ /* @__PURE__ */ jsx2(Box2, {
3308
+ marginTop: 1,
3309
+ flexDirection: "column",
3310
+ children: clip(d.plot, Math.max(30, barWidth + 10), 3).map((line, i) => /* @__PURE__ */ jsx2(Text2, {
3311
+ color: C.text,
3312
+ italic: true,
3313
+ children: line
3314
+ }, i))
3315
+ })
3316
+ ]
3317
+ }) : null
3318
+ ]
3319
+ });
3320
+ }
3321
+ function downloadLine(p, totalBytes) {
3322
+ const peers = `${p.peers} ${p.peers === 1 ? "peer" : "peers"}`;
3323
+ if (p.percent >= 100)
3324
+ return `on disk · ${peers}`;
3325
+ const parts = [`${p.percent}%`];
3326
+ if (totalBytes)
3327
+ parts.push(`${humanSize(totalBytes * p.percent / 100)} of ${humanSize(totalBytes)}`);
3328
+ parts.push(`${humanSize(p.downBytesPerSec)}/s`, peers);
3329
+ if (totalBytes && p.downBytesPerSec > 0) {
3330
+ const minutes = Math.max(1, Math.round(totalBytes * (1 - p.percent / 100) / p.downBytesPerSec / 60));
3331
+ parts.push(`about ${minutes} min to the end`);
3332
+ }
3333
+ return parts.join(" · ");
3334
+ }
3335
+ function RoomCard({ couch, torrent, minutes, upload }) {
3336
+ const seated = couch.room.seated();
3337
+ const s = couch.room.state;
3338
+ const at = clock(currentTime(s));
3339
+ const length = minutes ? ` of ${clock(minutes * 60)}` : "";
3340
+ const last = couch.room.lastChange;
3341
+ const bitrate = torrent.bytes && minutes ? torrent.bytes / (minutes * 60) : 0;
3342
+ const need = bitrate * seated.length;
3343
+ let health = /* @__PURE__ */ jsx2(Text2, {
3344
+ color: C.mute,
3345
+ children: "upload idle"
3346
+ });
3347
+ if (s.playing && seated.length && upload !== null) {
3348
+ const ok = !need || upload >= need * 0.9;
3349
+ health = /* @__PURE__ */ jsxs2(Text2, {
3350
+ color: ok ? C.good : C.warn,
3351
+ children: [
3352
+ "↑ ",
3353
+ humanSize(upload),
3354
+ "/s",
3355
+ need ? ` · the film needs ${humanSize(need)}/s` : "",
3356
+ " · ",
3357
+ ok ? "keeping up" : "may buffer"
3358
+ ]
3359
+ });
3360
+ }
3361
+ return /* @__PURE__ */ jsxs2(Box2, {
3362
+ flexDirection: "column",
3363
+ marginTop: 1,
3364
+ children: [
3365
+ /* @__PURE__ */ jsx2(Text2, {
3366
+ color: C.bulb,
3367
+ bold: true,
3368
+ children: spaced("the room")
3369
+ }),
3370
+ /* @__PURE__ */ jsx2(Text2, {
3371
+ wrap: "truncate",
3372
+ children: seated.length ? seated.map((seat, i) => /* @__PURE__ */ jsxs2(Text2, {
3373
+ children: [
3374
+ i ? " " : "",
3375
+ /* @__PURE__ */ jsx2(Text2, {
3376
+ color: C.text,
3377
+ children: seat.name
3378
+ }),
3379
+ /* @__PURE__ */ jsx2(Text2, {
3380
+ color: C.rule,
3381
+ children: ` ${sinceLabel(Date.now() - seat.since)}`
3382
+ })
3383
+ ]
3384
+ }, seat.id + i)) : /* @__PURE__ */ jsx2(Text2, {
3385
+ color: C.mute,
3386
+ children: "nobody yet: send the link below"
3387
+ })
3388
+ }),
3389
+ /* @__PURE__ */ jsxs2(Text2, {
3390
+ children: [
3391
+ !s.src ? /* @__PURE__ */ jsx2(Text2, {
3392
+ color: C.mute,
3393
+ children: "waiting for the film…"
3394
+ }) : s.playing ? /* @__PURE__ */ jsxs2(Text2, {
3395
+ color: C.accent,
3396
+ children: [
3397
+ "▶ ",
3398
+ at
3399
+ ]
3400
+ }) : /* @__PURE__ */ jsxs2(Text2, {
3401
+ color: C.text,
3402
+ children: [
3403
+ "❚❚ ",
3404
+ at,
3405
+ /* @__PURE__ */ jsx2(Text2, {
3406
+ color: C.mute,
3407
+ children: last?.action === "pause" ? ` paused by ${last.by}` : ""
3408
+ })
3409
+ ]
3410
+ }),
3411
+ /* @__PURE__ */ jsx2(Text2, {
3412
+ color: C.mute,
3413
+ children: s.src ? length : ""
3414
+ })
3415
+ ]
3416
+ }),
3417
+ health,
3418
+ couch.link ? /* @__PURE__ */ jsx2(Box2, {
3419
+ marginTop: 1,
3420
+ children: /* @__PURE__ */ jsx2(Text2, {
3421
+ color: C.accent,
3422
+ children: couch.link
3423
+ })
3424
+ }) : null
3425
+ ]
3426
+ });
3427
+ }
3428
+ function sinceLabel(ms) {
3429
+ const minutes = Math.floor(ms / 60000);
3430
+ if (minutes < 1)
3431
+ return "just joined";
3432
+ if (minutes < 60)
3433
+ return `here ${minutes} min`;
3434
+ return `here ${Math.floor(minutes / 60)} h ${minutes % 60} min`;
3435
+ }
3436
+ function Help() {
3437
+ const lines = [
3438
+ ["type", "search films and shows (IMDb)"],
3439
+ ["⏎", "open a title, an episode, or play a source"],
3440
+ ["↑ ↓", "move"],
3441
+ ["tab", "the programme: continue, now showing, shows"],
3442
+ ["← →", "change season"],
3443
+ ["c", "couch: copy the room link while a film is on"],
3444
+ ["esc", "back, clear the search, or home"],
3445
+ ["paste", "a magnet link or info hash plays it straight away"],
3446
+ ["ctrl+c", "quit; no torrent keeps uploading after flick closes"]
3447
+ ];
3448
+ return /* @__PURE__ */ jsxs2(Box2, {
3449
+ flexDirection: "column",
3450
+ children: [
3451
+ lines.map(([k, v]) => /* @__PURE__ */ jsxs2(Box2, {
3452
+ children: [
3453
+ /* @__PURE__ */ jsx2(Text2, {
3454
+ color: C.accent,
3455
+ children: k.padEnd(8)
3456
+ }),
3457
+ /* @__PURE__ */ jsx2(Text2, {
3458
+ color: C.text,
3459
+ children: v
3460
+ })
3461
+ ]
3462
+ }, k)),
3463
+ /* @__PURE__ */ jsx2(Box2, {
3464
+ marginTop: 1,
3465
+ children: /* @__PURE__ */ jsx2(Text2, {
3466
+ color: C.mute,
3467
+ children: "any key closes this"
3468
+ })
3469
+ })
3470
+ ]
3471
+ });
3472
+ }
3473
+
3474
+ // src/cli.tsx
3475
+ import { jsx as jsx3 } from "react/jsx-runtime";
3476
+ var VERSION = "0.1.0";
3477
+ var HELP = `flick ${VERSION}: search a film, pick a torrent, watch it now
3478
+
3479
+ usage:
3480
+ flick open flick: continue watching, trending, search
3481
+ flick <title> open flick already searching for <title>
3482
+ flick couch [title] watch together: films play in a room in both your
3483
+ browsers, in sync; flick prints the room's link
3484
+
3485
+ options:
3486
+ --engine rqbit|webtorrent torrent engine (default: rqbit if installed, else webtorrent)
3487
+ --player iina|mpv|vlc|browser
3488
+ player (default: the first one installed, in that order)
3489
+ --dub anime: prefer dual-audio releases
3490
+ -h, --help this help
3491
+ -v, --version the version
3492
+
3493
+ Settings live in ~/.config/flick/config.json (engine, player, cacheGB, dub).
3494
+ couch rooms run on this computer through a free Cloudflare quick tunnel (a new
3495
+ address each time). For one fixed address, create a named Cloudflare tunnel
3496
+ routed to http://127.0.0.1:8765 and set tunnelToken and tunnelHost there.
3497
+ Films are cached in ~/.cache/flick, capped at 10 GB by default; the least
3498
+ recently watched go first. Nothing keeps uploading once a film is closed.`;
3499
+ function parseArgs(argv) {
3500
+ const args = { query: "", dub: false, couch: false };
3501
+ const words = [];
3502
+ for (let i = 0;i < argv.length; i++) {
3503
+ const arg = argv[i];
3504
+ if (arg === "-h" || arg === "--help")
3505
+ return "help";
3506
+ if (arg === "-v" || arg === "--version")
3507
+ return "version";
3508
+ if (arg === "--dub")
3509
+ args.dub = true;
3510
+ else if (arg === "--engine" || arg === "--player") {
3511
+ const value = argv[++i];
3512
+ if (!value)
3513
+ return { error: `${arg} needs a value` };
3514
+ if (arg === "--engine")
3515
+ args.engine = value;
3516
+ else
3517
+ args.player = value;
3518
+ } else if (arg.startsWith("-"))
3519
+ return { error: `unknown option ${arg} (see flick --help)` };
3520
+ else
3521
+ words.push(arg);
3522
+ }
3523
+ if (words[0] === "couch") {
3524
+ args.couch = true;
3525
+ words.shift();
3526
+ }
3527
+ args.query = words.join(" ");
3528
+ return args;
3529
+ }
3530
+ function main() {
3531
+ const parsed = parseArgs(process.argv.slice(2));
3532
+ if (parsed === "help")
3533
+ return console.log(HELP);
3534
+ if (parsed === "version")
3535
+ return console.log(VERSION);
3536
+ if ("error" in parsed) {
3537
+ console.error(parsed.error);
3538
+ process.exitCode = 1;
3539
+ return;
3540
+ }
3541
+ const config = loadConfig();
3542
+ const engineChoice = parsed.engine ?? config.engine;
3543
+ if (engineChoice && engineChoice !== "rqbit" && engineChoice !== "webtorrent") {
3544
+ console.error(`unknown engine "${engineChoice}": use rqbit or webtorrent`);
3545
+ process.exitCode = 1;
3546
+ return;
3547
+ }
3548
+ if (engineChoice === "rqbit" && !which("rqbit")) {
3549
+ console.error("rqbit isn't installed (brew install rqbit), or use --engine webtorrent");
3550
+ process.exitCode = 1;
3551
+ return;
3552
+ }
3553
+ const playerChoice = parsed.player ?? config.player;
3554
+ if (playerChoice && !installedPlayers().includes(playerChoice)) {
3555
+ console.error(`player "${playerChoice}" isn't installed here. Installed: ${installedPlayers().join(", ")}`);
3556
+ process.exitCode = 1;
3557
+ return;
3558
+ }
3559
+ if (!process.stdin.isTTY) {
3560
+ console.error("flick needs an interactive terminal");
3561
+ process.exitCode = 1;
3562
+ return;
3563
+ }
3564
+ const engine = pickEngine(engineChoice);
3565
+ const couch = parsed.couch ? Couch.start() : undefined;
3566
+ for (const signal of ["SIGHUP", "SIGTERM"]) {
3567
+ process.on(signal, async () => {
3568
+ await couch?.close().catch(() => {});
3569
+ await engine.shutdown().catch(() => {});
3570
+ process.exit(0);
3571
+ });
3572
+ }
3573
+ render(/* @__PURE__ */ jsx3(App, {
3574
+ engine,
3575
+ player: pickPlayer(playerChoice),
3576
+ cacheGB: config.cacheGB ?? 10,
3577
+ dub: parsed.dub || Boolean(config.dub),
3578
+ initialQuery: parsed.query,
3579
+ couch
3580
+ }), { alternateScreen: true, exitOnCtrlC: false });
3581
+ }
3582
+ function startedDirectly() {
3583
+ const self = fileURLToPath2(import.meta.url);
3584
+ const started = process.argv[1] ?? "";
3585
+ if (started === self)
3586
+ return true;
3587
+ try {
3588
+ return realpathSync(started) === realpathSync(self);
3589
+ } catch {
3590
+ return false;
3591
+ }
3592
+ }
3593
+ if (startedDirectly())
3594
+ main();
3595
+ export {
3596
+ parseArgs
3597
+ };