-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathlookout_capture_controller.js
More file actions
609 lines (543 loc) · 19 KB
/
Copy pathlookout_capture_controller.js
File metadata and controls
609 lines (543 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { Controller } from "@hotwired/stimulus";
// Native Lookout recorder (the popup at /projects/:id/lookout_sessions/:id/record).
// Talks directly to Lookout's token-authenticated client API per
// https://github.com/hackclub/lookout/blob/main/docs/integration.md:
// - Desktop: deep-link to the Lookout app, then poll status.
// - Browser/Camera: grab a frame, GET upload-url, PUT it to R2, POST confirm,
// then schedule the next capture from the server's nextExpectedAt (credit
// mode). Time tracked = the server's trackedSeconds (we only display it).
const CLIENT_INFO = "Lookout Sdk (Stardance)/0.1.0 (web)";
const MAX_HEIGHT = 1080;
const TERMINAL = ["complete", "failed"];
export default class extends Controller {
static targets = [
"chooser",
"desktopStage",
"desktopStatus",
"deepLink",
"deepLinkText",
"captureStage",
"preview",
"status",
"timer",
"pauseBtn",
"resumeBtn",
"stopBtn",
"doneStage",
"doneStatus",
"result",
"rendering",
"destination",
"existingSelect",
"newName",
"finishBtn",
"destError",
"postPrompt",
"doneClose",
"error",
];
static values = {
token: String,
apiBase: String,
deepLink: String,
modeUrl: String,
forwardUrl: String,
stopUrl: String,
syncUrl: String,
};
connect() {
this.stream = null;
this.captureTimer = null;
this.displayTimer = null;
this.statusTimer = null;
this.paused = false;
this.stopped = false;
this.mode = null;
this.baseSeconds = 0;
this.lastSyncMs = Date.now();
}
disconnect() {
this.cleanup();
}
// ── mode selection ────────────────────────────────────────────────────
chooseDesktop() {
this.mode = "desktop";
this.setMode("desktop");
this.showStage("desktop");
this.deepLinkTextTarget.textContent = this.deepLinkValue;
this.deepLinkTarget.href = this.deepLinkValue;
window.location.href = this.deepLinkValue; // attempt to open the app
this.setText(
this.desktopStatusTarget,
"Waiting for the Lookout app to start recording…",
);
// When the desktop app finishes, drop into the same done stage (preview +
// "where should this time go?") the browser/camera flows use.
this.pollStatus(this.desktopStatusTarget, {
showVideo: true,
doneOnComplete: true,
});
}
async chooseBrowser() {
this.mode = "web";
this.setMode("web");
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: { frameRate: 1 },
audio: false,
});
this.startCapture(stream, "Sharing your screen");
} catch (_) {
this.showError("Screen sharing was cancelled or blocked.");
}
}
async chooseCamera() {
this.mode = "camera";
this.setMode("camera");
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false,
});
this.startCapture(stream, "Recording from your webcam");
} catch (_) {
this.showError(
"Couldn't access your webcam. Check your browser permissions.",
);
}
}
// ── capture loop ──────────────────────────────────────────────────────
startCapture(stream, label) {
this.stream = stream;
this.showStage("capture");
this.previewTarget.srcObject = stream;
this.previewTarget.play().catch(() => {});
// If the user ends the share from the browser's own UI, treat it as Stop.
const track = stream.getVideoTracks()[0];
if (track) track.addEventListener("ended", () => this.stop());
this.paused = false;
this.togglePauseButtons();
this.setStatus(label);
this.startDisplayTimer();
this.tick();
}
async tick() {
if (this.paused || this.stopped) return;
const canvas = this.captureFrame();
if (!canvas) {
this.scheduleNext(2000); // video not ready yet
return;
}
const capturedAt = new Date().toISOString();
try {
const blob = await new Promise((r) =>
canvas.toBlob(r, "image/jpeg", 0.7),
);
if (!blob) throw new Error("Could not encode frame");
const meta = await this.getJson(
`/api/sessions/${this.tokenValue}/upload-url` +
`?capturedAt=${encodeURIComponent(capturedAt)}` +
`&clientInfo=${encodeURIComponent(CLIENT_INFO)}`,
);
await this.put(meta.uploadUrl, blob);
const confirm = await this.postJson(
`/api/sessions/${this.tokenValue}/screenshots`,
{
screenshotId: meta.screenshotId,
width: canvas.width,
height: canvas.height,
fileSize: blob.size,
},
);
const tracked = confirm.trackedSeconds ?? confirm.tracked_seconds;
if (typeof tracked === "number") this.onTracked(tracked);
this.setStatus("Recording…");
const nextAt = confirm.nextExpectedAt || meta.nextExpectedAt;
const delay = nextAt
? Math.max(0, new Date(nextAt).getTime() - Date.now())
: 60000;
this.scheduleNext(delay);
} catch (error) {
console.error("Lookout capture error", error);
this.setStatus("Reconnecting…");
this.scheduleNext(8000); // back off, then re-capture
}
}
captureFrame() {
const video = this.previewTarget;
if (!video.videoWidth || !video.videoHeight) return null;
const scale = Math.min(1, MAX_HEIGHT / video.videoHeight);
const canvas = document.createElement("canvas");
canvas.width = Math.round(video.videoWidth * scale);
canvas.height = Math.round(video.videoHeight * scale);
canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
return canvas;
}
scheduleNext(delay) {
this.clearTimer("captureTimer");
if (this.stopped) return;
this.captureTimer = setTimeout(() => this.tick(), delay);
}
// ── pause / resume / stop ─────────────────────────────────────────────
async pause() {
this.paused = true;
this.clearTimer("captureTimer");
this.togglePauseButtons();
this.setStatus("Paused");
await this.postJson(`/api/sessions/${this.tokenValue}/pause`, {}).catch(
() => {},
);
}
async resume() {
this.paused = false;
this.togglePauseButtons();
this.setStatus("Recording…");
await this.postJson(`/api/sessions/${this.tokenValue}/resume`, {}).catch(
() => {},
);
this.lastSyncMs = Date.now();
this.scheduleNext(0);
}
async stop() {
if (this.stopped) return;
this.stopped = true;
this.clearTimer("captureTimer");
this.clearTimer("displayTimer");
this.stopStream();
this.showStage("done");
this.setText(
this.doneStatusTarget,
"Finishing up processing your timelapse. This can take a minute or two. Keep this tab open.",
);
this.chooseDestination(); // enable the right destination field for the default
// Tell Lookout to stop, and tell Stardance too so it stamps stopped_at and
// starts syncing the recording immediately rather than waiting for the
// every-5-min poller to notice.
await this.postJson(`/api/sessions/${this.tokenValue}/stop`, {}).catch(
() => {},
);
this.notifyStardanceStop();
// No auto-forward: the user picks where the time goes (or not) on this stage,
// then clicks Finish. Meanwhile, poll for the compiled video to preview it.
this.pollStatus(this.doneStatusTarget, { showVideo: true });
}
// Persist how this session is being recorded so the forwarded heartbeats get
// tagged Lookout-Desktop / Lookout-Web / Lookout-Camera. Best-effort.
setMode(mode) {
if (!this.modeUrlValue) return;
fetch(this.modeUrlValue, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": this.csrfToken(),
},
body: JSON.stringify({ mode }),
}).catch(() => {});
}
// Tell Stardance the recording stopped so it stamps stopped_at and syncs the
// latest state from Lookout right away, instead of waiting for the every-5-min
// poller. Same-origin, best-effort — the recorder still works against Lookout's
// API even if this fails.
notifyStardanceStop() {
if (!this.stopUrlValue) return;
fetch(this.stopUrlValue, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": this.csrfToken(),
},
}).catch(() => {});
}
// Ask Stardance to pull this session from Lookout (its `show` action runs
// sync_from_remote!), so the finished recording + duration land in Stardance's
// DB within seconds instead of on the next poll cycle. Best-effort.
syncStardance() {
if (!this.syncUrlValue) return;
fetch(this.syncUrlValue, { headers: { Accept: "application/json" } }).catch(
() => {},
);
}
// ── destination ("where should this time go?") ────────────────────────
// Enable only the input that belongs to the currently-selected destination,
// and clear any prior validation error.
chooseDestination() {
const choice = this.selectedDestination();
if (this.hasExistingSelectTarget)
this.existingSelectTarget.disabled = choice !== "existing";
if (this.hasNewNameTarget) this.newNameTarget.disabled = choice !== "new";
if (this.hasDestErrorTarget) this.destErrorTarget.hidden = true;
}
selectedDestination() {
const checked = this.element.querySelector(
'input[name="lookout-dest"]:checked',
);
return checked ? checked.value : "skip";
}
// Confirm the destination: forward the captured time to the chosen Hackatime
// project (existing or new), or send nothing when the user opted out.
async finish() {
const choice = this.selectedDestination();
let projectName = null;
if (choice === "existing")
projectName = this.hasExistingSelectTarget
? this.existingSelectTarget.value
: "";
else if (choice === "new")
projectName = this.hasNewNameTarget
? this.newNameTarget.value.trim()
: "";
if ((choice === "existing" || choice === "new") && !projectName) {
this.showDestError(
choice === "existing"
? "Pick a Hackatime project to send your time to."
: "Enter a name for the new Hackatime project.",
);
return;
}
if (this.hasFinishBtnTarget) this.finishBtnTarget.disabled = true;
if (projectName) {
this.setText(this.doneStatusTarget, "Sending your time to Hackatime…");
try {
await this.forwardHeartbeats(projectName);
this.setText(
this.doneStatusTarget,
`Time sent to “${projectName}” — it'll show up in Hackatime shortly.`,
);
} catch (error) {
// Surface the real reason next to the button and let the user retry,
// instead of advancing as though the time was sent.
console.error("Lookout forward error", error);
this.setText(this.doneStatusTarget, "Your timelapse is saved.");
this.showDestError(
error.message ||
"We couldn't send your time to Hackatime — please try again.",
);
if (this.hasFinishBtnTarget) this.finishBtnTarget.disabled = false;
return;
}
} else {
this.setText(
this.doneStatusTarget,
"All done — your recording was saved without sending time.",
);
}
if (this.hasDestinationTarget) this.destinationTarget.hidden = true;
// The time only counts toward the project once it's in a devlog — nudge the
// user there, but only when we actually sent time.
if (projectName && this.hasPostPromptTarget) {
this.postPromptTarget.hidden = false;
}
if (this.hasDoneCloseTarget) this.doneCloseTarget.hidden = false;
}
showDestError(message) {
if (!this.hasDestErrorTarget) return;
this.destErrorTarget.textContent = message;
this.destErrorTarget.hidden = false;
}
// Ask our backend to forward this session's capture timestamps to Hackatime
// as heartbeats under `projectName` (it has the user's token server-side).
async forwardHeartbeats(projectName) {
if (!this.forwardUrlValue || !projectName) return;
const res = await fetch(this.forwardUrlValue, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": this.csrfToken(),
Accept: "application/json",
},
body: JSON.stringify({ project_name: projectName }),
});
if (!res.ok) throw new Error(await this.forwardError(res));
}
// Pull the server's user-facing explanation out of the error response so the
// recorder shows *why* the send failed, not just a status code.
async forwardError(res) {
try {
const body = await res.json();
if (body && body.error) return body.error;
} catch (_) {
// non-JSON response
}
return `We couldn't send your time to Hackatime (error ${res.status}).`;
}
csrfToken() {
return document.querySelector('meta[name="csrf-token"]')?.content || "";
}
// ── status polling / completion ───────────────────────────────────────
async pollStatus(
statusEl,
{ showVideo = false, doneOnComplete = false } = {},
) {
this.clearTimer("statusTimer");
let data;
try {
data = await this.getJson(`/api/sessions/${this.tokenValue}/status`);
} catch (_) {
this.statusTimer = setTimeout(
() => this.pollStatus(statusEl, { showVideo, doneOnComplete }),
4000,
);
return;
}
if (data.status === "complete") {
// Stardance still shows this session in-progress until it syncs from
// Lookout — pull it now so the finished recording appears in the app.
this.syncStardance();
if (doneOnComplete) {
this.showStage("done");
this.chooseDestination();
this.setText(this.doneStatusTarget, "Your timelapse is ready!");
} else {
this.setText(statusEl, "Your timelapse is ready!");
}
if (showVideo) await this.revealVideo();
return;
}
if (data.status === "failed") {
this.setText(
doneOnComplete ? this.doneStatusTarget : statusEl,
"That recording failed to process — you can try again.",
);
return;
}
this.setText(
statusEl,
doneOnComplete
? "Waiting for your Lookout recording to finish…"
: "Finishing up processing your timelapse. This can take a minute or two. Keep this tab open.",
);
if (!TERMINAL.includes(data.status)) {
this.statusTimer = setTimeout(
() => this.pollStatus(statusEl, { showVideo, doneOnComplete }),
4000,
);
}
}
// Embed the compiled timelapse so the user can preview it before deciding
// where the time should go. Falls back to a "ready soon" note if not yet up.
async revealVideo() {
let url;
try {
const v = await this.getJson(`/api/sessions/${this.tokenValue}/video`);
url = v.videoUrl || v.video_url || v.url;
} catch (_) {
/* video URL not ready; the session row still syncs server-side later */
}
if (url && this.hasResultTarget) {
this.resultTarget.src = url;
this.resultTarget.hidden = false;
if (this.hasRenderingTarget) this.renderingTarget.hidden = true;
} else if (this.hasRenderingTarget) {
this.renderingTarget.textContent =
"Your timelapse will be ready to watch in a moment.";
}
}
close(event) {
if (event) event.preventDefault();
this.cleanup();
window.close();
}
// ── helpers ───────────────────────────────────────────────────────────
onTracked(seconds) {
if (seconds > this.baseSeconds) {
this.baseSeconds = seconds;
this.lastSyncMs = Date.now();
}
}
startDisplayTimer() {
this.updateTimer();
this.displayTimer = setInterval(() => this.updateTimer(), 1000);
}
updateTimer() {
if (!this.hasTimerTarget) return;
const elapsed = Math.max(
0,
Math.floor((Date.now() - this.lastSyncMs) / 1000),
);
this.timerTarget.textContent = this.formatTime(
this.baseSeconds + Math.min(60, elapsed),
);
}
formatTime(total) {
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
return h > 0 ? `${h}h ${m}m` : `${m}m ${s}s`;
}
togglePauseButtons() {
if (this.hasPauseBtnTarget) this.pauseBtnTarget.hidden = this.paused;
if (this.hasResumeBtnTarget) this.resumeBtnTarget.hidden = !this.paused;
}
showStage(stage) {
this.chooserTarget.hidden = stage !== "chooser";
if (this.hasDesktopStageTarget)
this.desktopStageTarget.hidden = stage !== "desktop";
if (this.hasCaptureStageTarget)
this.captureStageTarget.hidden = stage !== "capture";
if (this.hasDoneStageTarget) this.doneStageTarget.hidden = stage !== "done";
}
setStatus(text) {
this.setText(this.hasStatusTarget ? this.statusTarget : null, text);
}
setText(el, text) {
if (el) el.textContent = text;
}
showError(message) {
if (!this.hasErrorTarget) return;
this.errorTarget.textContent = message;
this.errorTarget.hidden = false;
this.showStage("chooser");
}
// ── Lookout client API (cross-origin, token-authenticated) ────────────
url(path) {
return `${this.apiBaseValue}${path}`;
}
async getJson(path) {
const res = await fetch(this.url(path), {
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(`GET ${path} -> ${res.status}`);
return res.json();
}
async postJson(path, body) {
const res = await fetch(this.url(path), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`POST ${path} -> ${res.status}`);
return res.json().catch(() => ({}));
}
async put(uploadUrl, blob) {
const res = await fetch(uploadUrl, {
method: "PUT",
body: blob,
headers: { "Content-Type": "image/jpeg" },
});
if (!res.ok) throw new Error(`PUT screenshot -> ${res.status}`);
}
// ── teardown ──────────────────────────────────────────────────────────
stopStream() {
if (this.stream) {
this.stream.getTracks().forEach((t) => t.stop());
this.stream = null;
}
}
clearTimer(name) {
if (this[name]) {
clearTimeout(this[name]);
clearInterval(this[name]);
this[name] = null;
}
}
cleanup() {
this.stopped = true;
this.clearTimer("captureTimer");
this.clearTimer("displayTimer");
this.clearTimer("statusTimer");
this.stopStream();
}
}