// ==UserScript== // @name Activity Tracker // @namespace adam-french.co.uk/activity-tracker // @version 1.0.0 // @description Records time spent on the focused tab and uploads it to the activity tracker. // @match *://*/* // @noframes // @run-at document-start // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_listValues // @grant GM_registerMenuCommand // @connect * // ==/UserScript== // Every tab runs its own copy of this script. A tab records a tab_focus // interval only while it is the selected tab of the focused browser window, // so at most one tab per browser is recording at any time. Closed intervals // are queued in the script's shared storage (one key per event, so tabs never // overwrite each other) and whichever tab holds the upload lease sends them. (function () { 'use strict'; const DEFAULTS = { url: '', // e.g. https://www.adam-french.co.uk/tracker key: '', // API key created with --kind browser fullUrls: false, // send attrs.url and split intervals per page titles: false, // send attrs.title (the title when the interval started) ignore: '', // regexp; matching hostnames are not recorded idleMinutes: 5, // no input for this long (and no media playing) ends the interval }; const MIN_DURATION = 2e3; // drop alt-tab flicker, as the Hyprland agent does const TICK = 1e3; const CHECKPOINT = 5e3; // how often the open interval is saved const GAP = 30e3; // a longer pause between ticks means the machine slept const STALE = 60e3; // other tabs' open intervals older than this are closed for them const UPLOAD_EVERY = 60e3; const LEASE = 90e3; const BATCH = 500; const config = () => ({ ...DEFAULTS, ...GM_getValue('config', {}) }); const ready = (c) => Boolean(c.url && c.key); function randomID() { // crypto.randomUUID needs a secure context; getRandomValues works on http pages too. const b = crypto.getRandomValues(new Uint8Array(16)); return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join(''); } const TAB = randomID(); // ---- tracking ---- let cur = null; // {id, key, label, attrs, start, seen, saved} let lastActive = Date.now(); for (const t of ['mousemove', 'mousedown', 'keydown', 'wheel', 'scroll', 'touchstart']) { window.addEventListener(t, () => { lastActive = Date.now(); }, { capture: true, passive: true }); } function mediaPlaying() { for (const m of document.querySelectorAll('video, audio')) { if (!m.paused && !m.ended && m.readyState > 2) return true; } return false; } // What this tab should be recording right now, or null. function wanted(c, now) { if (!ready(c)) return null; if (document.visibilityState !== 'visible' || !document.hasFocus()) return null; if (mediaPlaying()) lastActive = now; if (now - lastActive > c.idleMinutes * 60e3) return null; const host = location.hostname.replace(/^www\./, ''); if (!host) return null; if (c.ignore) { try { if (new RegExp(c.ignore, 'i').test(host)) return null; } catch (_) { /* bad regexp: ignore nothing */ } } const attrs = {}; if (c.fullUrls) attrs.url = location.href; if (c.titles && document.title) attrs.title = document.title; return { key: host + '\n' + (attrs.url || ''), label: host, attrs }; } function toEvent(o, end) { return { id: o.id, kind: 'tab_focus', label: o.label, started_at: new Date(o.start).toISOString(), ended_at: new Date(end).toISOString(), attrs: o.attrs, }; } function close(end) { if (!cur) return; GM_deleteValue('open:' + TAB); if (end - cur.start >= MIN_DURATION) GM_setValue('ev:' + cur.id, toEvent(cur, end)); cur = null; } function tick() { const now = Date.now(); if (cur && now - cur.seen > GAP) close(cur.seen); // slept or frozen: don't count the gap const c = config(); const w = wanted(c, now); if (cur && (!w || w.key !== cur.key)) close(now); if (w && !cur) cur = { id: randomID(), ...w, start: now, seen: now, saved: 0 }; if (!cur) return; cur.seen = now; if (now - cur.saved >= CHECKPOINT) { // Lets another tab recover the interval if this one is killed. GM_setValue('open:' + TAB, { ...toEvent(cur, now), tab: TAB }); cur.saved = now; } } window.addEventListener('focus', tick); window.addEventListener('blur', tick); window.addEventListener('pageshow', tick); document.addEventListener('visibilitychange', tick); window.addEventListener('pagehide', () => close(Date.now())); setInterval(tick, TICK); // also catches SPA navigation and idle tick(); // ---- upload ---- // Turns intervals left open by tabs that were closed or crashed into events. function sweep(now) { for (const k of GM_listValues()) { if (!k.startsWith('open:') || k === 'open:' + TAB) continue; const o = GM_getValue(k); const end = o && Date.parse(o.ended_at); if (!o || now - end < STALE) continue; GM_deleteValue(k); const { tab, ...ev } = o; if (end - Date.parse(ev.started_at) >= MIN_DURATION) GM_setValue('ev:' + ev.id, ev); } } function takeLease(now) { const l = GM_getValue('lease', null); if (l && l.tab !== TAB && l.until > now) return false; GM_setValue('lease', { tab: TAB, until: now + LEASE }); return true; } function setStatus(ok, msg) { GM_setValue('status', { at: new Date().toISOString(), ok, msg }); } function upload(force) { const c = config(); const now = Date.now(); if (!ready(c) || (!force && !takeLease(now))) return; sweep(now); const keys = GM_listValues().filter((k) => k.startsWith('ev:')).slice(0, BATCH); if (!keys.length) return; const events = keys.map((k) => GM_getValue(k)); GM_xmlhttpRequest({ method: 'POST', url: c.url.replace(/\/+$/, '') + '/api/v1/browser/events', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + c.key }, data: JSON.stringify({ events }), timeout: 30e3, onload(r) { if (r.status === 200) { keys.forEach(GM_deleteValue); setStatus(true, r.responseText); return; } let msg = r.responseText; try { msg = JSON.parse(r.responseText).error || msg; } catch (_) { /* not JSON */ } // The server rejects the whole batch for one bad event; drop that one // so it can't block the queue forever. const bad = r.status === 422 && /^event (\d+):/.exec(msg); if (bad && keys[+bad[1]]) GM_deleteValue(keys[+bad[1]]); setStatus(false, `HTTP ${r.status}: ${msg}`); }, onerror: () => setStatus(false, 'network error'), ontimeout: () => setStatus(false, 'timeout'), }); } setTimeout(() => upload(false), 5e3 + Math.random() * 5e3); setInterval(() => upload(false), UPLOAD_EVERY); // ---- menu ---- function save(patch) { GM_setValue('config', { ...GM_getValue('config', {}), ...patch }); } GM_registerMenuCommand('Set server and API key', () => { const c = config(); const url = prompt('Tracker URL (e.g. https://www.adam-french.co.uk/tracker)', c.url); if (url === null) return; const key = prompt('API key (tracker apikey create --kind browser)', c.key); if (key === null) return; save({ url: url.trim(), key: key.trim() }); }); GM_registerMenuCommand('Toggle full URLs', () => { const v = !config().fullUrls; save({ fullUrls: v }); alert('Full URLs ' + (v ? 'on' : 'off')); }); GM_registerMenuCommand('Toggle page titles', () => { const v = !config().titles; save({ titles: v }); alert('Page titles ' + (v ? 'on' : 'off')); }); GM_registerMenuCommand('Ignored hosts…', () => { const v = prompt('Regexp of hostnames not to record (empty = none), e.g. bank|mail\\.google', config().ignore); if (v !== null) save({ ignore: v.trim() }); }); GM_registerMenuCommand('Idle timeout…', () => { const v = prompt('Minutes without input before a tab stops counting', config().idleMinutes); const n = Number(v); if (v !== null && n > 0) save({ idleMinutes: n }); }); GM_registerMenuCommand('Status / upload now', () => { const c = config(); const queued = GM_listValues().filter((k) => k.startsWith('ev:')).length; const s = GM_getValue('status', null); upload(true); alert([ ready(c) ? 'Server: ' + c.url : 'Not configured: set the server and API key first.', 'Queued events: ' + queued, 'Recording here: ' + (cur ? cur.label : 'no'), s ? `Last upload ${s.at}: ${s.ok ? 'ok' : 'failed'} — ${s.msg}` : 'No uploads yet', ].join('\n')); }); })();