douyinWEB/backend/neko/live-ops-extension/content.js
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

221 lines
7.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const LIVE_HUB_MIN_INTERVAL_MS = 1800;
let lastSentAt = 0;
let lastSignature = "";
function cleanText(value, max = 260) {
return String(value || "")
.replace(/\s+/g, " ")
.trim()
.slice(0, max);
}
function pageText() {
return cleanText(document.body?.innerText || "", 6000);
}
function parseCompactNumber(raw) {
const text = cleanText(raw, 40).replace(/,/g, "");
const match = text.match(/(\d+(?:\.\d+)?)([kKmMwW万]*)/);
if (!match) return null;
let value = Number(match[1]);
const unit = match[2].toLowerCase();
if (unit === "k") value *= 1000;
if (unit === "m") value *= 1000000;
if (unit === "w" || unit === "万") value *= 10000;
return Number.isFinite(value) ? Math.round(value) : null;
}
function firstNumberByPatterns(text, patterns) {
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) {
const parsed = parseCompactNumber(match[1]);
if (parsed != null) return parsed;
}
}
return null;
}
function detectLiveStatus(text) {
const lower = text.toLowerCase();
if (/stream ended|not live|offline|直播已结束|未在直播/.test(lower)) return "ended";
if (/connect your encoder|no data|stream offline|not streaming|waiting for you to start/.test(lower)) {
return "waiting";
}
if (
/you'?re live|you are live|excellent connection|stream is healthy|end stream|stop streaming|concurrent viewers|watching now|直播中|正在直播|已开始直播|结束直播/.test(
lower
)
) {
return "live";
}
// Studio shows a LIVE pill + duration while on-air
if (/\blive\b[\s\S]{0,40}\d+:\d{2}(?::\d{2})?/.test(lower) && /end stream|stop streaming/.test(lower)) {
return "live";
}
if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting";
if (/error|failed|copyright|policy|异常|错误|受限|违规/.test(lower)) return "attention";
return "";
}
function detectHealth(text) {
const lower = text.toLowerCase();
if (/excellent connection|stream is healthy|health excellent|连接状况极佳|状况良好/.test(lower)) return "excellent";
if (/good connection|healthy|良好/.test(lower)) return "good";
if (/unstable|poor|buffer|warning|警告|不稳定|不佳|卡顿/.test(lower)) return "warning";
if (/error|failed|disconnect|异常|错误|断开/.test(lower)) return "error";
return "";
}
/** LIVE pill duration e.g. "37:06" or "1:19:36" → seconds */
function parseLiveDuration(text) {
const match =
text.match(/\bLIVE\b\s*(\d{1,2}:\d{2}(?::\d{2})?)/i) ||
text.match(/(?:直播时长|已直播)\s*[::]?\s*(\d{1,2}:\d{2}(?::\d{2})?)/i);
if (!match) return { live_duration: "", live_duration_sec: null };
const raw = match[1];
const parts = raw.split(":").map((x) => Number(x));
let sec = null;
if (parts.length === 3 && parts.every((n) => Number.isFinite(n))) {
sec = parts[0] * 3600 + parts[1] * 60 + parts[2];
} else if (parts.length === 2 && parts.every((n) => Number.isFinite(n))) {
sec = parts[0] * 60 + parts[1];
}
return { live_duration: raw, live_duration_sec: sec };
}
/** Analytics tab cumulative Views (not concurrent). */
function parseTotalViews(text) {
// Prefer labeled "Views" / 观看次数, avoid "Concurrent viewers"
const patterns = [
/(?:^|\n)\s*Views\s*\n\s*([\d,.]+[kKmMwW万]?)/i,
/\bViews\b(?!\s*per)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
/(?:总观看|观看次数|观看量)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/,
];
for (const pattern of patterns) {
const match = text.match(pattern);
if (!match) continue;
// Reject if this is clearly the concurrent line
const around = text.slice(Math.max(0, (match.index || 0) - 24), (match.index || 0) + 40).toLowerCase();
if (/concurrent/.test(around)) continue;
const parsed = parseCompactNumber(match[1]);
if (parsed != null) return parsed;
}
return null;
}
function collectPopupTexts() {
const selectors = [
"[role='dialog']",
"[aria-live='assertive']",
"[aria-live='polite']",
"ytcp-toast",
"tp-yt-paper-toast",
"paper-dialog",
"ytcp-alert",
"ytcp-ve",
];
const out = [];
for (const node of document.querySelectorAll(selectors.join(","))) {
const rect = node.getBoundingClientRect?.();
if (rect && rect.width === 0 && rect.height === 0) continue;
const text = cleanText(node.innerText || node.textContent || "", 500);
if (text && !out.includes(text)) out.push(text);
if (out.length >= 8) break;
}
return out;
}
function collectStreamTitle() {
const selectors = [
"input[aria-label*='Title']",
"textarea[aria-label*='Title']",
"ytcp-social-suggestions-textbox",
"ytcp-video-title",
"h1",
];
for (const selector of selectors) {
const node = document.querySelector(selector);
const value = node?.value || node?.innerText || node?.textContent;
const text = cleanText(value, 180);
if (text) return text;
}
return cleanText(document.title, 180);
}
function collectTelemetry() {
const text = pageText();
const viewerCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:watching|concurrent viewers)/i,
/(?:concurrent viewers|watching now|同时观看)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:人正在观看|正在观看)/,
]);
const likeCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:likes|like count)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:点赞|赞)/,
]);
const dur = parseLiveDuration(text);
const totalViews = parseTotalViews(text);
const popups = collectPopupTexts();
const payload = {
captured_at: Date.now() / 1000,
source: "chrome_extension",
url: location.href,
page_title: document.title,
stream_title: collectStreamTitle(),
live_status: detectLiveStatus(text),
health: detectHealth(text),
viewer_count: viewerCount,
like_count: likeCount,
total_views: totalViews,
live_duration: dur.live_duration,
live_duration_sec: dur.live_duration_sec,
popups,
text: text.slice(0, 2200),
signals: {
has_dialog: popups.length > 0,
visibility: document.visibilityState,
focused: document.hasFocus(),
path: location.pathname,
},
};
return payload;
}
function signatureOf(payload) {
return JSON.stringify([
payload.url,
payload.live_status,
payload.health,
payload.viewer_count,
payload.like_count,
payload.total_views,
payload.live_duration,
payload.popups,
payload.stream_title,
]);
}
function sendTelemetry(force = false) {
const now = Date.now();
if (!force && now - lastSentAt < LIVE_HUB_MIN_INTERVAL_MS) return;
const payload = collectTelemetry();
const sig = signatureOf(payload);
if (!force && sig === lastSignature && now - lastSentAt < 10000) return;
lastSentAt = now;
lastSignature = sig;
if (/studio\.youtube\.com\/.*\/livestreaming/.test(location.href)) {
chrome.storage.local.set({ lastLiveStudioUrl: location.href });
}
chrome.runtime.sendMessage({ type: "live-hub-youtube-telemetry", payload }, () => {
void chrome.runtime.lastError;
});
}
const observer = new MutationObserver(() => sendTelemetry(false));
observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
window.addEventListener("focus", () => sendTelemetry(true));
document.addEventListener("visibilitychange", () => sendTelemetry(true));
setInterval(() => sendTelemetry(false), 3000);
sendTelemetry(true);