662 lines
40 KiB
JavaScript
662 lines
40 KiB
JavaScript
// Service worker : interroge TIS 1x/minute avec TA session Chrome, calcule les couleurs, notifie.
|
||
importScripts('core.js'); // logique commune (couleurs, alertes, tendances, DEFAULT_PREFS)
|
||
|
||
const API = 'https://tis-prod.rne.eu/tis2020api/api/trainsearches';
|
||
const TIS_URL = 'https://tis-prod.rne.eu/';
|
||
const POLL_MIN = 1; // 1 requête légère par minute pour toute la liste
|
||
const DETAIL_EVERY_MS = 3 * 60000; // détail d'itinéraire (lourd) : toutes les 3 min, trains en circulation seulement
|
||
const MIN_FORCE_GAP_MS = 10000; // anti-flood : un forçage toutes les 10 s maximum
|
||
const DEFAULT_CFG = { yellowFromMin: 5, redFromMin: 15 };
|
||
const DEBUG_MAX = 300; // entrées gardées dans le journal de debug
|
||
const ALERTS_KEEP = 200; // historique des alertes : les 200 dernières (une nuit de poste)
|
||
|
||
let running = false;
|
||
|
||
// ---------- Journal de debug + statistiques : regroupés, une seule écriture par cycle ----------
|
||
const dbgBuf = [];
|
||
const pendingStats = { set: {}, inc: {} };
|
||
const dbg = (l, m, d) => { dbgBuf.push({ t: Date.now(), l, m, d }); };
|
||
const stat = (set, inc) => {
|
||
Object.assign(pendingStats.set, set || {});
|
||
for (const [k, v] of Object.entries(inc || {})) pendingStats.inc[k] = (pendingStats.inc[k] || 0) + v;
|
||
};
|
||
async function flushDbg() {
|
||
const hasStats = Object.keys(pendingStats.set).length || Object.keys(pendingStats.inc).length;
|
||
if (!dbgBuf.length && !hasStats) return;
|
||
try {
|
||
const s = await chrome.storage.local.get(['debug', 'stats']);
|
||
const out = {};
|
||
if (dbgBuf.length) out.debug = [...(s.debug || []), ...dbgBuf.splice(0)].slice(-DEBUG_MAX);
|
||
if (hasStats) {
|
||
const st = { ...(s.stats || {}), ...pendingStats.set, version: chrome.runtime.getManifest().version };
|
||
for (const [k, v] of Object.entries(pendingStats.inc)) st[k] = (st[k] || 0) + v;
|
||
pendingStats.set = {}; pendingStats.inc = {};
|
||
out.stats = st;
|
||
}
|
||
await chrome.storage.local.set(out);
|
||
} catch (e) { dbgBuf.length = 0; }
|
||
}
|
||
|
||
const load = async () => {
|
||
const s = await chrome.storage.local.get(['trains', 'cfg', 'data', 'details', 'detailTried', 'locNames', 'prev', 'lastRun', 'alerts', 'prefs',
|
||
'hidden', 'tisFilter', 'tisFilters', 'lists', 'extras', 'pins', 'compos']);
|
||
const prefs = { ...DEFAULT_PREFS, ...(s.prefs || {}), ev: { ...DEFAULT_PREFS.ev, ...((s.prefs || {}).ev || {}) } };
|
||
const lists = s.lists || [], tisFilters = s.tisFilters || [];
|
||
const active = resolveList(prefs, { lists, tisFilters, tisFilter: s.tisFilter });
|
||
// Numéros « en plus » : propres à chaque liste, jamais filtrés par entreprise.
|
||
// (versions précédentes : une seule liste « trains » → reprise dans la liste active)
|
||
const extras = s.extras || (s.trains && s.trains.length ? { [active.id]: s.trains } : {});
|
||
return { cfg: { ...DEFAULT_CFG, ...(s.cfg || {}) }, data: s.data || null, prefs, lists, tisFilters, active, extras,
|
||
trains: extras[active.id] || [], pins: s.pins || {}, compos: s.compos || {},
|
||
details: s.details || {}, detailTried: s.detailTried || {}, locNames: s.locNames || {}, prev: s.prev || {},
|
||
lastRun: s.lastRun || 0, alerts: s.alerts || [], hidden: s.hidden || {},
|
||
tisFilter: active.definition ? { name: active.name, definition: active.definition } : null,
|
||
fleetMode: !!active.definition };
|
||
};
|
||
|
||
// « 42920, 42921@27/10, 40146@27/10/2026 » → numéros + jours choisis (AAAA-MM-JJ).
|
||
function parseNumbers(text) {
|
||
const nums = [], pins = {};
|
||
const y = new Date().getFullYear();
|
||
for (const tok of String(text || '').split(/[\s,;]+/)) {
|
||
const m = tok.match(/^(\d{1,10})(?:@(\d{1,2})[\/.-](\d{1,2})(?:[\/.-](\d{2,4}))?)?$/);
|
||
if (!m) continue;
|
||
if (!nums.includes(m[1])) nums.push(m[1]);
|
||
if (m[2]) {
|
||
const yy = m[4] ? (m[4].length === 2 ? 2000 + Number(m[4]) : Number(m[4])) : y;
|
||
pins[m[1]] = `${yy}-${String(m[3]).padStart(2, '0')}-${String(m[2]).padStart(2, '0')}`;
|
||
}
|
||
}
|
||
return { nums: nums.slice(0, 100), pins };
|
||
}
|
||
|
||
// Sonnerie : un document caché (offscreen) joue le son, même si la page de suivi est fermée.
|
||
async function playSound(kind) {
|
||
try {
|
||
const open = await chrome.runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'] });
|
||
if (!open.length) {
|
||
await chrome.offscreen.createDocument({ url: 'offscreen.html', reasons: ['AUDIO_PLAYBACK'], justification: 'Alertes sonores de suivi des trains' });
|
||
dbg('info', 'document audio créé');
|
||
}
|
||
await chrome.runtime.sendMessage({ target: 'offscreen', type: 'play', kind });
|
||
dbg('info', `son joué : ${kind}`);
|
||
} catch (e) { dbg('warn', 'son impossible : ' + e.message); }
|
||
}
|
||
|
||
// Notifications Windows / Chrome (silencieuses : le son est géré par TTA) + son de l'alerte la plus importante.
|
||
async function emit(alerts, prefs) {
|
||
if (prefs.desktop) for (const a of alerts) {
|
||
const opts = { type: 'basic', iconUrl: 'icon128.png', title: a.title, message: a.body || '', priority: 2, silent: true };
|
||
// une notification « session » ouvre directement la fenêtre de connexion quand on clique dessus
|
||
if (a.kind === 'session') chrome.notifications.create('tta-login-' + Date.now(), { ...opts, requireInteraction: true });
|
||
else chrome.notifications.create(opts);
|
||
}
|
||
const kinds = alerts.map(a => a.kind);
|
||
const loudest = KIND_PRIORITY.find(k => kinds.includes(k));
|
||
if (loudest && prefs.sound) await playSound(loudest);
|
||
else if (loudest) dbg('info', `son coupé dans les réglages (alerte ${loudest})`);
|
||
}
|
||
|
||
// Badge sur l'icône : nombre de trains en rouge (sinon en jaune), « ! » si TIS est injoignable.
|
||
function updateBadge(rows, error) {
|
||
const red = rows.filter(t => t.color === 'red').length, yellow = rows.filter(t => t.color === 'yellow').length;
|
||
let text = '', color = '#2fb36b';
|
||
if (error) { text = '!'; color = '#6b7685'; }
|
||
else if (red) { text = String(red); color = '#ef4444'; }
|
||
else if (yellow) { text = String(yellow); color = '#e5b020'; }
|
||
chrome.action.setBadgeText({ text });
|
||
chrome.action.setBadgeBackgroundColor({ color });
|
||
chrome.action.setTitle({ title: error ? `TTA – ${error}` : `TTA – ${red} en retard important, ${yellow} en retard, ${rows.length} suivi(s)` });
|
||
}
|
||
|
||
const searchBody = (nums, details, onlyRunning) => ({
|
||
withSectionsAndDetails: details, withInterruptionInfo: true, withInterruptionInfoInHeaderOnly: false,
|
||
filter: { onlyRunning, maxNumberOfResults: 200, trainNumbers: nums },
|
||
});
|
||
|
||
// 1) appel direct avec la session Chrome (permission d'hôte) ; 2) sinon via un onglet TIS ouvert.
|
||
async function callTis(body, label) {
|
||
const t0 = Date.now();
|
||
const kb = r => Math.round(JSON.stringify(r).length / 1024);
|
||
try {
|
||
const r = await fetch(API, {
|
||
method: 'POST', credentials: 'include',
|
||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-PAGE-URL': '/search#multiple' },
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (r.ok) {
|
||
const j = await r.json().catch(() => null);
|
||
if (j && j.data && j.data.result) {
|
||
dbg('info', `TIS ${label} : OK direct (HTTP ${r.status})`, { ms: Date.now() - t0, ko: kb(j.data.result), trains: (j.data.result.trains || []).length });
|
||
return { ok: true, result: j.data.result, route: 'direct', status: r.status, ms: Date.now() - t0 };
|
||
}
|
||
dbg('warn', `TIS ${label} : réponse directe non exploitable (probablement page de connexion)`, { ms: Date.now() - t0 });
|
||
} else if (r.status !== 401 && r.status !== 403) {
|
||
dbg('error', `TIS ${label} : HTTP ${r.status}`);
|
||
return { ok: false, error: `TIS a répondu HTTP ${r.status}`, status: r.status, route: 'direct', ms: Date.now() - t0 };
|
||
} else dbg('warn', `TIS ${label} : direct refusé (HTTP ${r.status}), essai via onglet TIS`);
|
||
} catch (e) { dbg('warn', `TIS ${label} : appel direct impossible (${e.message}), essai via onglet TIS`); }
|
||
|
||
const tabs = await chrome.tabs.query({ url: TIS_URL + '*' });
|
||
if (!tabs.length) {
|
||
dbg('error', `TIS ${label} : aucun onglet TIS ouvert pour le plan B`);
|
||
return { ok: false, auth: true, error: 'Pas connecté à TIS : clique sur « Se connecter à TIS ».', status: 401, route: 'aucune', ms: Date.now() - t0 };
|
||
}
|
||
try {
|
||
const [res] = await chrome.scripting.executeScript({
|
||
target: { tabId: tabs[0].id },
|
||
func: async (b) => {
|
||
const r = await fetch('/tis2020api/api/trainsearches', {
|
||
method: 'POST', credentials: 'include',
|
||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-PAGE-URL': '/search#multiple' },
|
||
body: JSON.stringify(b),
|
||
});
|
||
return { status: r.status, json: r.ok ? await r.json() : null };
|
||
},
|
||
args: [body],
|
||
});
|
||
const out = res && res.result;
|
||
if (out && out.json && out.json.data) {
|
||
dbg('info', `TIS ${label} : OK via onglet TIS (HTTP ${out.status})`, { ms: Date.now() - t0, ko: kb(out.json.data.result), trains: (out.json.data.result.trains || []).length });
|
||
return { ok: true, result: out.json.data.result, route: 'onglet', status: out.status, ms: Date.now() - t0 };
|
||
}
|
||
if (out && (out.status === 401 || out.status === 403)) {
|
||
dbg('error', `TIS ${label} : session expirée (HTTP ${out.status})`);
|
||
return { ok: false, auth: true, error: 'Session TIS expirée : clique sur « Se connecter à TIS ».', status: out.status, route: 'onglet', ms: Date.now() - t0 };
|
||
}
|
||
dbg('error', `TIS ${label} : HTTP ${out ? out.status : '?'} via onglet`);
|
||
return { ok: false, error: `TIS a répondu HTTP ${out ? out.status : '?'}`, status: out && out.status, route: 'onglet', ms: Date.now() - t0 };
|
||
} catch (e) {
|
||
dbg('error', `TIS ${label} : échec via onglet (${e.message})`);
|
||
return { ok: false, error: 'Impossible d\'interroger TIS : ' + e.message, route: 'onglet', ms: Date.now() - t0 };
|
||
}
|
||
}
|
||
|
||
const DETAIL_BATCH = 4; // détail d'itinéraire : au plus 4 trains par cycle (les autres aux cycles suivants)
|
||
const COMPO_EVERY_MS = 15 * 60000; // composition (véhicules, longueur, poids) : change rarement → toutes les 15 min par train
|
||
const COMPO_BATCH = 4; // … au plus 4 trains par cycle
|
||
const pad2 = n => String(n).padStart(2, '0');
|
||
// Format d'heure attendu par TIS : heure locale « yyyy-MM-ddTHH:mm:ss ».
|
||
const tisTime = ms => { const d = new Date(ms); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`; };
|
||
// Filtre TIS enregistré, nettoyé des réglages propres à l'écran de TIS (sinon TIS répond 400).
|
||
function cleanDef(def) {
|
||
const d = { ...(def || {}) };
|
||
for (const k of ['timeframe', 'timeFramePast', 'timeFrameFuture', 'timeFrameBaseTime', 'timeFrameBaseTimeType', 'cttLine', 'realLine',
|
||
'splitLocations', 'mobileTimeFrame', 'departureTimeFrom', 'departureTimeTo', 'trainNumbers']) delete d[k];
|
||
return d;
|
||
}
|
||
const filterBody = filter => ({ withSectionsAndDetails: false, withInterruptionInfo: true, withInterruptionInfoInHeaderOnly: false, filter });
|
||
|
||
// Trains à afficher. Mode « filtre TIS » : trains du filtre en circulation + départs des X prochaines minutes
|
||
// (et ceux pas encore partis jusqu'à Y min après l'heure prévue) ; plus les numéros saisis à la main.
|
||
// Renvoie l'échec du premier appel TIS, ou { ok, fleet:[trains], extra:[trains]|null, all:[trains] }.
|
||
async function gather(s) {
|
||
const out = { ok: true, fleet: [], extra: null, all: [] };
|
||
const absorb = res => { for (const l of res.locations || []) s.locNames[l.id] = l.name; const tr = res.trains || []; out.all.push(...tr); return tr; };
|
||
let first = null;
|
||
if (s.fleetMode) {
|
||
const def = cleanDef(s.tisFilter.definition), name = s.tisFilter.name;
|
||
const r1 = await callTis(filterBody({ ...def, onlyRunning: true, maxNumberOfResults: 1000 }), `filtre « ${name} » en circulation`);
|
||
if (!r1.ok) return r1;
|
||
first = r1;
|
||
const now = Date.now();
|
||
const r2 = await callTis(filterBody({ ...def, onlyRunning: false, maxNumberOfResults: 500,
|
||
departureTimeFrom: tisTime(now - s.prefs.lateLookbackMin * 60000), departureTimeTo: tisTime(now + s.prefs.upcomingMin * 60000) }), `filtre « ${name} » départs`);
|
||
stat({}, { requests: 1 });
|
||
const runningT = absorb(r1.result);
|
||
// des départs, on ne garde que les trains PAS ENCORE partis (les autres sont déjà dans « en circulation »)
|
||
const upcomingT = r2.ok ? absorb(r2.result).filter(t => { const h = t.header; return !h.running && !(h.origin || {}).actualTime && !(h.destination || {}).actualTime; }) : [];
|
||
if (!r2.ok) dbg('warn', 'départs à venir indisponibles ce cycle');
|
||
out.fleet = [...runningT, ...upcomingT].filter(t => !t.header.archive);
|
||
dbg('info', `filtre « ${name} » : ${runningT.length} en circulation, ${upcomingT.length} pas encore parti(s) (départ ≤ ${s.prefs.upcomingMin} min ou en retard)`);
|
||
}
|
||
if (s.trains.length) {
|
||
const r = await callTis(searchBody(s.trains, false, false), s.fleetMode ? 'trains en plus' : 'liste');
|
||
if (!r.ok && !first) return r;
|
||
if (first) stat({}, { requests: 1 }); else first = r;
|
||
if (r.ok) out.extra = absorb(r.result); else dbg('warn', 'trains en plus indisponibles ce cycle');
|
||
}
|
||
return { ...out, route: first.route, status: first.status, ms: first.ms };
|
||
}
|
||
|
||
// Composition d'un train (GET train-compositions?trainId=…), réduite à l'essentiel.
|
||
async function getComposition(id, archive) {
|
||
try {
|
||
const r = await fetch(`https://tis-prod.rne.eu/tis2020api/api/train-compositions?trainId=${id}`, {
|
||
credentials: 'include', headers: { Accept: 'application/json', ...(archive ? { Archive: 'true' } : {}) },
|
||
});
|
||
if (!r.ok) { dbg('warn', `composition ${id} : HTTP ${r.status}`); return { ok: false }; }
|
||
const j = await r.json().catch(() => null);
|
||
return { ok: true, list: compactCompositions(j && j.data) };
|
||
} catch (e) { dbg('warn', `composition ${id} : ${e.message}`); return { ok: false }; }
|
||
}
|
||
|
||
async function poll(reason = 'alarme') {
|
||
if (running) { dbg('info', `cycle ignoré (${reason}) : un cycle est déjà en cours`); await flushDbg(); return; }
|
||
running = true;
|
||
const t0 = Date.now();
|
||
try {
|
||
const s = await load();
|
||
dbg('info', `── cycle (${reason}) : liste « ${s.active.name} »${s.fleetMode ? ` (${(s.tisFilter.definition.ruCodes || []).length || '?'} entreprise(s))` : ''}${s.trains.length ? ` + ${s.trains.length} numéro(s) en plus` : ''}`);
|
||
if (!s.trains.length && !s.fleetMode) {
|
||
await chrome.storage.local.set({ lastRun: Date.now(), data: { updatedAt: new Date().toISOString(), error: null, rows: [] } });
|
||
updateBadge([], null);
|
||
dbg('info', 'liste vide : rien à interroger');
|
||
return;
|
||
}
|
||
|
||
const r = await gather(s);
|
||
stat({ lastRoute: r.route, lastStatus: r.status ?? null, lastMs: r.ms }, { requests: 1 });
|
||
if (!r.ok) {
|
||
const prevRows = s.data ? s.data.rows : [];
|
||
// Session expirée (une fois par épisode) : reconnexion automatique silencieuse si activée,
|
||
// sinon alerte « connexion requise » tout de suite.
|
||
const stamped = [];
|
||
if (r.auth) await chrome.storage.local.set({ session: { ok: false, checkedAt: Date.now() } });
|
||
if (r.auth && !(s.data && s.data.auth)) {
|
||
if (s.prefs.autoLogin) { dbg('info', 'session expirée : tentative de reconnexion automatique'); await startLogin(true); }
|
||
else if (s.prefs.ev.session) stamped.push(sessionAlert());
|
||
}
|
||
if (stamped.length) { dbg('info', 'ALERTE session : connexion TIS requise'); await emit(stamped, s.prefs); }
|
||
await chrome.storage.local.set({
|
||
lastRun: Date.now(),
|
||
data: { updatedAt: s.data ? s.data.updatedAt : null, checkedAt: new Date().toISOString(), error: r.error, auth: !!r.auth, rows: prevRows },
|
||
...(stamped.length ? { alerts: [...stamped, ...s.alerts].slice(0, ALERTS_KEEP) } : {}),
|
||
});
|
||
updateBadge(prevRows, r.error);
|
||
stat({ lastError: r.error, lastErrorAt: new Date().toISOString() }, { errors: 1 });
|
||
return;
|
||
}
|
||
|
||
const mkCtx = () => ({ cfg: s.cfg, stuckAfterMin: s.prefs.overdueYellowMin, locName: id => s.locNames[id] || (id ? `#${id}` : '?'), details: s.details, compos: s.compos, now: Date.now() });
|
||
// Numéros saisis introuvables : on essaie le numéro de parité opposée (42920 ↔ 42921),
|
||
// car le numéro change souvent en passant une frontière.
|
||
let twinTrains = null;
|
||
const lost = buildRows([], r.extra, s.trains, mkCtx(), s.pins).filter(t => t.phase === 'notfound' && !t.pinned).map(t => t.query);
|
||
if (lost.length) {
|
||
const rt = await callTis(searchBody(lost.map(twinNumber), false, false), 'parité');
|
||
stat({}, { requests: 1 });
|
||
if (rt.ok) {
|
||
for (const l of rt.result.locations || []) s.locNames[l.id] = l.name;
|
||
twinTrains = rt.result.trains || [];
|
||
r.all.push(...twinTrains);
|
||
}
|
||
}
|
||
const withTwins = row => {
|
||
if (row.src !== 'list' || row.phase !== 'notfound' || row.pinned) return row;
|
||
const twin = twinNumber(row.query);
|
||
const alt = twinTrains && pickPerNumber(twinTrains, [twin], mkCtx())[0];
|
||
if (alt && alt.phase !== 'notfound') {
|
||
return { ...alt, src: 'list', query: row.query, parityFrom: row.query,
|
||
reason: `Trouvé sous le n° ${twin} : le numéro change de parité en route (souvent à la frontière)` };
|
||
}
|
||
return { ...row, twin, reason: `Introuvable dans TIS, ni sous le n° ${row.query} ni sous le n° ${twin} (parité). Vérifie le numéro ou choisis un autre jour.` };
|
||
};
|
||
const build = () => buildRows(r.fleet, r.extra, s.trains, mkCtx(), s.pins).map(withTwins).filter(t => !(t.id && s.hidden[t.id] > Date.now()));
|
||
|
||
// Détail d'itinéraire (prochain point) : trains en circulation dont le cache est périmé, au plus
|
||
// DETAIL_BATCH par cycle (les plus anciens d'abord), et pas plus d'une tentative / 3 min par numéro.
|
||
let rows = build();
|
||
const fresh = v => v && Date.now() - (typeof v === 'number' ? v : Date.parse(v)) < DETAIL_EVERY_MS;
|
||
const need = [...new Set(rows.filter(t => t.phase === 'running' && !fresh(t.detailAt) && !fresh(s.detailTried[t.otn]))
|
||
.sort((a, b) => (Date.parse(a.detailAt || 0) || 0) - (Date.parse(b.detailAt || 0) || 0)).map(t => t.otn))].slice(0, DETAIL_BATCH);
|
||
if (need.length) {
|
||
dbg('info', `détail d'itinéraire demandé pour : ${need.join(', ')}`);
|
||
for (const n of need) s.detailTried[n] = Date.now();
|
||
const d = await callTis(searchBody(need, true, true), 'détail');
|
||
stat({}, { requests: 1, detailRequests: 1 });
|
||
if (d.ok) {
|
||
let got = 0;
|
||
for (const l of d.result.locations || []) s.locNames[l.id] = l.name;
|
||
for (const t of d.result.trains || []) {
|
||
const pts = compactDetails(t);
|
||
if (pts) { s.details[t.header.id] = { at: new Date().toISOString(), points: pts, passed: passedLocations(t), causes: compactCauses(t) }; got++; }
|
||
}
|
||
dbg(got ? 'info' : 'warn', `détail reçu pour ${got} train(s) sur ${need.length} demandé(s)${got ? '' : ' — nouvel essai dans 3 min'}`);
|
||
rows = build();
|
||
}
|
||
}
|
||
// Composition (onglet « Train composition » de TIS) : au plus COMPO_BATCH trains par cycle, toutes les 15 min.
|
||
const compoNeed = rows.filter(t => t.id && ['running', 'waiting', 'arrived'].includes(t.phase)
|
||
&& !(s.compos[t.id] && Date.now() - s.compos[t.id].at < COMPO_EVERY_MS))
|
||
.sort((a, b) => (s.compos[a.id] ? s.compos[a.id].at : 0) - (s.compos[b.id] ? s.compos[b.id].at : 0)).slice(0, COMPO_BATCH);
|
||
if (compoNeed.length) {
|
||
let got = 0;
|
||
for (const t of compoNeed) {
|
||
const c = await getComposition(t.id, t.archive);
|
||
stat({}, { requests: 1, compoRequests: 1 });
|
||
if (c.ok) { s.compos[t.id] = { at: Date.now(), list: c.list }; if (c.list.length) got++; }
|
||
else s.compos[t.id] = { at: Date.now() - COMPO_EVERY_MS + 3 * 60000, list: (s.compos[t.id] || {}).list || [] }; // échec : nouvel essai dans 3 min
|
||
}
|
||
dbg('info', `composition demandée pour ${compoNeed.length} train(s) : ${got} disponible(s)`);
|
||
rows = build();
|
||
}
|
||
// Ménage des caches : seulement ce qui sert encore aux trains affichés.
|
||
const keep = new Set(rows.map(t => String(t.id))), shownOtns = new Set(rows.map(t => t.otn));
|
||
for (const id of Object.keys(s.compos)) if (!keep.has(id)) delete s.compos[id];
|
||
for (const id of Object.keys(s.details)) if (!keep.has(id)) delete s.details[id];
|
||
for (const n of Object.keys(s.detailTried)) if (!shownOtns.has(n)) delete s.detailTried[n];
|
||
for (const id of Object.keys(s.hidden)) if (s.hidden[id] < Date.now()) delete s.hidden[id];
|
||
const usedLocs = usedLocations(r.all, s.details);
|
||
for (const id of Object.keys(s.locNames)) if (!usedLocs.has(id)) delete s.locNames[id];
|
||
|
||
applyTrends(rows, s.prev, Date.now());
|
||
const count = c => rows.filter(t => t.color === c).length;
|
||
dbg('info', `résultat : ${rows.length} ligne(s) — rouge ${count('red')}, jaune ${count('yellow')}, vert ${count('green')}, bleu ${count('blue')}, gris ${count('grey')}`);
|
||
for (const t of rows.filter(t => t.phase === 'notfound')) dbg('warn', `train ${t.otn} : non trouvé dans TIS`);
|
||
|
||
const { alerts, next } = diffAlerts(rows, s.prev, s.prefs);
|
||
const stamped = alerts.map(a => ({ ...a, at: new Date().toISOString() }));
|
||
for (const a of stamped) dbg('info', `ALERTE ${a.kind} : ${a.title}`, { corps: a.body });
|
||
if (s.data && s.data.auth) dbg('info', 'session TIS rétablie');
|
||
await emit(stamped, s.prefs);
|
||
|
||
await chrome.storage.local.set({
|
||
lastRun: Date.now(),
|
||
data: { updatedAt: new Date().toISOString(), error: null, rows, hiddenCount: Object.keys(s.hidden).length },
|
||
details: s.details, detailTried: s.detailTried, locNames: s.locNames, prev: next, hidden: s.hidden, compos: s.compos,
|
||
...(stamped.length ? { alerts: [...stamped, ...s.alerts].slice(0, ALERTS_KEEP) } : {}),
|
||
});
|
||
updateBadge(rows, null);
|
||
const sess = (await chrome.storage.local.get('session')).session;
|
||
if (!sess || !sess.ok) await checkSession(); // récupère le nom affiché après une (re)connexion
|
||
stat({ lastOkAt: new Date().toISOString(), lastCycleMs: Date.now() - t0 }, { okCycles: 1 });
|
||
} catch (e) {
|
||
dbg('error', 'ERREUR inattendue dans le cycle : ' + (e && e.stack || e));
|
||
stat({ lastError: String(e && e.message || e), lastErrorAt: new Date().toISOString() }, { errors: 1 });
|
||
} finally {
|
||
running = false;
|
||
await flushDbg();
|
||
}
|
||
}
|
||
|
||
function schedule() { chrome.alarms.create('poll', { periodInMinutes: POLL_MIN, delayInMinutes: 0.1 }); }
|
||
chrome.runtime.onInstalled.addListener(details => {
|
||
schedule(); dbg('info', `extension installée / mise à jour (v${chrome.runtime.getManifest().version})`); flushDbg();
|
||
if (details.reason === 'install') openDashboard(); // première installation : on ouvre TTA directement
|
||
});
|
||
chrome.runtime.onStartup.addListener(() => { schedule(); dbg('info', 'Chrome démarré'); flushDbg(); });
|
||
chrome.alarms.onAlarm.addListener(a => { if (a.name === 'poll') poll('alarme'); });
|
||
|
||
// Ouvre (ou ramène au premier plan) la page de suivi : icône de l'extension ou clic sur une notification.
|
||
async function openDashboard() {
|
||
const url = chrome.runtime.getURL('dashboard.html');
|
||
const tabs = await chrome.tabs.query({ url });
|
||
if (tabs.length) { await chrome.tabs.update(tabs[0].id, { active: true }); await chrome.windows.update(tabs[0].windowId, { focused: true }); }
|
||
else await chrome.tabs.create({ url });
|
||
}
|
||
chrome.action.onClicked.addListener(openDashboard);
|
||
chrome.notifications.onClicked.addListener(id => {
|
||
chrome.notifications.clear(id);
|
||
if (id.startsWith('tta-login')) startLogin(false); else openDashboard();
|
||
});
|
||
|
||
// ---------- Connexion TIS intégrée ----------
|
||
// TIS se connecte via Microsoft (login.microsoftonline.com) : impossible à afficher dans la page de l'extension.
|
||
// On ouvre donc une petite fenêtre TIS ; l'utilisateur s'y connecte lui-même (l'extension ne voit jamais
|
||
// le mot de passe). Dès que TIS répond « connecté », la fenêtre se ferme et le suivi reprend.
|
||
const SELF_URL = 'https://tis-prod.rne.eu/tis2020api/api/accounts/self';
|
||
const LOGIN_URL = 'https://tis-prod.rne.eu/search';
|
||
const SILENT_TIMEOUT_MIN = 1; // reconnexion silencieuse : abandon après 1 min
|
||
const VISIBLE_TIMEOUT_MIN = 15; // fenêtre visible : on arrête de la surveiller après 15 min
|
||
|
||
function sessionAlert() {
|
||
return { kind: 'session', level: 'red', title: 'TTA : connexion TIS requise', body: 'Clique ici pour te reconnecter à TIS et reprendre le suivi.', at: new Date().toISOString() };
|
||
}
|
||
|
||
// true = connecté, false = non connecté, null = indéterminé (réseau…). Ne garde que le nom affiché.
|
||
async function checkSession() {
|
||
try {
|
||
const r = await fetch(SELF_URL, { credentials: 'include', headers: { Accept: 'application/json' } });
|
||
if (r.ok) {
|
||
const j = await r.json().catch(() => null);
|
||
const u = (j && (j.data || j)) || {};
|
||
const name = [u.firstName || u.firstname, u.lastName || u.lastname].filter(Boolean).join(' ') || u.displayName || u.name || '';
|
||
await chrome.storage.local.set({ session: { ok: true, name: String(name).slice(0, 60), checkedAt: Date.now() } });
|
||
return true;
|
||
}
|
||
if (r.status === 401 || r.status === 403) { await chrome.storage.local.set({ session: { ok: false, checkedAt: Date.now() } }); return false; }
|
||
} catch (e) { dbg('warn', 'vérification de session impossible : ' + e.message); }
|
||
return null;
|
||
}
|
||
|
||
async function startLogin(silent) {
|
||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||
if (cur) {
|
||
try {
|
||
await chrome.windows.get(cur.id);
|
||
if (!silent) { // fenêtre déjà ouverte (même réduite) : on la montre
|
||
await chrome.windows.update(cur.id, { state: 'normal', focused: true });
|
||
await chrome.storage.local.set({ loginWin: { ...cur, silent: false } });
|
||
chrome.alarms.create('loginTimeout', { delayInMinutes: VISIBLE_TIMEOUT_MIN });
|
||
}
|
||
return;
|
||
} catch (e) { /* fenêtre fermée entre-temps */ }
|
||
}
|
||
const w = await chrome.windows.create(silent
|
||
? { url: LOGIN_URL, type: 'normal', state: 'minimized', focused: false }
|
||
: { url: LOGIN_URL, type: 'popup', width: 520, height: 780, focused: true });
|
||
await chrome.storage.local.set({ loginWin: { id: w.id, silent: !!silent, at: Date.now() } });
|
||
chrome.alarms.create('loginTimeout', { delayInMinutes: silent ? SILENT_TIMEOUT_MIN : VISIBLE_TIMEOUT_MIN });
|
||
dbg('info', silent ? 'reconnexion automatique : fenêtre TIS réduite ouverte' : 'fenêtre de connexion TIS ouverte');
|
||
await flushDbg();
|
||
}
|
||
|
||
async function finishLogin(cur) {
|
||
await chrome.storage.local.remove('loginWin');
|
||
chrome.alarms.clear('loginTimeout');
|
||
try { await chrome.windows.remove(cur.id); } catch (e) { /* déjà fermée */ }
|
||
dbg('info', cur.silent ? 'reconnexion automatique réussie' : 'connecté à TIS');
|
||
if (!cur.silent) chrome.notifications.create({ type: 'basic', iconUrl: 'icon128.png', title: 'TTA : connecté à TIS', message: 'Le suivi des trains reprend.', priority: 0, silent: true });
|
||
await poll('connexion');
|
||
}
|
||
|
||
// Chaque page chargée dans la fenêtre de connexion : si on est revenu sur TIS, on vérifie la session.
|
||
// Après Microsoft, TIS revient sur sa page d'accueil puis échange le code en arrière-plan : on vérifie
|
||
// plusieurs fois sur quelques secondes (la page change d'adresse sans forcément se « recharger »).
|
||
let probing = false;
|
||
chrome.tabs.onUpdated.addListener(async (_tabId, info, tab) => {
|
||
if (!(info.status === 'complete' || info.url) || !tab.url || !tab.url.startsWith('https://tis-prod.rne.eu/') || tab.url.includes('/login')) return;
|
||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||
if (!cur || tab.windowId !== cur.id || probing) return;
|
||
probing = true;
|
||
try {
|
||
for (const wait of [0, 1500, 3000, 6000]) {
|
||
if (wait) await new Promise(r => setTimeout(r, wait));
|
||
if (!(await chrome.storage.local.get('loginWin')).loginWin) return; // déjà terminé ailleurs
|
||
if (await checkSession()) return finishLogin(cur);
|
||
}
|
||
} finally { probing = false; }
|
||
});
|
||
|
||
// L'utilisateur ferme la fenêtre lui-même : on regarde si la connexion a abouti.
|
||
chrome.windows.onRemoved.addListener(async id => {
|
||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||
if (!cur || cur.id !== id) return;
|
||
await chrome.storage.local.remove('loginWin');
|
||
chrome.alarms.clear('loginTimeout');
|
||
if (await checkSession()) { dbg('info', 'connecté à TIS (fenêtre fermée)'); await poll('connexion'); }
|
||
else { dbg('warn', 'fenêtre de connexion fermée sans connexion'); await flushDbg(); }
|
||
});
|
||
|
||
// Délai dépassé : la reconnexion silencieuse n'a pas suffi → on ferme et on demande à l'utilisateur.
|
||
chrome.alarms.onAlarm.addListener(async a => {
|
||
if (a.name !== 'loginTimeout') return;
|
||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||
if (!cur) return;
|
||
if (await checkSession()) return finishLogin(cur);
|
||
await chrome.storage.local.remove('loginWin');
|
||
if (cur.silent) {
|
||
try { await chrome.windows.remove(cur.id); } catch (e) { /* déjà fermée */ }
|
||
dbg('warn', 'reconnexion automatique impossible (Microsoft demande une action) : connexion manuelle requise');
|
||
const s = await load();
|
||
if (s.prefs.ev.session) {
|
||
const al = sessionAlert();
|
||
await emit([al], s.prefs);
|
||
await chrome.storage.local.set({ alerts: [al, ...s.alerts].slice(0, ALERTS_KEEP) });
|
||
}
|
||
}
|
||
await flushDbg();
|
||
});
|
||
|
||
// Messages de la page de suivi.
|
||
chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
|
||
if (msg && msg.target === 'offscreen') return; // destiné au document audio
|
||
(async () => {
|
||
const s = await load();
|
||
if (msg.type === 'force') {
|
||
const gap = Date.now() - s.lastRun;
|
||
if (gap < MIN_FORCE_GAP_MS) { dbg('info', `forçage refusé (anti-flood, ${Math.ceil((MIN_FORCE_GAP_MS - gap) / 1000)} s restantes)`); await flushDbg(); return reply({ ok: false, error: `Trop rapide : attends ${Math.ceil((MIN_FORCE_GAP_MS - gap) / 1000)} s` }); }
|
||
reply({ ok: true }); await poll('forçage'); return;
|
||
}
|
||
if (msg.type === 'setTrains') {
|
||
// Numéros « en plus » de la liste active (hors filtre), avec jour optionnel : 42920@27/10.
|
||
// On garde la mémoire des états (prev) : un train déjà suivi ne perd pas ses alertes en cours.
|
||
const { nums, pins } = parseNumbers(msg.numbers);
|
||
const extras = { ...s.extras, [s.active.id]: nums };
|
||
await chrome.storage.local.set({ extras, pins: { ...s.pins, ...pins }, trains: [] });
|
||
dbg('info', `numéros (${s.active.name}) : ${nums.join(', ') || '(aucun)'}${Object.keys(pins).length ? ' · jours : ' + Object.entries(pins).map(([k, v]) => k + '@' + v).join(', ') : ''}`);
|
||
reply({ ok: true, trains: nums }); await poll('liste modifiée'); return;
|
||
}
|
||
if (msg.type === 'remove') {
|
||
const otn = String(msg.otn);
|
||
const list = s.trains.filter(n => n !== otn);
|
||
const pins = { ...s.pins }; delete pins[otn];
|
||
const rows = s.data ? s.data.rows.filter(t => !(t.src === 'list' && (t.query || t.otn) === otn)) : [];
|
||
await chrome.storage.local.set({ extras: { ...s.extras, [s.active.id]: list }, pins, trains: [], data: { ...(s.data || {}), rows } });
|
||
updateBadge(rows, s.data && s.data.error);
|
||
dbg('info', `train ${otn} retiré de la liste`); await flushDbg();
|
||
return reply({ ok: true, trains: list });
|
||
}
|
||
// Jour choisi pour un numéro (date = AAAA-MM-JJ, ou null = automatique).
|
||
if (msg.type === 'pin') {
|
||
const pins = { ...s.pins };
|
||
if (msg.date) pins[String(msg.otn)] = msg.date; else delete pins[String(msg.otn)];
|
||
await chrome.storage.local.set({ pins });
|
||
dbg('info', `train ${msg.otn} : jour ${msg.date || 'automatique'}`);
|
||
reply({ ok: true }); await poll('jour modifié'); return;
|
||
}
|
||
// Suivre un train vu dans un filtre à une autre date : il passe dans les numéros en plus, avec ce jour.
|
||
if (msg.type === 'track') {
|
||
const otn = String(msg.otn), list = s.trains.includes(otn) ? s.trains : [...s.trains, otn];
|
||
await chrome.storage.local.set({ extras: { ...s.extras, [s.active.id]: list }, pins: msg.date ? { ...s.pins, [otn]: msg.date } : s.pins });
|
||
reply({ ok: true }); await poll('train ajouté'); return;
|
||
}
|
||
// ---------- Listes ----------
|
||
if (msg.type === 'setList') {
|
||
const prefs = { ...s.prefs, activeList: String(msg.id), sourceChosen: true };
|
||
if (String(msg.id).startsWith('tis-')) {
|
||
const f = s.tisFilters.find(x => 'tis-' + x.id === String(msg.id));
|
||
if (!f) return reply({ ok: false, error: 'Filtre TIS introuvable' });
|
||
await chrome.storage.local.set({ tisFilter: { id: f.id, name: f.name, definition: f.definition } });
|
||
}
|
||
await chrome.storage.local.set({ prefs });
|
||
dbg('info', `liste active : ${resolveList(prefs, { lists: s.lists, tisFilters: s.tisFilters }).name}`);
|
||
reply({ ok: true }); await poll('liste changée'); return;
|
||
}
|
||
if (msg.type === 'saveList') {
|
||
const l = msg.list || {};
|
||
const name = String(l.name || '').trim().slice(0, 40);
|
||
if (!name) return reply({ ok: false, error: 'Donne un nom à la liste' });
|
||
const ruCodes = [...new Set((l.ruCodes || []).map(String).filter(Boolean))].slice(0, 80);
|
||
const { nums, pins } = parseNumbers(l.trains || '');
|
||
const id = l.id && !String(l.id).startsWith('preset-') ? String(l.id) : 'list-' + Date.now();
|
||
const lists = [...s.lists.filter(x => x.id !== id), { id, name, ruCodes }];
|
||
await chrome.storage.local.set({ lists, extras: { ...s.extras, [id]: nums }, pins: { ...s.pins, ...pins } });
|
||
dbg('info', `liste « ${name} » enregistrée (${ruCodes.length} entreprise(s), ${nums.length} numéro(s))`);
|
||
reply({ ok: true, id });
|
||
if (s.active.id === id) await poll('liste modifiée'); else await flushDbg();
|
||
return;
|
||
}
|
||
if (msg.type === 'deleteList') {
|
||
const id = String(msg.id);
|
||
if (id.startsWith('preset-')) return reply({ ok: false, error: 'Les listes intégrées ne peuvent pas être supprimées' });
|
||
const extras = { ...s.extras }; delete extras[id];
|
||
const prefs = s.active.id === id ? { ...s.prefs, activeList: 'preset-sibelit' } : s.prefs;
|
||
await chrome.storage.local.set({ lists: s.lists.filter(x => x.id !== id), extras, prefs });
|
||
dbg('info', `liste supprimée`);
|
||
reply({ ok: true }); if (s.active.id === id) await poll('liste supprimée'); else await flushDbg();
|
||
return;
|
||
}
|
||
// Entreprises ferroviaires de TIS (pour composer une liste) : chargées une fois, gardées 7 jours.
|
||
// Horaire complet d'un train (GET trains/<id>), pour l'impression « de tel point à tel point ».
|
||
if (msg.type === 'timetable') {
|
||
try {
|
||
const r = await fetch(`https://tis-prod.rne.eu/tis2020api/api/trains/${msg.id}`, {
|
||
credentials: 'include', headers: { Accept: 'application/json', 'With-polylines': 'false', ...(msg.archive ? { Archive: 'true' } : {}) },
|
||
});
|
||
if (!r.ok) { dbg('warn', `horaire ${msg.id} : HTTP ${r.status}`); await flushDbg(); return reply({ ok: false, error: `TIS a répondu HTTP ${r.status}` }); }
|
||
const data = ((await r.json()) || {}).data || {};
|
||
const names = Object.fromEntries((data.locations || []).map(l => [l.id, l.name]));
|
||
const train = (data.trains || [])[0];
|
||
if (!train) return reply({ ok: false, error: 'Train introuvable dans TIS' });
|
||
const rows = buildTimetable(train, id => names[id] || `#${id}`);
|
||
dbg('info', `horaire du train ${train.header.otn} : ${rows.length} étapes`); await flushDbg();
|
||
return reply({ ok: true, rows, numbers: trainNumbers(train.header) });
|
||
} catch (e) { return reply({ ok: false, error: e.message }); }
|
||
}
|
||
if (msg.type === 'companies') {
|
||
const c = (await chrome.storage.local.get('companies')).companies;
|
||
if (c && c.at && Date.now() - c.at < 7 * 86400e3 && !msg.refresh) return reply({ ok: true, list: c.list });
|
||
try {
|
||
const r = await fetch('https://tis-prod.rne.eu/tis2020api/api/companies', { credentials: 'include', headers: { Accept: 'application/json' } });
|
||
if (!r.ok) return reply({ ok: false, error: `TIS HTTP ${r.status}` });
|
||
const list = ((await r.json()).data || []).filter(x => x.displayType === 'RAILWAY_UNDERTAKING' && x.code)
|
||
.map(x => ({ c: x.code, n: x.name || x.shortName || '', cc: x.countryCode || '' }));
|
||
await chrome.storage.local.set({ companies: { at: Date.now(), list } });
|
||
dbg('info', `entreprises ferroviaires TIS chargées : ${list.length}`); await flushDbg();
|
||
return reply({ ok: true, list });
|
||
} catch (e) { return reply({ ok: false, error: e.message }); }
|
||
}
|
||
if (msg.type === 'setCfg') {
|
||
await chrome.storage.local.set({ cfg: { yellowFromMin: Number(msg.yellowFromMin) || 5, redFromMin: Number(msg.redFromMin) || 15 } });
|
||
return reply({ ok: true });
|
||
}
|
||
if (msg.type === 'login') { await startLogin(false); return reply({ ok: true }); }
|
||
// Filtres de recherche enregistrés dans TIS (ex. « Sib » = tes entreprises ferroviaires).
|
||
if (msg.type === 'listFilters') {
|
||
try {
|
||
const r = await fetch('https://tis-prod.rne.eu/tis2020api/api/trainsearchfilter/self', { credentials: 'include', headers: { Accept: 'application/json' } });
|
||
if (!r.ok) { dbg('warn', `filtres TIS indisponibles (HTTP ${r.status})`); await flushDbg(); return reply({ ok: false, auth: r.status === 401 || r.status === 403, error: `TIS HTTP ${r.status}` }); }
|
||
const list = ((await r.json()).data || {}).trainSearchFilters || [];
|
||
const filters = list.map(f => ({ id: f.id, name: f.name, isDefault: !!f.isDefault, definition: f.definition, ruCount: ((f.definition || {}).ruCodes || []).length }));
|
||
await chrome.storage.local.set({ tisFilters: filters });
|
||
dbg('info', `filtres TIS : ${filters.map(f => f.name).join(', ') || 'aucun'}`); await flushDbg();
|
||
return reply({ ok: true, filters });
|
||
} catch (e) { dbg('warn', 'filtres TIS illisibles : ' + e.message); await flushDbg(); return reply({ ok: false, error: e.message }); }
|
||
}
|
||
if (msg.type === 'setSource') { // compatibilité : ancienne façon de choisir la source
|
||
const id = msg.source !== 'filter' ? 'preset-manual' : String(msg.filterId).startsWith('preset-') ? String(msg.filterId) : 'tis-' + msg.filterId;
|
||
if (id.startsWith('tis-')) {
|
||
const f = s.tisFilters.find(x => 'tis-' + x.id === id);
|
||
if (!f) return reply({ ok: false, error: 'Filtre introuvable' });
|
||
await chrome.storage.local.set({ tisFilter: { id: f.id, name: f.name, definition: f.definition } });
|
||
}
|
||
await chrome.storage.local.set({ prefs: { ...s.prefs, activeList: id, sourceChosen: true, source: id === 'preset-manual' ? 'list' : 'filter' } });
|
||
dbg('info', `source : ${id}`);
|
||
reply({ ok: true }); await poll('source modifiée'); return;
|
||
}
|
||
// Mode filtre : masquer un train (24 h) au lieu de le retirer d'une liste.
|
||
if (msg.type === 'hide') {
|
||
const hidden = { ...s.hidden, [msg.id]: Date.now() + 24 * 3600e3 };
|
||
const rows = s.data ? s.data.rows.filter(t => String(t.id) !== String(msg.id)) : [];
|
||
await chrome.storage.local.set({ hidden, data: { ...(s.data || {}), rows, hiddenCount: Object.keys(hidden).length } });
|
||
updateBadge(rows, s.data && s.data.error);
|
||
dbg('info', `train ${msg.otn || msg.id} masqué pour 24 h`); await flushDbg();
|
||
return reply({ ok: true });
|
||
}
|
||
if (msg.type === 'unhideAll') { await chrome.storage.local.set({ hidden: {} }); reply({ ok: true }); await poll('trains réaffichés'); return; }
|
||
if (msg.type === 'checkSession') {
|
||
const ok = await checkSession();
|
||
reply({ ok });
|
||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||
if (ok && cur) await finishLogin(cur); // filet de sécurité : la page TTA vérifie aussi pendant la connexion
|
||
return;
|
||
}
|
||
if (msg.type === 'dbg') { dbg(msg.level || 'info', String(msg.text || '').slice(0, 500)); await flushDbg(); return reply({ ok: true }); }
|
||
if (msg.type === 'clearDebug') { dbgBuf.length = 0; pendingStats.set = {}; pendingStats.inc = {}; await chrome.storage.local.set({ debug: [], stats: { version: chrome.runtime.getManifest().version } }); return reply({ ok: true }); }
|
||
reply({ ok: false });
|
||
})();
|
||
return true; // réponse asynchrone
|
||
});
|