douyinWEB/backend/neko/live-ops-extension/background.js
eric dea036c50d Prefer YouTube receiving/Studio on-air for live-map and sync assign lives to hub.
Tighten http/youtubei live probes, classify Studio encoder_lost vs waiting, and keep dy/dylive public live counts aligned via edge assign_lives.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 22:57:52 -05:00

210 lines
6.5 KiB
JavaScript

const API_BASES = [
// Physical / Docker: hit host API first — public HTTPS often hangs and blocks all telemetry.
"http://host.docker.internal:8014",
"http://172.17.0.1:8014",
// VPS dylive (local assign Neko on hub) — must be present or telemetry never reaches hub.
"https://dylive.nomadro.com",
"https://dy.nomadro.com",
"https://dy.nomadro.cn",
"https://dy.nomadro.live",
"http://127.0.0.1:8014",
];
const JUNK_TAB_RE = /tampermonkey\.net\/(changelog|installed)\.php/i;
const LIVE_STUDIO_RE = /studio\.youtube\.com\/.*\/livestreaming/i;
const AUTH_JUNK_RE =
/accounts\.google\.com\/(?:ServiceLogin|signin|v3\/signin|accountchooser|RotateCookiesPage)/i;
const YOUTUBE_HOME_RE = /^https:\/\/www\.youtube\.com\/?(?:\?|$)/;
let cachedNekoInstanceId = "";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function tabUrl(tab) {
return tab?.pendingUrl || tab?.url || "";
}
function normalizeNekoRef(raw) {
const text = String(raw || "").trim();
if (!text) return "";
const low = text.toLowerCase();
if (low.startsWith("ops-") || low.startsWith("ops:")) {
const digits = low.replace(/^ops[-:]/, "").replace(/[^\d]/g, "");
return digits ? `ops-${digits}` : "";
}
const n = Number(text);
if (Number.isFinite(n) && n > 0) return String(Math.trunc(n));
return "";
}
async function loadNekoInstanceId() {
if (cachedNekoInstanceId) return cachedNekoInstanceId;
try {
const stored = await chrome.storage.local.get(["nekoInstanceId", "nekoInstanceRef"]);
const fromRef = normalizeNekoRef(stored.nekoInstanceRef || stored.nekoInstanceId || "");
if (fromRef) {
cachedNekoInstanceId = fromRef;
return cachedNekoInstanceId;
}
} catch {}
try {
const res = await fetch(chrome.runtime.getURL("instance_id.txt"), { cache: "no-store" });
if (res.ok) {
const text = (await res.text()).trim();
const ref = normalizeNekoRef(text);
if (ref) {
cachedNekoInstanceId = ref;
await chrome.storage.local.set({ nekoInstanceId: ref, nekoInstanceRef: ref });
return ref;
}
}
} catch {}
return "";
}
loadNekoInstanceId().catch(() => {});
async function focusYoutubeLiveTab(tabs) {
const liveTabs = tabs.filter((tab) => LIVE_STUDIO_RE.test(tabUrl(tab)) && tab.id);
if (liveTabs.length) {
const target = liveTabs.find((tab) => tab.active) || liveTabs[0];
await chrome.tabs.update(target.id, { active: true });
await chrome.tabs.reload(target.id);
if (LIVE_STUDIO_RE.test(tabUrl(target))) {
await chrome.storage.local.set({ lastLiveStudioUrl: tabUrl(target) });
}
return target.id;
}
const stored = await chrome.storage.local.get(["lastLiveStudioUrl"]);
const saved = (stored.lastLiveStudioUrl || "").trim();
if (saved && LIVE_STUDIO_RE.test(saved)) {
const created = await chrome.tabs.create({ url: saved, active: true });
return created?.id || null;
}
return null;
}
async function normalizeTabsAfterRestore(attempt = 0) {
const delayMs = attempt === 0 ? 5000 : 2500;
if (attempt > 12) return;
await sleep(delayMs);
let tabs = [];
try {
tabs = await chrome.tabs.query({});
} catch {
return;
}
for (const tab of tabs) {
const url = tabUrl(tab);
if (!tab.id) continue;
if (JUNK_TAB_RE.test(url)) {
try {
await chrome.tabs.remove(tab.id);
} catch {}
}
}
tabs = await chrome.tabs.query({});
const liveTabId = await focusYoutubeLiveTab(tabs);
if (liveTabId) {
const refreshed = await chrome.tabs.query({});
for (const tab of refreshed) {
const url = tabUrl(tab);
if (!tab.id || tab.id === liveTabId) continue;
if (JUNK_TAB_RE.test(url) || AUTH_JUNK_RE.test(url) || YOUTUBE_HOME_RE.test(url)) {
try {
await chrome.tabs.remove(tab.id);
} catch {}
}
}
}
const remainingJunk = (await chrome.tabs.query({})).some((tab) => JUNK_TAB_RE.test(tabUrl(tab)));
if (remainingJunk) {
normalizeTabsAfterRestore(attempt + 1);
}
}
function scheduleTabHygiene() {
normalizeTabsAfterRestore(0).catch(() => {});
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
const url = changeInfo.url || tabUrl(tab);
if (!url || !JUNK_TAB_RE.test(url)) return;
chrome.tabs.remove(tabId).catch(() => {});
});
chrome.tabs.onCreated.addListener((tab) => {
const url = tabUrl(tab);
if (!url || !JUNK_TAB_RE.test(url)) return;
if (tab.id) chrome.tabs.remove(tab.id).catch(() => {});
});
chrome.runtime.onStartup.addListener(scheduleTabHygiene);
chrome.runtime.onInstalled.addListener(scheduleTabHygiene);
scheduleTabHygiene();
async function postTelemetry(payload) {
const stored = await chrome.storage.local.get(["liveHubIngestToken"]);
const ingestToken = (stored.liveHubIngestToken || "").trim();
const nekoRef =
(await loadNekoInstanceId()) ||
normalizeNekoRef(payload?.neko_ref || payload?.neko_instance_id || "") ||
"";
const body = JSON.stringify({
...payload,
source: payload.source || "chrome_extension",
received_at: Date.now() / 1000,
...(nekoRef
? {
neko_instance_id: nekoRef,
neko_ref: nekoRef,
}
: {}),
...(ingestToken ? { ingest_token: ingestToken } : {}),
});
let lastError = "";
for (const base of API_BASES) {
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500);
const res = await fetch(`${base}/hub/youtube/live/ingest`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
cache: "no-store",
signal: ctrl.signal,
});
clearTimeout(timer);
if (res.ok) {
const data = await res.json().catch(() => ({}));
await chrome.storage.local.set({
liveHubLastOk: Date.now(),
liveHubLastBase: base,
liveHubLastEvent: data?.event?.id || null,
liveHubLastNekoId: data?.event?.neko_ref || data?.event?.neko_instance_id || nekoRef || null,
});
return { ok: true, base, eventId: data?.event?.id || null };
}
lastError = `${base} HTTP ${res.status}`;
} catch (err) {
lastError = `${base} ${err?.message || String(err)}`;
}
}
await chrome.storage.local.set({ liveHubLastError: lastError, liveHubLastErrorAt: Date.now() });
return { ok: false, error: lastError };
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || message.type !== "live-hub-youtube-telemetry") return false;
postTelemetry(message.payload || {}).then(sendResponse);
return true;
});