@nitrimandylis/flick 0.0.0-stage → 0.1.1

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/room/room.js ADDED
@@ -0,0 +1,551 @@
1
+ // couch room: both browsers play the same MP4 in a plain <video>, streamed from
2
+ // the host's computer by `flick couch`, which also serves this page and the relay
3
+ // that keeps play, pause and seek in step.
4
+ //
5
+ // One rule decides what counts as a person acting: a media event is only sent
6
+ // to the room when it disagrees with the room. A "play" while the room plays,
7
+ // or a seek that lands where the room is, is just us following.
8
+
9
+ const DRIFT_LIMIT = 3; // seconds apart before the pill turns magenta
10
+ const CURTAIN_CAP = 10000; // ms before the loading curtain gives up and lifts
11
+ const SEEK_LEAD = 1.5; // seconds: a jump while playing re-buffers through the tunnel, so land ahead
12
+ const FOLLOW_SLACK = 2; // seconds a playing film may differ from the room before we seek
13
+
14
+ const roomId = location.pathname.split("/")[2];
15
+ const $ = (id) => document.getElementById(id);
16
+ const video = $("player");
17
+
18
+ // Who this browser is. The id survives renames; the name is what toasts show.
19
+ if (!localStorage.couchId) localStorage.couchId = crypto.randomUUID();
20
+ const me = { id: localStorage.couchId, name: localStorage.couchName || "" };
21
+
22
+ let ws = null;
23
+ let seated = false;
24
+ let room = null; // last state from the server
25
+ let raters = []; // browser ids that have rated, from the server
26
+ let clockOffset = 0; // server clock minus our clock, in ms
27
+ let seenRev = 0; // the room's revision in its last state message: sent with each press
28
+ let peers = [];
29
+
30
+ let playing = null; // the source we attached: { key, url, subs }
31
+ let peerPos = null; // { name, time, playing, at } from the other browser
32
+ let sendTimer = null;
33
+ let lastLocalAction = 0; // ms: when the person at this screen last played, paused or seeked
34
+ let ownSeek = null; // where follow() last sent our player; that seek finishing isn't a person seeking
35
+ // "play"/"pause" events flick caused itself, so they aren't reported as the person's.
36
+ const ownToggle = new Set();
37
+ let capTimer = null;
38
+
39
+ // ---------- small helpers ----------
40
+
41
+ function clock(seconds) {
42
+ seconds = Math.max(0, Math.floor(seconds || 0));
43
+ const h = Math.floor(seconds / 3600);
44
+ const m = Math.floor((seconds % 3600) / 60);
45
+ const s = seconds % 60;
46
+ const mm = h > 0 ? String(m).padStart(2, "0") : String(m);
47
+ return (h > 0 ? h + ":" : "") + mm + ":" + String(s).padStart(2, "0");
48
+ }
49
+
50
+ function send(msg) {
51
+ if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
52
+ }
53
+
54
+ function show(sectionId) {
55
+ for (const id of ["gate", "empty", "stage", "after"]) $(id).hidden = id !== sectionId;
56
+ }
57
+
58
+ // Where the room says the film is right now.
59
+ function roomTime() {
60
+ if (!room || !room.film) return 0;
61
+ if (!room.playing) return room.time;
62
+ return room.time + (Date.now() + clockOffset - room.at) / 1000;
63
+ }
64
+
65
+ function otherPeer() {
66
+ return peers.find((p) => p.id !== me.id) || null;
67
+ }
68
+
69
+ // ---------- connection ----------
70
+
71
+ function connect() {
72
+ const scheme = location.protocol === "https:" ? "wss://" : "ws://";
73
+ ws = new WebSocket(scheme + location.host + "/r/" + roomId + "/ws");
74
+ ws.addEventListener("open", () => {
75
+ if (seated) send({ type: "hello", id: me.id, name: me.name });
76
+ });
77
+ ws.addEventListener("message", (event) => onServer(JSON.parse(event.data)));
78
+ ws.addEventListener("close", () => {
79
+ setTimeout(connect, 1500); // laptop slept or wifi blinked: come back quietly
80
+ });
81
+ }
82
+
83
+ function onServer(msg) {
84
+ if (msg.type === "state") {
85
+ clockOffset = msg.now - Date.now();
86
+ seenRev = msg.rev;
87
+ applyState(msg);
88
+ } else if (msg.type === "peers") {
89
+ peers = msg.peers;
90
+ const other = otherPeer();
91
+ if (other) localStorage.couchPeer = other.name;
92
+ if (!seated) renderGate();
93
+ updatePill();
94
+ } else if (msg.type === "pos") {
95
+ peerPos = { name: msg.name, time: msg.time, playing: msg.playing, at: Date.now() };
96
+ updatePill();
97
+ } else if (msg.type === "pull") {
98
+ // The other person is ahead and asked us to jump to them.
99
+ video.currentTime = msg.time;
100
+ toast(msg.name + " pulled you to " + clock(msg.time));
101
+ }
102
+ }
103
+
104
+ async function applyState(msg) {
105
+ room = msg.state;
106
+ raters = msg.raters || [];
107
+
108
+ if (!seated) {
109
+ renderGate();
110
+ return;
111
+ }
112
+
113
+ if (!room.film) {
114
+ detach();
115
+ renderEmpty();
116
+ show("empty");
117
+ return;
118
+ }
119
+
120
+ if (room.ended) {
121
+ detach();
122
+ renderAfter();
123
+ show("after");
124
+ return;
125
+ }
126
+
127
+ show("stage");
128
+ $("pill-film").textContent = room.film.title;
129
+
130
+ if (!room.src) {
131
+ // The host is between films (the torrent stopped). Hold where we are.
132
+ pausePlayer();
133
+ curtain("The host stopped the film. It comes back when they start it again in flick.");
134
+ return;
135
+ }
136
+
137
+ const fromMe = msg.byId === me.id;
138
+ if (!playing || playing.key !== room.src.url) {
139
+ await attach();
140
+ }
141
+ // Always line up with the room, even after our own action: if the other
142
+ // person acted at the same moment, the room may already disagree with what
143
+ // we did. When we already match, follow() changes nothing.
144
+ follow();
145
+
146
+ if (!fromMe && msg.by) {
147
+ if (msg.action === "play") toast(msg.by + " pressed play at " + clock(room.time));
148
+ if (msg.action === "pause") toast(msg.by + " paused at " + clock(room.time));
149
+ if (msg.action === "seek") toast(msg.by + " jumped to " + clock(room.time));
150
+ }
151
+ if (msg.action === "load") toast(room.film.title + " is on");
152
+ wake();
153
+ }
154
+
155
+ // ---------- the player ----------
156
+
157
+ // Everyone, the host included, streams through the tunnel: a public page
158
+ // reaching this Mac's own 127.0.0.1 makes Chrome ask for local network access.
159
+ async function attach() {
160
+ const { url, subs } = room.src;
161
+ playing = { key: url, url, subs };
162
+ pausePlayer(); // swapping the source stops the old one: not the person pausing
163
+
164
+ curtain("Loading " + room.film.title + "…");
165
+ video.src = url;
166
+ const track = $("subs");
167
+ track.src = subs || "";
168
+ $("cc").hidden = !subs;
169
+ setCaptions(localStorage.couchCaptions === "on");
170
+ video.load();
171
+ // Wait for the file's index before seeking into it, but never forever.
172
+ await Promise.race([
173
+ new Promise((resolve) => video.addEventListener("loadedmetadata", resolve, { once: true })),
174
+ new Promise((resolve) => setTimeout(resolve, CURTAIN_CAP)),
175
+ ]);
176
+ }
177
+
178
+ function detach() {
179
+ if (!playing) return;
180
+ playing = null;
181
+ pausePlayer();
182
+ video.removeAttribute("src");
183
+ video.load();
184
+ }
185
+
186
+ // Put our player where the room is. Small differences are left alone: a
187
+ // playing film is allowed to be off by up to FOLLOW_SLACK (wider than
188
+ // SEEK_LEAD, so a follower that landed ahead doesn't seek itself again).
189
+ function follow() {
190
+ if (!playing) return;
191
+ const target = roomTime();
192
+ const slack = room.playing ? FOLLOW_SLACK : 0.2; // paused, a seek is free: show the same frame
193
+ if (Math.abs(video.currentTime - target) > slack) seekTo(target + (room.playing ? SEEK_LEAD : 0));
194
+ if (room.playing && video.paused) {
195
+ ownToggle.add("play");
196
+ video.play().catch(() => {
197
+ ownToggle.delete("play");
198
+ toast("Press play: the browser didn't let couch start the film.", 5000);
199
+ });
200
+ } else if (!room.playing && !video.paused) {
201
+ pausePlayer();
202
+ }
203
+ }
204
+
205
+ // Report a change made by the person at this screen. Seeking fires a burst of
206
+ // events while the bar is dragged, so only where it settles is sent.
207
+ // `playing` is what the person asked for, kept from the moment they asked: a
208
+ // late message from the room can still flip our player inside the 300 ms.
209
+ let wantPlaying = null;
210
+ let wantRev = 0; // what this screen had seen of the room when the person pressed
211
+ function report(playing) {
212
+ lastLocalAction = Date.now();
213
+ if (playing !== undefined) {
214
+ wantPlaying = playing;
215
+ wantRev = seenRev;
216
+ }
217
+ clearTimeout(sendTimer);
218
+ sendTimer = setTimeout(() => {
219
+ send({ type: "set", playing: wantPlaying ?? !video.paused, time: video.currentTime, rev: wantPlaying === null ? seenRev : wantRev });
220
+ wantPlaying = null;
221
+ }, 300);
222
+ }
223
+
224
+ function pausePlayer() {
225
+ if (video.paused) return;
226
+ ownToggle.add("pause");
227
+ video.pause();
228
+ }
229
+
230
+ // Every play or pause the person makes is reported, even when our copy of the
231
+ // room already agrees: that copy can be a second or more out of date on a slow
232
+ // tunnel, and the room itself drops reports that change nothing.
233
+ video.addEventListener("play", () => {
234
+ if (ownToggle.delete("play")) return;
235
+ // The room is already playing and our player was paused (say autoplay was
236
+ // blocked and they pressed play by hand): start from where the room is.
237
+ if (room && room.playing && Math.abs(video.currentTime - roomTime()) > FOLLOW_SLACK) seekTo(roomTime() + SEEK_LEAD);
238
+ report(true);
239
+ });
240
+ video.addEventListener("pause", () => {
241
+ if (ownToggle.delete("pause") || video.ended) return;
242
+ report(false);
243
+ });
244
+ // Seeks flick makes to follow the room, remembered so their "seeked" event,
245
+ // which can arrive many seconds later on a slow connection, isn't mistaken
246
+ // for the person seeking (that would drag everyone back to a stalled spot).
247
+ function seekTo(time) {
248
+ ownSeek = time;
249
+ video.currentTime = time;
250
+ }
251
+
252
+ video.addEventListener("seeked", () => {
253
+ if (ownSeek !== null && Math.abs(video.currentTime - ownSeek) < 1) {
254
+ ownSeek = null;
255
+ return;
256
+ }
257
+ ownSeek = null;
258
+ if (room && Math.abs(video.currentTime - roomTime()) > FOLLOW_SLACK + 0.5) report(); // wider than any seek of our own
259
+ });
260
+ video.addEventListener("ended", () => send({ type: "ended" }));
261
+ video.addEventListener("canplay", hideCurtain);
262
+ video.addEventListener("timeupdate", updateClock);
263
+
264
+ // Stay locked to the room's clock while playing: nudge the speed by 5% (pitch
265
+ // is preserved, so it's inaudible) to close small gaps, instead of seeking,
266
+ // which would stutter. Big gaps are follow()'s job.
267
+ setInterval(() => {
268
+ if (!playing || !room || !room.playing || video.paused || video.seeking) {
269
+ video.playbackRate = 1;
270
+ return;
271
+ }
272
+ // Right after our own seek the room hasn't heard about it yet, and its clock
273
+ // still shows the old spot. Don't drag the person back to it.
274
+ if (Date.now() - lastLocalAction < 3000) return;
275
+ const behind = roomTime() - video.currentTime;
276
+ if (Math.abs(behind) > FOLLOW_SLACK) follow();
277
+ else if (behind > 0.3) video.playbackRate = 1.05;
278
+ else if (behind < -0.3) video.playbackRate = 0.95;
279
+ else video.playbackRate = 1;
280
+ }, 1000);
281
+
282
+ // Tell the other browser where we are, for the drift badge.
283
+ setInterval(() => {
284
+ if (!seated || !playing || !room || room.ended) return;
285
+ send({ type: "pos", time: video.currentTime, playing: !video.paused });
286
+ }, 3000);
287
+
288
+ // ---------- curtain ----------
289
+
290
+ function curtain(text) {
291
+ $("curtain-text").textContent = text;
292
+ const line = $("curtain-line");
293
+ line.replaceWith(line.cloneNode(true)); // restart the progress line
294
+ $("curtain").classList.remove("gone");
295
+ clearTimeout(capTimer);
296
+ capTimer = setTimeout(hideCurtain, CURTAIN_CAP);
297
+ }
298
+
299
+ function hideCurtain() {
300
+ if (room && room.film && !room.src) return; // offline notice stays up
301
+ clearTimeout(capTimer);
302
+ $("curtain").classList.add("gone");
303
+ }
304
+
305
+ // ---------- subtitles ----------
306
+
307
+ function setCaptions(on) {
308
+ const track = video.textTracks[0];
309
+ if (track) track.mode = on ? "showing" : "hidden";
310
+ $("cc").classList.toggle("on", on);
311
+ $("cc").setAttribute("aria-pressed", String(on));
312
+ }
313
+
314
+ $("cc").addEventListener("click", () => {
315
+ const on = localStorage.couchCaptions !== "on";
316
+ localStorage.couchCaptions = on ? "on" : "off";
317
+ setCaptions(on);
318
+ });
319
+
320
+ // ---------- pill ----------
321
+
322
+ let sleepTimer = null;
323
+
324
+ function wake() {
325
+ const pill = $("pill");
326
+ pill.classList.remove("asleep");
327
+ clearTimeout(sleepTimer);
328
+ sleepTimer = setTimeout(() => {
329
+ if (!$("dot").classList.contains("drift")) pill.classList.add("asleep");
330
+ }, 3000);
331
+ }
332
+
333
+ // Seconds we are ahead of the other person (negative: behind). Null if unknown.
334
+ function driftSeconds() {
335
+ if (!peerPos || !playing || !otherPeer()) return null;
336
+ if (Date.now() - peerPos.at > 10000) return null; // stale report
337
+ const theirs = peerPos.time + (peerPos.playing ? (Date.now() - peerPos.at) / 1000 : 0);
338
+ return video.currentTime - theirs;
339
+ }
340
+
341
+ function updatePill() {
342
+ const dot = $("dot");
343
+ const status = $("status");
344
+ const other = otherPeer();
345
+ const drift = driftSeconds();
346
+ dot.className = "dot";
347
+ $("resync").hidden = true;
348
+
349
+ if (!other) {
350
+ dot.classList.add("waiting");
351
+ status.textContent = "Waiting for " + (localStorage.couchPeer || "the other seat");
352
+ } else if (drift !== null && Math.abs(drift) > DRIFT_LIMIT) {
353
+ dot.classList.add("drift");
354
+ const gap = Math.round(Math.abs(drift)) + " s";
355
+ status.textContent = drift > 0 ? other.name + " is " + gap + " behind" : "You're " + gap + " behind";
356
+ $("resync").hidden = false;
357
+ wake();
358
+ } else {
359
+ status.textContent = "In sync with " + other.name;
360
+ }
361
+ }
362
+
363
+ function updateClock() {
364
+ const el = $("clock");
365
+ el.textContent = clock(video.currentTime) + " ";
366
+ if (video.duration) {
367
+ const of = document.createElement("span");
368
+ of.className = "of";
369
+ of.textContent = "/ " + clock(video.duration);
370
+ el.append(of);
371
+ }
372
+ }
373
+
374
+ $("resync").addEventListener("click", () => {
375
+ const drift = driftSeconds();
376
+ if (drift === null) return;
377
+ if (drift < 0) {
378
+ // We are behind: jump ourselves to them.
379
+ video.currentTime = peerPos.time + (peerPos.playing ? (Date.now() - peerPos.at) / 1000 : 0);
380
+ } else {
381
+ // They are behind: pull them to us.
382
+ send({ type: "pull", time: video.currentTime, playing: !video.paused });
383
+ toast("Pulling " + otherPeer().name + " to " + clock(video.currentTime));
384
+ }
385
+ peerPos = null;
386
+ updatePill();
387
+ });
388
+
389
+ $("stage").addEventListener("mousemove", wake);
390
+
391
+ $("fullscreen").addEventListener("click", () => {
392
+ if (document.fullscreenElement) document.exitFullscreen();
393
+ else document.documentElement.requestFullscreen();
394
+ });
395
+
396
+ // ---------- toasts ----------
397
+
398
+ let toastTimer = null;
399
+
400
+ function toast(text, ms = 2600) {
401
+ const el = $("toast");
402
+ el.textContent = text;
403
+ el.classList.remove("gone");
404
+ clearTimeout(toastTimer);
405
+ toastTimer = setTimeout(() => el.classList.add("gone"), ms);
406
+ }
407
+
408
+ // ---------- gate ----------
409
+
410
+ function renderGate() {
411
+ $("gate-film").textContent = room && room.film && !room.ended ? "Tonight: " + room.film.title : "";
412
+ const other = otherPeer();
413
+ $("gate-peer").textContent = other ? other.name + " is already here." : "";
414
+ }
415
+
416
+ $("name-field").hidden = !!me.name;
417
+ $("name").value = me.name;
418
+
419
+ function sitDown() {
420
+ if (!me.name) {
421
+ const typed = $("name").value.trim();
422
+ if (!typed) {
423
+ $("name").focus();
424
+ return;
425
+ }
426
+ me.name = typed;
427
+ localStorage.couchName = typed;
428
+ }
429
+ seated = true;
430
+ send({ type: "hello", id: me.id, name: me.name });
431
+ }
432
+
433
+ $("sit").addEventListener("click", sitDown);
434
+ $("name").addEventListener("keydown", (event) => {
435
+ if (event.key === "Enter") sitDown();
436
+ });
437
+
438
+ // ---------- empty room ----------
439
+
440
+ function renderEmpty() {
441
+ if (room && room.last) {
442
+ const date = new Date(room.last.finished).toLocaleDateString(undefined, { day: "numeric", month: "short" });
443
+ $("last").textContent = "Last time: " + room.last.title + ", finished " + date + ".";
444
+ } else {
445
+ $("last").textContent = "";
446
+ }
447
+ }
448
+
449
+ // ---------- after the film ----------
450
+
451
+ let detailsFor = null;
452
+
453
+ function renderAfter() {
454
+ const film = room.film;
455
+ if (detailsFor !== film.id) {
456
+ detailsFor = film.id;
457
+ $("after-title").textContent = film.title;
458
+ for (const id of ["facts", "tagline", "plot", "about", "credits"]) $(id).textContent = "";
459
+ $("backdrop").style.backgroundImage = "";
460
+ loadDetails(film.id);
461
+ }
462
+ renderVerdict();
463
+ }
464
+
465
+ async function loadDetails(id) {
466
+ let info;
467
+ try {
468
+ info = await (await fetch("/api/film/" + id)).json();
469
+ } catch {
470
+ return;
471
+ }
472
+ if (detailsFor !== id) return;
473
+ if (info.title) $("after-title").textContent = info.title;
474
+ if (info.poster) $("backdrop").style.backgroundImage = "url(" + info.poster + ")";
475
+
476
+ const facts = $("facts");
477
+ const bits = [];
478
+ if (info.year) bits.push(String(info.year));
479
+ if (info.runtime) bits.push(Math.floor(info.runtime / 3600) + " h " + Math.round((info.runtime % 3600) / 60) + " min");
480
+ if (info.genres.length) bits.push(info.genres.join(", "));
481
+ for (const bit of bits) {
482
+ const span = document.createElement("span");
483
+ span.textContent = bit;
484
+ facts.append(span);
485
+ }
486
+
487
+ $("tagline").textContent = info.tagline || "";
488
+ $("plot").textContent = info.plot || "";
489
+ $("about").textContent = info.about || "";
490
+
491
+ const credits = $("credits");
492
+ const rows = [
493
+ [info.directors.length > 1 ? "Directors" : "Director", info.directors],
494
+ ["Written by", info.writers],
495
+ ["Starring", info.stars],
496
+ ];
497
+ for (const [label, names] of rows) {
498
+ if (!names.length) continue;
499
+ const dt = document.createElement("dt");
500
+ dt.textContent = label;
501
+ const dd = document.createElement("dd");
502
+ dd.textContent = names.join(", ");
503
+ credits.append(dt, dd);
504
+ }
505
+ }
506
+
507
+ function renderVerdict() {
508
+ const stars = $("stars");
509
+ const mine = Number(localStorage["couchRating:" + room.film.id]) || 0;
510
+ const iRated = raters.includes(me.id);
511
+ stars.innerHTML = "";
512
+ for (let n = 1; n <= 5; n++) {
513
+ const button = document.createElement("button");
514
+ button.textContent = String(n);
515
+ button.setAttribute("aria-label", n + " out of 5");
516
+ if (iRated && n === mine) button.classList.add("picked");
517
+ button.addEventListener("click", () => {
518
+ localStorage["couchRating:" + room.film.id] = n;
519
+ send({ type: "rate", stars: n });
520
+ });
521
+ stars.append(button);
522
+ }
523
+
524
+ const revealed = room.ratings.length >= 2 && room.ratings.every((r) => r.stars !== null);
525
+ $("reveal").hidden = !revealed;
526
+ stars.hidden = revealed;
527
+ if (revealed) {
528
+ $("reveal").innerHTML = "";
529
+ for (const r of room.ratings) {
530
+ const box = document.createElement("div");
531
+ const score = document.createElement("strong");
532
+ score.textContent = String(r.stars);
533
+ const who = document.createElement("span");
534
+ who.textContent = r.name;
535
+ box.append(score, who);
536
+ $("reveal").append(box);
537
+ }
538
+ $("verdict-note").textContent = "Out of 5. Now argue.";
539
+ } else if (iRated) {
540
+ const other = otherPeer();
541
+ $("verdict-note").textContent = "You picked " + mine + ". Waiting for " + (other ? other.name : "the other seat") + ".";
542
+ } else {
543
+ $("verdict-note").textContent = "Both scores stay hidden until you have both picked one.";
544
+ }
545
+ }
546
+
547
+ $("done").addEventListener("click", () => send({ type: "done" }));
548
+
549
+ // ---------- start ----------
550
+
551
+ connect();