-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
623 lines (562 loc) · 20.2 KB
/
index.js
File metadata and controls
623 lines (562 loc) · 20.2 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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
#!/usr/bin/env node
try {
require('dotenv').config({ path: '.env.local' })
require('dotenv').config()
} catch (_err) {
// dotenv is optional in production containers.
}
const { addonBuilder, getRouter } = require('stremio-addon-sdk')
const express = require('express')
const DEFAULTS = {
timeFormat: '24h',
flashDurationSec: 10,
repeatIntervalSec: 60,
mode: 'flash'
}
const ALLOWED = {
timeFormat: new Set(['24h', '12h']),
flashDurationSec: new Set(['3', '5', '10', '15', '30', '60']),
repeatIntervalSec: new Set(['10', '20', '30', '60', '120', '300']),
mode: new Set(['flash', 'always-on', 'subliminal'])
}
const manifest = {
id: 'com.kepners.flashclock',
version: '1.0.0',
name: 'Clockrr (Top Right)',
description: 'Digital clock overlay via subtitles - flashes current time briefly, then disappears. Perfect for checking time when pausing.',
logo: 'https://raw.githubusercontent.com/Kepners/clockrr/master/logo.ico',
background: '#524948',
resources: ['subtitles'],
types: ['movie', 'series'],
catalogs: [],
stremioAddonsConfig: {
issuer: 'https://stremio-addons.net',
signature: 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..KgLtKC1PoD-j8qhI-KhRfA.rkzlJ3SK6rpY8yodw_4v-VhzbTyowuzeBUzjtduBcUNyzumYeqX-RKeHLfrNcelbLtDxQOWLpbGBkSUy9HAoOkJ8K4jU1IrTq_-SFB18QCBCmgc81BVutdVIayMPQ-2_.R1oeS6DraLHhHFwwzRhdPA'
},
behaviorHints: {
configurable: true,
configurationRequired: false
},
config: [
{
key: 'timeFormat',
type: 'select',
title: 'Time Format',
options: ['24h', '12h'],
default: DEFAULTS.timeFormat
},
{
key: 'flashDurationSec',
type: 'select',
title: 'Flash Duration (seconds)',
options: ['3', '5', '10', '15', '30', '60'],
default: String(DEFAULTS.flashDurationSec)
},
{
key: 'repeatIntervalSec',
type: 'select',
title: 'Repeat Interval (seconds)',
options: ['10', '20', '30', '60', '120', '300'],
default: String(DEFAULTS.repeatIntervalSec)
},
{
key: 'mode',
type: 'select',
title: 'Display Mode',
options: ['flash', 'always-on', 'subliminal'],
default: DEFAULTS.mode
}
]
}
const builder = new addonBuilder(manifest)
const cache = new Map()
const CACHE_TTL_MS = 30000
const PORT = process.env.PORT || 7000
function normalizeConfig(input = {}) {
const timeFormat = String(input.timeFormat || DEFAULTS.timeFormat)
const flashDurationSec = String(input.flashDurationSec || DEFAULTS.flashDurationSec)
const repeatIntervalSec = String(input.repeatIntervalSec || DEFAULTS.repeatIntervalSec)
const mode = String(input.mode || DEFAULTS.mode)
return {
timeFormat: ALLOWED.timeFormat.has(timeFormat) ? timeFormat : DEFAULTS.timeFormat,
flashDurationSec: ALLOWED.flashDurationSec.has(flashDurationSec) ? Number(flashDurationSec) : DEFAULTS.flashDurationSec,
repeatIntervalSec: ALLOWED.repeatIntervalSec.has(repeatIntervalSec) ? Number(repeatIntervalSec) : DEFAULTS.repeatIntervalSec,
mode: ALLOWED.mode.has(mode) ? mode : DEFAULTS.mode
}
}
function getCacheKey(config) {
return JSON.stringify(config)
}
function getCachedVTT(config) {
const cached = cache.get(getCacheKey(config))
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached.vtt
}
return null
}
function setCachedVTT(config, vtt) {
cache.set(getCacheKey(config), { vtt, timestamp: Date.now() })
if (cache.size > 100) {
const now = Date.now()
for (const [key, value] of cache.entries()) {
if (now - value.timestamp > CACHE_TTL_MS) {
cache.delete(key)
}
}
}
}
function formatTime(date, format) {
const hours = date.getHours()
const minutes = date.getMinutes()
if (format === '12h') {
const h12 = hours % 12 || 12
const ampm = hours < 12 ? 'AM' : 'PM'
return `${h12}:${minutes.toString().padStart(2, '0')} ${ampm}`
}
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
}
function formatVTTTime(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = Math.floor(totalSeconds % 60)
const ms = Math.floor((totalSeconds % 1) * 1000)
return [
hours.toString().padStart(2, '0'),
minutes.toString().padStart(2, '0'),
seconds.toString().padStart(2, '0')
].join(':') + `.${ms.toString().padStart(3, '0')}`
}
function generateWebVTT(rawConfig, baseTime) {
const config = normalizeConfig(rawConfig)
const totalSeconds = 12 * 60 * 60
let cueIndex = 1
let vtt = 'WEBVTT\n\n'
if (config.mode === 'always-on' || config.mode === 'subliminal') {
const duration = config.mode === 'always-on' ? 1 : 0.05
for (let t = 0; t < totalSeconds; t += 1) {
const cueDate = new Date(baseTime.getTime() + (t * 1000))
vtt += `${cueIndex}\n`
vtt += `${formatVTTTime(t)} --> ${formatVTTTime(t + duration)} line:5% position:95% align:end\n`
vtt += `${formatTime(cueDate, config.timeFormat)}\n\n`
cueIndex++
}
return vtt
}
for (let t = 0; t < totalSeconds; t += config.repeatIntervalSec) {
const cueDate = new Date(baseTime.getTime() + (t * 1000))
vtt += `${cueIndex}\n`
vtt += `${formatVTTTime(t)} --> ${formatVTTTime(t + config.flashDurationSec)} line:5% position:95% align:end\n`
vtt += `${formatTime(cueDate, config.timeFormat)}\n\n`
cueIndex++
}
return vtt
}
function parseConfig(configStr) {
if (!configStr) return {}
try {
return JSON.parse(Buffer.from(configStr, 'base64').toString('utf-8'))
} catch {
try {
return JSON.parse(decodeURIComponent(configStr))
} catch {
return {}
}
}
}
function encodeConfig(config) {
return Buffer.from(JSON.stringify(normalizeConfig(config))).toString('base64')
}
function getTimeBucket(date = new Date()) {
return [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, '0'),
String(date.getDate()).padStart(2, '0'),
String(date.getHours()).padStart(2, '0'),
String(date.getMinutes()).padStart(2, '0')
].join('')
}
function parseBucketTime(bucket) {
if (!bucket || !/^\d{12}$/.test(String(bucket))) {
return new Date()
}
const text = String(bucket)
return new Date(
Number(text.slice(0, 4)),
Number(text.slice(4, 6)) - 1,
Number(text.slice(6, 8)),
Number(text.slice(8, 10)),
Number(text.slice(10, 12)),
0
)
}
function getRequestOrigin(req) {
const forwardedProto = (req.get('x-forwarded-proto') || '').split(',')[0].trim()
const forwardedHost = (req.get('x-forwarded-host') || '').split(',')[0].trim()
const protocol = forwardedProto || req.protocol || 'http'
const host = forwardedHost || req.get('host') || `localhost:${PORT}`
return `${protocol}://${host}`.replace(/\/+$/, '')
}
function getConfiguredBaseUrl(req) {
const explicitBaseUrl = (process.env.ADDON_URL || '').trim()
if (explicitBaseUrl) {
return explicitBaseUrl.replace(/\/+$/, '')
}
if (req) {
return getRequestOrigin(req)
}
return `http://localhost:${PORT}`
}
function toStremioInstallUrl(baseUrl, manifestPath = '/manifest.json') {
const normalizedBaseUrl = String(baseUrl || '').replace(/\/+$/, '')
const normalizedManifestPath = manifestPath.startsWith('/') ? manifestPath : `/${manifestPath}`
return `stremio://${normalizedBaseUrl.replace(/^https?:\/\//, '')}${normalizedManifestPath}`
}
function buildSubtitlesResponse(type, _id, userConfig = {}, req) {
if (!['movie', 'series'].includes(type)) {
return { subtitles: [] }
}
const config = normalizeConfig(userConfig)
const cfgEncoded = encodeConfig(config)
const baseUrl = getConfiguredBaseUrl(req)
const timeBucket = getTimeBucket()
return {
subtitles: [
{
id: 'flashclock-time',
lang: 'eng',
label: 'Clockrr (Top Right)',
url: `${baseUrl}/flashclock.vtt?cfg=${cfgEncoded}&t=${timeBucket}`
}
]
}
}
builder.defineSubtitlesHandler(({ type, id, config }) => {
console.log(`[Clockrr] Subtitles request: type=${type}, id=${id}`)
return Promise.resolve(buildSubtitlesResponse(type, id, config || {}))
})
const app = express()
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type')
if (req.method === 'OPTIONS') {
return res.sendStatus(200)
}
next()
})
app.get('/robots.txt', (req, res) => {
const origin = getRequestOrigin(req)
res.type('text/plain').send([
'User-agent: *',
'Allow: /',
'',
`Sitemap: ${origin}/sitemap.xml`
].join('\n'))
})
app.get('/sitemap.xml', (req, res) => {
const origin = getRequestOrigin(req)
res.type('application/xml').send(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>${origin}/</loc><changefreq>monthly</changefreq><priority>1.0</priority></url>
<url><loc>${origin}/configure</loc><changefreq>monthly</changefreq><priority>0.8</priority></url>
</urlset>`)
})
app.get('/', (req, res) => {
const installUrl = toStremioInstallUrl(getRequestOrigin(req))
res.type('html').send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clockrr - Stremio Subtitle Clock Addon</title>
<meta name="description" content="Clockrr adds a configurable clock overlay to Stremio using a subtitle track.">
<link rel="icon" type="image/x-icon" href="https://raw.githubusercontent.com/Kepners/clockrr/master/logo.ico">
<style>
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #fff;
background:
radial-gradient(circle at 20% 20%, rgba(124, 180, 184, 0.28), transparent 34rem),
linear-gradient(180deg, #524948 0%, #312d2c 100%);
}
main {
width: min(920px, calc(100% - 32px));
margin: 0 auto;
min-height: 100vh;
display: grid;
align-content: center;
gap: 32px;
padding: 48px 0;
}
.hero { display: grid; gap: 18px; }
h1 {
margin: 0;
font-size: clamp(2.8rem, 8vw, 5.8rem);
line-height: 0.95;
letter-spacing: 0;
}
.tagline {
margin: 0;
max-width: 620px;
color: rgba(255,255,255,0.78);
font-size: clamp(1.1rem, 3vw, 1.45rem);
line-height: 1.45;
}
.clock {
display: inline-flex;
width: fit-content;
padding: 12px 18px;
border: 1px solid rgba(112, 248, 186, 0.34);
border-radius: 8px;
background: rgba(0,0,0,0.24);
color: #70F8BA;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: clamp(1.8rem, 6vw, 3rem);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 14px;
}
.button {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48px;
padding: 0 20px;
border-radius: 8px;
font-weight: 700;
color: #191919;
background: #70F8BA;
text-decoration: none;
}
.button.secondary {
color: #fff;
background: rgba(255,255,255,0.12);
border: 1px solid rgba(255,255,255,0.18);
}
.features {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 14px;
}
.feature {
border: 1px solid rgba(255,255,255,0.12);
border-radius: 8px;
padding: 16px;
background: rgba(255,255,255,0.06);
}
.feature h2 {
margin: 0 0 8px;
font-size: 1rem;
}
.feature p {
margin: 0;
color: rgba(255,255,255,0.72);
line-height: 1.5;
}
</style>
</head>
<body>
<main>
<section class="hero">
<h1>Clockrr</h1>
<p class="tagline">A Stremio subtitle addon that flashes the current time in the top-right corner while you watch.</p>
<div class="clock" id="liveClock">--:--:--</div>
<div class="actions">
<a class="button" href="${installUrl}">Install in Stremio</a>
<a class="button secondary" href="/configure">Configure</a>
</div>
</section>
<section class="features" aria-label="Clockrr modes">
<article class="feature">
<h2>Flash</h2>
<p>Show the time briefly at the interval you choose.</p>
</article>
<article class="feature">
<h2>Always On</h2>
<p>Keep a clock cue visible continuously during playback.</p>
</article>
<article class="feature">
<h2>Subtitle Based</h2>
<p>Works through Stremio's subtitle track flow without a media source.</p>
</article>
</section>
</main>
<script>
function updateClock() {
const now = new Date();
const h = String(now.getHours()).padStart(2, '0');
const m = String(now.getMinutes()).padStart(2, '0');
const s = String(now.getSeconds()).padStart(2, '0');
document.getElementById('liveClock').textContent = h + ':' + m + ':' + s;
}
updateClock();
setInterval(updateClock, 1000);
</script>
</body>
</html>`)
})
app.get('/flashclock.vtt', (req, res) => {
const config = normalizeConfig(parseConfig(req.query.cfg))
const baseTime = parseBucketTime(req.query.t)
const cacheConfig = { ...config, t: req.query.t || '' }
let vtt = getCachedVTT(cacheConfig)
if (!vtt) {
vtt = generateWebVTT(config, baseTime)
setCachedVTT(cacheConfig, vtt)
}
res.set({
'Content-Type': 'text/vtt; charset=utf-8',
'Cache-Control': 'public, max-age=3600, s-maxage=3600'
})
res.send(vtt)
})
function renderOptions(values, current) {
return values.map(value => {
const selected = String(value) === String(current) ? ' selected' : ''
return `<option value="${value}"${selected}>${value}</option>`
}).join('')
}
function getConfigureHTML(currentConfig = {}) {
const config = normalizeConfig(currentConfig)
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clockrr - Configure</title>
<style>
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: linear-gradient(135deg, #524948 0%, #312d2c 100%);
}
.panel {
width: min(440px, 100%);
padding: 28px;
border-radius: 8px;
background: #fff;
color: #222;
box-shadow: 0 24px 80px rgba(0,0,0,0.32);
}
h1 { margin: 0 0 8px; font-size: 1.6rem; }
p { margin: 0 0 22px; color: #666; line-height: 1.45; }
label {
display: block;
margin: 18px 0 8px;
font-size: 0.9rem;
font-weight: 700;
}
select {
width: 100%;
min-height: 44px;
padding: 0 12px;
border: 1px solid #cfcfcf;
border-radius: 8px;
background: #fff;
font-size: 1rem;
}
.button {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 48px;
margin-top: 24px;
border-radius: 8px;
background: #57467B;
color: #fff;
font-weight: 700;
text-decoration: none;
}
.manifest {
margin-top: 14px;
padding: 10px;
border-radius: 8px;
background: #f5f5f5;
color: #555;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 0.75rem;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main class="panel">
<h1>Clockrr</h1>
<p>Configure the subtitle clock track before installing it in Stremio.</p>
<label for="timeFormat">Time Format</label>
<select id="timeFormat" onchange="updateLink()">
${renderOptions(['24h', '12h'], config.timeFormat)}
</select>
<label for="mode">Display Mode</label>
<select id="mode" onchange="updateLink()">
${renderOptions(['flash', 'always-on', 'subliminal'], config.mode)}
</select>
<label for="flashDurationSec">Flash Duration Seconds</label>
<select id="flashDurationSec" onchange="updateLink()">
${renderOptions(['3', '5', '10', '15', '30', '60'], config.flashDurationSec)}
</select>
<label for="repeatIntervalSec">Repeat Interval Seconds</label>
<select id="repeatIntervalSec" onchange="updateLink()">
${renderOptions(['10', '20', '30', '60', '120', '300'], config.repeatIntervalSec)}
</select>
<a id="installLink" class="button" href="#">Install in Stremio</a>
<div id="manifestUrl" class="manifest"></div>
</main>
<script>
function updateLink() {
const config = {
timeFormat: document.getElementById('timeFormat').value,
mode: document.getElementById('mode').value,
flashDurationSec: document.getElementById('flashDurationSec').value,
repeatIntervalSec: document.getElementById('repeatIntervalSec').value
};
const configStr = btoa(JSON.stringify(config));
const manifestPath = '/' + configStr + '/manifest.json';
const manifestUrl = window.location.origin + manifestPath;
document.getElementById('installLink').href = 'stremio://' + window.location.host + manifestPath;
document.getElementById('manifestUrl').textContent = manifestUrl;
}
updateLink();
</script>
</body>
</html>`
}
app.get('/configure', (_req, res) => {
res.type('html').send(getConfigureHTML({}))
})
app.get('/:config/configure', (req, res) => {
res.type('html').send(getConfigureHTML(parseConfig(req.params.config)))
})
app.get('/:config/manifest.json', (req, res) => {
parseConfig(req.params.config)
res.json(manifest)
})
app.get('/subtitles/:type/:id.json', (req, res) => {
const { type, id } = req.params
console.log(`[Clockrr] Base subtitles: type=${type}, id=${id}`)
res.json(buildSubtitlesResponse(type, id, {}, req))
})
app.get('/:config/subtitles/:type/:id.json', (req, res) => {
const { config, type, id } = req.params
console.log(`[Clockrr] Config subtitles: type=${type}, id=${id}`)
res.json(buildSubtitlesResponse(type, id, parseConfig(config), req))
})
app.use(getRouter(builder.getInterface()))
module.exports = app
if (require.main === module) {
app.listen(PORT, () => {
console.log(`Clockrr running on http://localhost:${PORT}`)
console.log(`Manifest: http://localhost:${PORT}/manifest.json`)
})
}