Files
ofsaver/ext/lib/main-hook.js
collector 53d31572a1 init
2026-12-06 12:41:22 +01:00

235 lines
9.8 KiB
JavaScript

// MAIN world: hook the page's network and index every media entry OF sends us.
// Posts/media land in window.__ofsaverMedia; the content script picks them up
// via a DOM CustomEvent, so both worlds see the same data.
(() => {
if (window.__ofsaverHooked) return;
window.__ofsaverHooked = true;
const store = new Map(); // mediaId -> entry (includes .raw = full media object)
const users = new Map(); // userId -> username (from any response that names a user)
const emit = () => {
try {
window.dispatchEvent(new CustomEvent("ofsaver-media-data", {
detail: [...store.values()],
}));
window.dispatchEvent(new CustomEvent("ofsaver-users", {
detail: [...users.entries()],
}));
} catch {}
};
const walk = (obj, found) => {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) { for (const v of obj) walk(v, found); return; }
const type = obj.type;
const files = obj.files;
if ((type === "video" || type === "audio" || type === "photo" || type === "gif") && files && typeof files === "object" && obj.id != null) {
found.add(obj);
}
for (const k of Object.keys(obj)) walk(obj[k], found);
};
const ingest = (json, url) => {
let data;
try { data = JSON.parse(json); } catch { return; }
// chat messages: emit the ordered batch so the content script can map
// DOM rows positionally (the chat rows expose no message ids). Locked
// chat media ships WITHOUT a files key and is NOT added to the media
// store — its info rides in this batch instead, keeping the store
// exactly as the download flow expects it.
if (url) {
const cm = String(url).match(/\/api2\/v2\/chats\/([^/]+)\/messages/);
if (cm) {
const list = data?.list ?? (Array.isArray(data) ? data : null);
if (list && list.length) {
const fu = list.find((m) => m.fromUser)?.fromUser;
if (fu) console.log("[ofsaver] chat batch fromUser sample:", fu.id, fu.username);
try {
window.dispatchEvent(new CustomEvent("ofsaver-chat-batch", {
detail: {
chatId: cm[1],
msgs: list.map((m) => ({
id: String(m.id),
username: m.fromUser?.username ?? null,
media: (m.media ?? []).map((x) => ({
id: x.id,
type: x.type,
duration: x.duration ?? x.videoDuration ?? null,
canView: x.canView !== false,
})),
})),
},
}));
} catch {}
}
}
}
const found = new Set();
walk(data, found);
// find post context: any post objects mapping postId → their media list
const postMedia = new Map();
// containers: posts (postedAt/responseType) and chat messages (fromUser/createdAt)
const containers = [];
const walkContainers = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkContainers(v); return; }
if (o.id != null && Array.isArray(o.media) && o.media.length) {
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
const isMessage = Array.isArray(o.media) && (o.fromUser !== undefined || o.createdAt !== undefined) && !isPost;
if (isPost || isMessage) {
containers.push({
id: o.id,
responseType: isMessage ? "message" : (o.responseType ?? "post"),
username: o.author?.username ?? o.fromUser?.username,
creatorId: o.author?.id ?? o.fromUser?.id,
});
}
}
for (const k of Object.keys(o)) walkContainers(o[k]);
};
walkContainers(data);
// second pass: map media ids to their container
const containerMedia = new Map();
const walkMediaLinks = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkMediaLinks(v); return; }
if (o.id != null && Array.isArray(o.media) && o.media.length) {
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
const isMessage = o.fromUser !== undefined || (o.createdAt !== undefined && !isPost);
if (isPost || isMessage) {
for (const m of o.media) {
if (m?.id != null) containerMedia.set(m.id, {
postId: o.id,
responseType: isMessage ? "message" : (o.responseType ?? "post"),
username: o.author?.username ?? o.fromUser?.username,
creatorId: o.author?.id ?? o.fromUser?.id,
});
}
}
}
for (const k of Object.keys(o)) walkMediaLinks(o[k]);
};
walkMediaLinks(data);
// any response that names a user fixes the id → handle mapping for all
// future naming (some views ship fromUser.id without the username)
const usersBefore = users.size;
const walkUsers = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkUsers(v); return; }
if (o.id != null && typeof o.username === "string" && o.username) users.set(String(o.id), o.username);
for (const k of Object.keys(o)) walkUsers(o[k]);
};
walkUsers(data);
for (const m of found) {
const drm = m.files?.drm;
const src = m.files?.source?.url ?? m.files?.full?.url ?? null;
const prev = store.get(m.id);
// keep the richest info we've seen (later API views may be less privileged)
const ctx = containerMedia.get(m.id) ?? {};
const entry = {
id: m.id,
postId: ctx.postId ?? prev?.postId ?? null,
responseType: ctx.responseType ?? prev?.responseType ?? null,
username: ctx.username ?? (ctx.creatorId != null ? users.get(String(ctx.creatorId)) : null) ?? prev?.username ?? null,
creatorId: ctx.creatorId ?? prev?.creatorId ?? null,
type: m.type,
canView: m.canView !== false, // latest API view wins
duration: m.duration ?? m.videoDuration ?? prev?.duration ?? null,
createdAt: m.createdAt ?? prev?.createdAt ?? null,
height: m.height ?? m.files?.source?.h ?? prev?.height ?? null,
drm: (drm?.manifest && drm) || prev?.drm || null,
source: (m.canView !== false && src) || prev?.source || null,
raw: m, // full media object for quality variants
};
if (m.canView === false) entry.canView = false;
store.set(m.id, entry);
}
if (found.size || users.size !== usersBefore) emit();
};
const of = window.fetch;
window.fetch = async function (...args) {
try {
const u = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
if (/\/api2\//.test(u)) {
const h = args[1]?.headers;
const get = (k) => {
if (!h) return null;
if (typeof Headers !== "undefined" && h instanceof Headers) return h.get(k);
return h[k] ?? h[k.toLowerCase()] ?? null;
};
const uid = get("user-id");
const bc = get("x-bc");
if (uid != null || bc != null) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
if (uid != null) store.uid = String(uid);
if (bc != null) store.bc = String(bc);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
}
}
} catch {}
const res = await of.apply(this, args);
try {
const url = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
if (/\/api2\/v2\//.test(url) && res.ok) {
const clone = res.clone();
clone.text().then((t) => ingest(t, url)).catch(() => {});
}
} catch {}
return res;
};
// capture the page's own license request headers for auth debugging
const osrh = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
try {
const lk = String(k).toLowerCase();
const u = String(this.__ofsaverUrl ?? "");
// session auth capture: every signed /api2/ request carries user-id
// and x-bc — the tab's own session, which is the only correct one in
// incognito (chrome.cookies reads the regular jar there)
if (/\/api2\//.test(u) && (lk === "user-id" || lk === "x-bc")) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
if (lk === "user-id") store.uid = String(v);
else store.bc = String(v);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
}
if (/\/drm\/|\/licenses?\b|type=widevine/i.test(u) || /sign|time|x-bc|app-token|user-id|x-of-rev/i.test(lk)) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-lic") || "{}");
(store.h = store.h || {})[lk] = v;
store.url = u.slice(0, 120);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-lic", JSON.stringify(store));
}
} catch {}
return osrh.call(this, k, v);
};
const oo = XMLHttpRequest.prototype.open;
const os = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
this.__ofsaverUrl = url;
return oo.call(this, method, url, ...rest);
};
XMLHttpRequest.prototype.send = function (...args) {
this.addEventListener("load", () => {
try {
if (/\/api2\/v2\//.test(String(this.__ofsaverUrl ?? "")) && this.responseText) ingest(this.responseText, this.__ofsaverUrl);
} catch {}
});
return os.apply(this, args);
};
emit();
// content script can push fetched API data back in (backfills for posts
// whose responses happened before this hook installed)
window.addEventListener("ofsaver-ingest", (e) => {
try { ingest(e.detail); } catch {}
});
})();