-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsite-usage-tracker.user.js
More file actions
853 lines (732 loc) · 25.5 KB
/
Copy pathwebsite-usage-tracker.user.js
File metadata and controls
853 lines (732 loc) · 25.5 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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
// ==UserScript==
// @name Website Usage Tracker
// @namespace local.website-usage-tracker
// @version 1.1.0
// @description Track daily sessions, opening times, per-session duration, and total time for configured websites.
// @author local
// @match *://*/*
// @run-at document-start
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_registerMenuCommand
// ==/UserScript==
(function () {
'use strict';
const SETTINGS = {
storageKey: 'websiteUsageTracker.v1',
configKey: 'websiteUsageTracker.config.v1',
tabSessionKey: 'websiteUsageTracker.activeVisit.v1',
heartbeatMs: 15_000,
idleAfterMs: 5 * 60_000,
resumeWithinMs: 2 * 60_000,
dashboardHash: '#website-usage-tracker',
};
const now = () => Date.now();
const createVisitId = () => `${now().toString(36)}-${Math.random().toString(36).slice(2)}`;
const page = {
host: location.hostname.toLowerCase(),
};
const DEFAULT_TRACKING_CONFIG = {
version: 1,
rules: [],
};
let currentVisit = null;
let started = false;
let finalized = false;
let visibleSince = document.visibilityState === 'visible' ? now() : null;
let activeMs = 0;
let lastActivityAt = now();
let lastRecordedUrl = location.href;
registerMenuCommands();
maybeOpenDashboardFromHash();
initializeTracking();
async function initializeTracking() {
const config = await readTrackingConfig();
const matchedRule = getMatchedTrackingRule(config);
if (!matchedRule) return;
startTracking(getSiteLabel(matchedRule));
}
function startTracking(siteLabel) {
if (started) return;
window.addEventListener('focus', markActivity, true);
window.addEventListener('blur', flushVisit, true);
window.addEventListener('mousemove', markActivity, true);
window.addEventListener('keydown', markActivity, true);
window.addEventListener('scroll', markActivity, true);
window.addEventListener('pointerdown', markActivity, true);
document.addEventListener('visibilitychange', onVisibilityChange, true);
window.addEventListener('pagehide', finalizeVisit, true);
window.addEventListener('beforeunload', finalizeVisit, true);
setInterval(flushVisit, SETTINGS.heartbeatMs);
installSpaUrlWatcher();
startVisit(siteLabel);
}
async function startVisit(siteLabel) {
if (started) return;
started = true;
const date = localDateKey(new Date());
const tabSession = readTabSession(siteLabel);
currentVisit = {
id: tabSession?.id || createVisitId(),
site: siteLabel,
host: page.host,
url: location.href,
title: document.title || '',
date,
openedAt: tabSession?.openedAt || new Date().toISOString(),
closedAt: null,
durationMs: tabSession?.durationMs || 0,
lastSeenAt: new Date().toISOString(),
};
activeMs = currentVisit.durationMs;
const db = await readDb();
const day = ensureDay(db, currentVisit.date);
const site = ensureSite(day, currentVisit.site, page.host);
const storedVisit = findVisit(db, currentVisit.date, currentVisit.site, currentVisit.id);
if (storedVisit) {
const previousDuration = storedVisit.durationMs || 0;
Object.assign(storedVisit, currentVisit);
site.totalMs = Math.max(0, (site.totalMs || 0) + currentVisit.durationMs - previousDuration);
} else {
site.opens += 1;
site.visits.push(currentVisit);
}
saveTabSession();
await writeDb(db);
}
async function flushVisit() {
if (!currentVisit || finalized) return;
accrueVisibleTime();
currentVisit.durationMs = activeMs;
currentVisit.title = document.title || currentVisit.title;
currentVisit.url = location.href;
currentVisit.lastSeenAt = new Date().toISOString();
currentVisit.closedAt = null;
saveTabSession();
const db = await readDb();
const storedVisit = findVisit(db, currentVisit.date, currentVisit.site, currentVisit.id);
if (!storedVisit) return;
const previousDuration = storedVisit.durationMs || 0;
Object.assign(storedVisit, currentVisit);
const site = ensureSite(ensureDay(db, currentVisit.date), currentVisit.site, page.host);
site.totalMs = Math.max(0, (site.totalMs || 0) + currentVisit.durationMs - previousDuration);
await writeDb(db);
}
async function finalizeVisit() {
if (!currentVisit || finalized) return;
finalized = true;
accrueVisibleTime();
currentVisit.durationMs = activeMs;
currentVisit.closedAt = new Date().toISOString();
currentVisit.lastSeenAt = currentVisit.closedAt;
saveTabSession();
const db = await readDb();
const storedVisit = findVisit(db, currentVisit.date, currentVisit.site, currentVisit.id);
if (storedVisit) {
const previousDuration = storedVisit.durationMs || 0;
Object.assign(storedVisit, currentVisit);
const site = ensureSite(ensureDay(db, currentVisit.date), currentVisit.site, page.host);
site.totalMs = Math.max(0, (site.totalMs || 0) + currentVisit.durationMs - previousDuration);
await writeDb(db);
}
}
function readTabSession(siteLabel) {
try {
const raw = sessionStorage.getItem(SETTINGS.tabSessionKey);
if (!raw) return null;
const value = JSON.parse(raw);
if (!value || typeof value !== 'object') return null;
if (value.site !== siteLabel) return null;
if (value.date !== localDateKey(new Date())) return null;
if (!value.id || !value.openedAt) return null;
const lastSeen = Date.parse(value.lastSeenAt || value.openedAt);
if (!Number.isFinite(lastSeen) || now() - lastSeen > SETTINGS.resumeWithinMs) return null;
return {
id: String(value.id),
site: String(value.site),
date: String(value.date),
openedAt: String(value.openedAt),
durationMs: Math.max(0, Number(value.durationMs) || 0),
};
} catch (_error) {
return null;
}
}
function saveTabSession() {
if (!currentVisit) return;
try {
sessionStorage.setItem(
SETTINGS.tabSessionKey,
JSON.stringify({
id: currentVisit.id,
site: currentVisit.site,
date: currentVisit.date,
openedAt: currentVisit.openedAt,
durationMs: currentVisit.durationMs || activeMs || 0,
lastSeenAt: currentVisit.lastSeenAt || new Date().toISOString(),
}),
);
} catch (_error) {
// Browsers can block sessionStorage; tracking still works without reload merging.
}
}
function onVisibilityChange() {
markActivity();
if (document.visibilityState === 'visible') {
visibleSince = now();
} else {
accrueVisibleTime();
visibleSince = null;
flushVisit();
}
}
function markActivity() {
lastActivityAt = now();
}
function accrueVisibleTime() {
if (document.visibilityState !== 'visible' || visibleSince === null) return;
const current = now();
const windowMs = current - visibleSince;
const idleMs = current - lastActivityAt;
if (idleMs <= SETTINGS.idleAfterMs) {
activeMs += windowMs;
} else {
const activeCutoff = Math.max(0, SETTINGS.idleAfterMs - (lastActivityAt - visibleSince));
activeMs += Math.min(windowMs, activeCutoff);
}
visibleSince = current;
}
function installSpaUrlWatcher() {
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function (...args) {
const result = originalPushState.apply(this, args);
onPotentialUrlChange();
return result;
};
history.replaceState = function (...args) {
const result = originalReplaceState.apply(this, args);
onPotentialUrlChange();
return result;
};
window.addEventListener('popstate', onPotentialUrlChange, true);
}
function onPotentialUrlChange() {
window.setTimeout(() => {
if (location.href === lastRecordedUrl) return;
lastRecordedUrl = location.href;
flushVisit();
}, 0);
}
function registerMenuCommands() {
const register = getMenuRegister();
if (!register) return;
register('Track this site', trackCurrentSite);
register('Configure tracked sites', configureTrackedSites);
register('Show website usage stats', showDashboard);
register('Export website usage JSON', exportJson);
register('Reset website usage data', resetAllData);
}
async function trackCurrentSite() {
const config = await readTrackingConfig();
const existingRule = config.rules.find((rule) => matchesTrackingRule(rule, location.href, page.host, location.pathname));
if (existingRule) {
window.alert(`${page.host} is already tracked by "${existingRule.pattern}".`);
return;
}
const label = window.prompt(`Optional dashboard label for ${page.host}:`, '');
if (label === null) return;
const rule = { pattern: page.host, label: label.trim() };
config.rules.push(rule);
await writeTrackingConfig(config);
if (!started) startTracking(getSiteLabel(rule));
window.alert(`${page.host} is now tracked.`);
}
async function configureTrackedSites() {
const config = await readTrackingConfig();
const input = window.prompt(
[
'Tracked sites, separated by commas or new lines.',
'Use "pattern = Label" to set a dashboard label.',
'Examples: app.posthog.com = PostHog, *.reddit.com',
].join('\n'),
serializeTrackingConfig(config),
);
if (input === null) return;
const nextConfig = {
version: 1,
rules: parseTrackingConfigText(input),
};
await writeTrackingConfig(nextConfig);
const matchedRule = getMatchedTrackingRule(nextConfig);
if (!started && matchedRule) startTracking(getSiteLabel(matchedRule));
window.alert('Tracked sites saved. Reload any open tracked tabs to apply changes there.');
}
function maybeOpenDashboardFromHash() {
if (location.hash === SETTINGS.dashboardHash) {
window.setTimeout(showDashboard, 250);
}
}
async function showDashboard() {
await flushVisit();
const existing = document.getElementById('wut-dashboard');
if (existing) {
existing.remove();
return;
}
const db = await readDb();
const root = document.createElement('div');
root.id = 'wut-dashboard';
root.attachShadow({ mode: 'open' });
const shadow = root.shadowRoot;
shadow.innerHTML = `
<style>
:host {
all: initial;
color-scheme: light dark;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.backdrop {
position: fixed;
inset: 0;
z-index: 2147483647;
background: rgba(15, 23, 42, 0.45);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 6vh 16px;
box-sizing: border-box;
}
.panel {
width: min(980px, 100%);
max-height: 88vh;
overflow: auto;
background: Canvas;
color: CanvasText;
border: 1px solid color-mix(in srgb, CanvasText 18%, transparent);
border-radius: 8px;
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.25);
}
header {
position: sticky;
top: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 14px 16px;
background: Canvas;
border-bottom: 1px solid color-mix(in srgb, CanvasText 14%, transparent);
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1.25;
font-weight: 650;
}
.actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
button,
select {
min-height: 34px;
border: 1px solid color-mix(in srgb, CanvasText 22%, transparent);
border-radius: 6px;
background: Canvas;
color: CanvasText;
font: inherit;
font-size: 13px;
padding: 0 10px;
}
button {
cursor: pointer;
}
main {
padding: 16px;
}
.summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
margin-bottom: 16px;
}
.metric {
border: 1px solid color-mix(in srgb, CanvasText 12%, transparent);
border-radius: 8px;
padding: 12px;
}
.metric strong {
display: block;
font-size: 20px;
line-height: 1.2;
}
.metric span {
display: block;
margin-top: 3px;
color: color-mix(in srgb, CanvasText 68%, transparent);
font-size: 12px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
th,
td {
padding: 9px 8px;
text-align: left;
border-bottom: 1px solid color-mix(in srgb, CanvasText 11%, transparent);
vertical-align: top;
}
th {
font-size: 12px;
color: color-mix(in srgb, CanvasText 70%, transparent);
font-weight: 650;
}
.muted {
color: color-mix(in srgb, CanvasText 62%, transparent);
}
.visit-list {
margin: 0;
padding: 0;
list-style: none;
}
.visit-list li + li {
margin-top: 5px;
}
.url {
max-width: 340px;
overflow-wrap: anywhere;
}
@media (max-width: 680px) {
.backdrop {
padding: 0;
}
.panel {
min-height: 100vh;
max-height: 100vh;
border-radius: 0;
border: 0;
}
header {
align-items: flex-start;
flex-direction: column;
}
th:nth-child(3),
td:nth-child(3) {
display: none;
}
}
</style>
<div class="backdrop" part="backdrop">
<section class="panel" role="dialog" aria-modal="true" aria-label="Website usage statistics">
<header>
<h1>Website Usage</h1>
<div class="actions">
<select id="date-select" aria-label="Date"></select>
<button id="export">Export JSON</button>
<button id="reset-today">Reset Day</button>
<button id="close">Close</button>
</div>
</header>
<main id="content"></main>
</section>
</div>
`;
document.documentElement.appendChild(root);
const dateSelect = shadow.getElementById('date-select');
const content = shadow.getElementById('content');
const dates = Object.keys(db.days || {}).sort().reverse();
const today = localDateKey(new Date());
const selectedDate = dates.includes(today) ? today : dates[0] || today;
if (!dates.includes(today)) dates.unshift(today);
for (const date of dates) {
const option = document.createElement('option');
option.value = date;
option.textContent = date;
dateSelect.appendChild(option);
}
dateSelect.value = selectedDate;
const render = () => renderDay(content, db, dateSelect.value);
dateSelect.addEventListener('change', render);
shadow.getElementById('close').addEventListener('click', () => root.remove());
shadow.querySelector('.backdrop').addEventListener('click', (event) => {
if (event.target === event.currentTarget) root.remove();
});
shadow.getElementById('export').addEventListener('click', exportJson);
shadow.getElementById('reset-today').addEventListener('click', async () => {
if (!window.confirm(`Reset usage data for ${dateSelect.value}?`)) return;
const latest = await readDb();
delete latest.days[dateSelect.value];
await writeDb(latest);
root.remove();
showDashboard();
});
render();
}
function renderDay(container, db, date) {
const day = db.days[date] || { sites: {} };
const sites = Object.values(day.sites || {}).sort((a, b) => (b.totalMs || 0) - (a.totalMs || 0));
const totalSessions = sites.reduce((sum, site) => sum + (site.opens || 0), 0);
const totalMs = sites.reduce((sum, site) => sum + (site.totalMs || 0), 0);
container.innerHTML = `
<section class="summary">
<div class="metric"><strong>${sites.length}</strong><span>Tracked sites</span></div>
<div class="metric"><strong>${totalSessions}</strong><span>Total sessions</span></div>
<div class="metric"><strong>${formatDuration(totalMs)}</strong><span>Total active time</span></div>
</section>
${
sites.length
? `<table>
<thead>
<tr>
<th>Site</th>
<th>Sessions</th>
<th>Total</th>
<th>Session details</th>
</tr>
</thead>
<tbody>
${sites.map(renderSiteRow).join('')}
</tbody>
</table>`
: '<p class="muted">No visits recorded for this day.</p>'
}
`;
}
function renderSiteRow(site) {
const visits = [...(site.visits || [])].sort((a, b) => String(a.openedAt).localeCompare(String(b.openedAt)));
return `
<tr>
<td>
<strong>${escapeHtml(site.label || site.host)}</strong>
<div class="muted">${escapeHtml(site.host || '')}</div>
</td>
<td>${site.opens || visits.length}</td>
<td>${formatDuration(site.totalMs || 0)}</td>
<td>
<ul class="visit-list">
${visits
.map(
(visit) => `
<li>
<strong>${formatTime(visit.openedAt)}</strong>
<span class="muted">for ${formatDuration(visit.durationMs || 0)}</span>
<div class="url">${escapeHtml(visit.url || '')}</div>
</li>
`,
)
.join('')}
</ul>
</td>
</tr>
`;
}
async function exportJson() {
await flushVisit();
const db = await readDb();
const blob = new Blob([JSON.stringify(db, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `website-usage-${localDateKey(new Date())}.json`;
link.style.display = 'none';
document.documentElement.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
async function resetAllData() {
if (!window.confirm('Reset all website usage data?')) return;
await deleteValue(SETTINGS.storageKey);
}
async function readTrackingConfig() {
const value = await getValue(SETTINGS.configKey, DEFAULT_TRACKING_CONFIG);
return normalizeTrackingConfig(value);
}
async function writeTrackingConfig(config) {
await setValue(SETTINGS.configKey, normalizeTrackingConfig(config));
}
function normalizeTrackingConfig(value) {
const rules = Array.isArray(value?.rules) ? value.rules : Array.isArray(value?.sites) ? value.sites : [];
return {
version: 1,
rules: rules.map(normalizeTrackingRule).filter(Boolean),
};
}
function normalizeTrackingRule(rule) {
if (typeof rule === 'string') return parseTrackingRuleLine(rule);
if (!rule || typeof rule !== 'object') return null;
const pattern = String(rule.pattern || '').trim();
if (!pattern) return null;
return {
pattern,
label: String(rule.label || '').trim(),
};
}
function parseTrackingConfigText(text) {
return String(text)
.split(/[\n,]+/)
.map(parseTrackingRuleLine)
.filter(Boolean);
}
function parseTrackingRuleLine(line) {
const trimmed = String(line).trim();
if (!trimmed || trimmed.startsWith('#')) return null;
const labelMatch = trimmed.match(/^(.+?)\s+=\s+(.+)$/);
const pattern = (labelMatch ? labelMatch[1] : trimmed).trim();
if (!pattern) return null;
return {
pattern,
label: labelMatch ? labelMatch[2].trim() : '',
};
}
function serializeTrackingConfig(config) {
return normalizeTrackingConfig(config)
.rules.map((rule) => (rule.label ? `${rule.pattern} = ${rule.label}` : rule.pattern))
.join('\n');
}
function getMatchedTrackingRule(config) {
return normalizeTrackingConfig(config).rules.find((rule) =>
matchesTrackingRule(rule, location.href, page.host, location.pathname),
);
}
function matchesTrackingRule(rule, url, host, path) {
const pattern = String(rule?.pattern || '').trim().toLowerCase();
if (!pattern) return false;
if (pattern.startsWith('/') && pattern.endsWith('/') && pattern.length > 2) {
try {
return new RegExp(pattern.slice(1, -1)).test(url);
} catch (_error) {
return false;
}
}
if (pattern.includes('*') && pattern.includes('://')) {
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
return new RegExp(`^${escaped}$`, 'i').test(url);
}
if (pattern.startsWith('http://') || pattern.startsWith('https://')) {
try {
const parsed = new URL(pattern);
const expectedPath = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, '');
const currentPath = path.replace(/\/+$/, '');
return (
location.protocol === parsed.protocol &&
host === parsed.hostname.toLowerCase() &&
(!expectedPath || currentPath === expectedPath || currentPath.startsWith(`${expectedPath}/`))
);
} catch (_error) {
return false;
}
}
if (pattern.startsWith('*.')) {
const domain = pattern.slice(2);
return host.endsWith(`.${domain}`);
}
return host === pattern || host.endsWith(`.${pattern}`);
}
async function readDb() {
const fallback = { version: 1, days: {} };
const value = await getValue(SETTINGS.storageKey, fallback);
if (!value || typeof value !== 'object') return fallback;
if (!value.days || typeof value.days !== 'object') value.days = {};
return value;
}
async function writeDb(db) {
db.updatedAt = new Date().toISOString();
await setValue(SETTINGS.storageKey, db);
}
function ensureDay(db, date) {
if (!db.days[date]) db.days[date] = { sites: {} };
if (!db.days[date].sites) db.days[date].sites = {};
return db.days[date];
}
function ensureSite(day, label, host) {
if (!day.sites[label]) {
day.sites[label] = {
label,
host,
opens: 0,
totalMs: 0,
visits: [],
};
}
return day.sites[label];
}
function findVisit(db, date, siteLabel, id) {
const site = db.days?.[date]?.sites?.[siteLabel];
if (!site) return null;
return site.visits.find((visit) => visit.id === id) || null;
}
function getSiteLabel(rule) {
const configuredLabel = String(rule?.label || '').trim();
if (configuredLabel) return configuredLabel;
const pattern = String(rule?.pattern || '').trim();
if (!pattern || pattern.includes('*') || pattern.startsWith('/') || pattern.includes('://')) {
return page.host;
}
return pattern.replace(/^\*\./, '').toLowerCase();
}
function localDateKey(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function formatTime(iso) {
if (!iso) return 'open';
return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
function formatDuration(ms) {
const seconds = Math.max(0, Math.round(ms / 1000));
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours) return `${hours}h ${minutes}m`;
if (minutes) return `${minutes}m ${secs}s`;
return `${secs}s`;
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => {
const entities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return entities[char];
});
}
function getMenuRegister() {
if (typeof GM_registerMenuCommand === 'function') return GM_registerMenuCommand;
if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand === 'function') {
return (name, callback) => GM.registerMenuCommand(name, callback);
}
return null;
}
async function getValue(key, defaultValue) {
if (typeof GM_getValue === 'function') return GM_getValue(key, defaultValue);
if (typeof GM !== 'undefined' && typeof GM.getValue === 'function') return GM.getValue(key, defaultValue);
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : defaultValue;
}
async function setValue(key, value) {
if (typeof GM_setValue === 'function') return GM_setValue(key, value);
if (typeof GM !== 'undefined' && typeof GM.setValue === 'function') return GM.setValue(key, value);
localStorage.setItem(key, JSON.stringify(value));
}
async function deleteValue(key) {
if (typeof GM_deleteValue === 'function') return GM_deleteValue(key);
if (typeof GM !== 'undefined' && typeof GM.deleteValue === 'function') return GM.deleteValue(key);
localStorage.removeItem(key);
}
})();