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

791 lines
34 KiB
JavaScript

// Isolated world: per-media Download pills in post/message
// toolbars + a BUNDLE pill for multi-media groups. Menus offer quality
// variants; DRM media run the full license flow; saved media are marked.
(() => {
if (window.__ofsaverContentLoaded) return;
window.__ofsaverContentLoaded = true;
// drop pills left by a previous (orphaned) instance
document.querySelectorAll("[data-ofsaver-media]").forEach((el) => el.remove());
if (!document.getElementById("ofsaver-style")) {
const st = document.createElement("style");
st.id = "ofsaver-style";
st.textContent = "@keyframes ofsaverspin{to{transform:rotate(360deg)}}";
document.documentElement.appendChild(st);
}
const media = new Map(); // id -> entry
const buttons = new Map(); // key -> pill element
const savedSet = new Map(); // mediaId -> ts
let openMenu = null;
let activeBundle = null; // { btn, done, items } while a bundle runs
function refreshSaved() {
chrome.runtime.sendMessage({ op: "getSaved" }, (res) => {
if (res?.ok && res.set) {
for (const [id, ts] of Object.entries(res.set)) savedSet.set(id, ts);
render();
}
});
}
refreshSaved();
function postMedia(postId) {
return [...media.values()].filter((m) => String(m.postId) === String(postId));
}
const POST_ANCHORS = [
(id) => document.getElementById(`postId_${id}`),
(id) => document.querySelector(`[data-post-id="${id}"]`),
];
const TOOLBARS = [".b-post__tools", ".b-post__actions", ".feed-item-stats"];
const MESSAGE_ANCHORS = [
(id) => document.querySelector(`[data-message-id="${id}"]`),
(id) => document.getElementById(`messageId_${id}`),
];
const MESSAGE_TOOLBARS = [".m-chat-message__actions"];
function findToolbar(postId) {
for (const anchor of POST_ANCHORS) {
const root = anchor(postId);
if (!root) continue;
for (const sel of TOOLBARS) {
const bar = root.querySelector(sel) ?? (root.matches(sel) ? root : null);
if (bar) return bar;
}
return root;
}
for (const anchor of MESSAGE_ANCHORS) {
const root = anchor(postId);
if (!root) continue;
for (const sel of MESSAGE_TOOLBARS) {
const bar = root.querySelector(sel) ?? (root.matches(sel) ? root : null);
if (bar) return bar;
}
return root;
}
return null;
}
function pageUsername() {
if (/\/my\/chats\//.test(location.pathname)) return null; // chat routes have no creator in the path
const segs = location.pathname.split("/").filter(Boolean);
for (let i = segs.length - 1; i >= 0; i--) {
if (!/^\d+$/.test(segs[i]) && segs[i].length > 1) return segs[i];
}
return null;
}
// ---- pills -------------------------------------------------------------
const BADGES = { photo: "PIC", video: "VID", gif: "GIF", audio: "AUD" };
function fmtDuration(sec) {
const s = Math.round(Number(sec) || 0);
if (!s) return "";
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}
const SPINNER = `<span style="width:12px;height:12px;flex:none;border:2px solid #d8d8de;border-top-color:#e5484d;border-radius:50%;display:inline-block;animation:ofsaverspin .7s linear infinite"></span>`;
function pillEl(key) {
let btn = buttons.get(key);
if (btn && btn.isConnected) return btn;
btn = document.createElement("div");
btn.dataset.ofsaverMedia = key;
btn.__ofsaverMine = true;
btn.style.cssText =
"display:inline-flex;align-items:center;gap:4px;margin-left:8px;cursor:pointer;user-select:none;flex:none;vertical-align:middle;";
buttons.set(key, btn);
return btn;
}
function pillInner(entry, status, pct) {
const hasDrm = Boolean(entry.drm);
const saved = savedSet.has(String(entry.id));
const dur = fmtDuration(entry.duration);
const label = status === "loading" ? `Downloading ${pct ?? 0}%` : (status || (saved ? "Saved" : "Download"));
return (
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(status === "loading" && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(status === "loading" ? SPINNER : "") +
`<span data-label>${label}</span>` +
(dur && !status ? `<span style="color:#e5484d;font-size:11px">· ${dur}</span>` : "") +
`<span style="font-size:9px;opacity:.6">▼</span></span>` +
(hasDrm ? `<span style="background:#111;color:#fff;border-radius:6px;font:700 10px/1 -apple-system,system-ui,sans-serif;padding:4px 7px;display:inline-flex;align-items:center">DRM</span>` : "") +
(saved && !status ? `<span style="color:#23a55a;font:600 12px -apple-system,system-ui,sans-serif">✓</span>` : "")
);
}
function paintPill(btn, entry, status, pct) {
pct = pct ?? (Number(btn.dataset.pct) || 0);
if (status === "loading" && btn.dataset.status === "loading" && btn.querySelector("[data-bar]")) {
paintPillProgress(btn, pct); // smooth: update label + bar in place
return;
}
btn.innerHTML = pillInner(entry, status, pct);
}
function paintPillProgress(btn, pct) {
btn.dataset.pct = pct;
const lbl = btn.querySelector("[data-label]");
if (lbl) lbl.textContent = `Downloading ${pct}%`;
const bar = btn.querySelector("[data-bar]");
if (bar) bar.style.width = pct + "%";
}
function paintBundlePill(btn, count, status, pct) {
const saved = status === "saved";
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(status === "loading" && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(status === "loading" ? SPINNER : "") +
`<span data-blabel>${status === "loading" ? (pct != null ? `Downloading ${pct}%` : "Downloading…") : saved ? "Saved" : "Download all"}</span>` +
`<span style="color:#888;font-size:11px">${count}</span></span>`;
}
/** In-place bundle label/bar update (no innerHTML churn). */
function paintBundleProgress(btn, text, pct) {
btn.dataset.pct = pct ?? "";
const lbl = btn.querySelector("[data-blabel]");
if (lbl) lbl.textContent = text;
const bar = btn.querySelector("[data-bar]");
if (pct != null) {
if (bar) { bar.style.width = pct + "%"; return; }
// no bar yet (pill was painted without one) — add it
const shell = btn.firstElementChild;
if (shell) {
const el = document.createElement("span");
el.dataset.bar = "";
el.style.cssText = "position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:" + pct + "%;transition:width .2s";
shell.prepend(el);
}
}
}
// ---- menu --------------------------------------------------------------
function closeMenu() {
openMenu?.remove();
openMenu = null;
}
document.addEventListener("click", (e) => {
if (openMenu && !openMenu.contains(e.target) && !e.target.closest("[data-ofsaver-media]")) closeMenu();
}, true);
const fmtSize = (n) => {
if (!n || n <= 0) return "";
if (n < 1024 * 1024) return Math.max(1, Math.round(n / 1024)) + " KB";
return (n / (1024 * 1024)).toFixed(1) + " MB";
};
function qualityOptions(entry) {
const out = [];
const files = entry.raw?.files ?? {};
if (entry.type === "photo" || entry.type === "gif") {
if (files.full?.url) out.push({ label: "source", url: files.full.url, ext: entry.type === "gif" ? "gif" : "jpg", size: files.full?.size });
if (!files.full?.url && files.preview?.url) out.push({ label: "preview", url: files.preview.url, ext: "jpg" });
} else if (entry.drm) {
out.push({ label: "source", drm: true, size: files.source?.size });
} else {
const vs = entry.raw?.videoSources;
const variants = [];
if (Array.isArray(vs)) for (const v of vs) if (v?.url) variants.push(v);
else if (files.source?.sources) for (const v of files.source.sources) if (v?.url) variants.push(v);
const seen = new Set();
for (const v of variants) {
if (seen.has(v.url)) continue;
seen.add(v.url);
out.push({ label: v.height ? v.height + "p" : (v.type ?? "video"), url: v.url, ext: "mp4", size: v.size ?? files.source?.size });
}
if (files.source?.url) out.push({ label: "source", url: files.source.url, ext: "mp4", size: files.source?.size });
else if (files.full?.url) out.push({ label: "source", url: files.full.url, ext: "mp4", size: files.full?.size });
}
return out;
}
function thumbFor(entry) {
return (
entry.raw?.files?.preview?.url ??
entry.raw?.files?.full?.url ??
entry.raw?.files?.source?.url ??
""
);
}
/** Backfill: if the DOM shows more media than we indexed, fetch the post. */
async function backfillIfNeeded(postId, entries, root) {
if (!root) return;
const countEl = [...root.querySelectorAll("*")].find((el) =>
el.children.length === 0 && /^\s*\d+\s*\/\s*\d+\s*$/.test(el.textContent ?? "")
);
if (!countEl) return;
const expected = Number(countEl.textContent.split("/")[1]);
if (!expected || expected <= entries.length) return;
const any = entries[0];
const res = await new Promise((r) =>
chrome.runtime.sendMessage(
{ op: "fetchPostMedia", postId, creatorId: any?.creatorId, username: any?.username ?? pageUsername() },
r
)
);
if (res?.ok && res.data) {
window.dispatchEvent(new CustomEvent("ofsaver-ingest", { detail: res.data }));
}
}
function toggleMenu(btn, entry) {
const key = String(entry.id);
if (openMenu && openMenu.dataset.media === key) { closeMenu(); return; }
closeMenu();
const who = entry.username ? `@${entry.username}` : (entry.creatorId ? `#${entry.creatorId}` : "");
const menu = document.createElement("div");
menu.dataset.media = key;
menu.style.cssText = [
"position:absolute", "z-index:1000000", "background:#fff", "color:#111",
"border-radius:14px", "padding:14px 16px", "min-width:340px",
"max-height:65vh", "overflow:auto", "box-shadow:0 8px 32px rgba(0,0,0,.35)",
"font:13px/1.5 -apple-system,system-ui,sans-serif",
].join(";");
const opts = qualityOptions(entry);
const thumb = thumbFor(entry);
const rows = [];
opts.forEach((opt, i) => {
const isSaved = savedSet.has(String(entry.id));
rows.push(
`<div style="display:flex;align-items:center;gap:10px;padding:6px 0${isSaved ? ";opacity:.55" : ""}">` +
(thumb
? `<img src="${thumb}" style="width:44px;height:44px;border-radius:8px;object-fit:cover;flex:none" referrerpolicy="no-referrer">`
: `<div style="width:44px;height:44px;border-radius:8px;background:#eee;flex:none"></div>`) +
`<div style="flex:1;min-width:0"><div style="font-weight:600">${opt.label}${isSaved ? ` <span style="color:#23a55a;font-size:11px;font-weight:700">saved</span>` : ""}</div>` +
`<div style="font-size:11px;color:#777">${fmtSize(opt.size)}</div></div>` +
`<button data-idx="${i}" title="download" style="width:34px;height:34px;border-radius:50%;border:1px solid #f3c1c3;background:#fdf3f4;color:#e5484d;font-size:14px;cursor:pointer;flex:none">${isSaved ? "↻" : "⬇"}</button>` +
`</div>`
);
});
if (!opts.length) rows.push(`<div style="color:#888;padding:8px 0">no downloadable media</div>`);
menu.innerHTML =
`<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:4px">` +
`<div style="font-weight:700;font-size:14px">${entry.type} by ${who}</div>` +
`<button data-close style="margin-left:auto;border:0;background:none;font-size:14px;cursor:pointer;color:#888">✕</button>` +
`</div>` +
rows.join("");
menu.querySelector("[data-close]")?.addEventListener("click", closeMenu);
menu.querySelectorAll("button[data-idx]").forEach((b) => {
b.addEventListener("click", () => {
const opt = opts[Number(b.dataset.idx)];
closeMenu();
runOne(entry, opt, btn);
});
});
document.body.appendChild(menu);
const r = btn.getBoundingClientRect();
menu.style.left = Math.max(8, Math.min(r.left - 120, window.innerWidth - 380)) + "px";
menu.style.top = r.bottom + window.scrollY + 8 + "px";
openMenu = menu;
}
// Watchdog: resolve a hard failure if the SW never answers — but dlProgress
// activity re-arms the timer, so a slow multi-GB item is never killed mid-
// flight. Registered per media id so the dlProgress handler can feed it.
const pendingTouches = new Map(); // mediaId -> arm()
function sendMessageP(msg, timeoutMs = 300000) {
return new Promise((resolve) => {
let done = false;
let timer = null;
const finish = (res) => {
if (done) return;
done = true;
pendingTouches.delete(String(msg.media?.id));
clearTimeout(timer);
resolve(res);
};
const arm = () => {
clearTimeout(timer);
timer = setTimeout(() => finish({ ok: false, error: `no response in ${Math.round(timeoutMs / 1000)}s` }), timeoutMs);
};
arm();
if (msg.media?.id != null) pendingTouches.set(String(msg.media.id), arm);
try {
chrome.runtime.sendMessage(msg, (res) => {
if (chrome.runtime.lastError) finish({ ok: false, error: chrome.runtime.lastError.message });
else finish(res ?? { ok: false, error: "no response" });
});
} catch (e) { finish({ ok: false, error: String(e.message ?? e) }) }
});
}
/** Ask the offscreen doc for its last log line — names the stage that's
* stuck when an item dies without a response. 3s budget: if the offscreen
* can't even answer this, its event loop is blocked (that's the answer). */
async function probeOffscreenLog() {
try {
const res = await Promise.race([
new Promise((r) => {
try { chrome.runtime.sendMessage({ op: "lastLog" }, (x) => r(chrome.runtime.lastError ? null : x)); } catch { r(null); }
}),
new Promise((r) => setTimeout(() => r(null), 3000)),
]);
return res?.ok ? String(res.line ?? "") : null;
} catch { return null; }
}
async function runOne(entry, opt, btn) {
if (btn) { btn.__entry = entry; btn.dataset.status = "loading"; paintPill(btn, entry, "loading", 0); }
const quality = /^\d+p$/.test(opt.label) ? opt.label : (opt.label === "source" ? "source" : null);
const enriched = { ...entry, username: entry.username ?? pageUsername() };
const msg = opt.drm
? { op: "download", media: { ...enriched, responseType: entry.responseType ?? "post" } }
: { op: "downloadUrl", url: opt.url, media: enriched, ext: opt.ext, quality };
const res = await sendMessageP(msg);
if (res?.ok) {
savedSet.set(String(entry.id), Date.now());
if (btn) { delete btn.dataset.status; paintPill(btn, entry); }
} else {
const err = String(res?.error ?? "failed").slice(0, 90);
console.log("[ofsaver] download failed:", err);
if (btn) {
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#c2333a;font:600 11px/1.2 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;max-width:340px;word-break:break-word">${err}</span>`;
setTimeout(() => { delete btn.dataset.status; paintPill(btn, entry); }, 8000);
}
}
}
async function runBundle(postId, entries, btn) {
if (btn) { btn.dataset.status = "loading"; btn.dataset.pct = 0; paintBundlePill(btn, entries.length, "loading", 0); }
activeBundle = { btn, done: 0, items: entries };
let i = 0, ok = 0, fail = 0, firstError = null;
const n = entries.length;
const step = async () => {
if (i >= n) {
activeBundle = null;
if (btn) {
delete btn.dataset.status;
if (fail === 0) for (const e of entries) savedSet.set(String(e.id), Date.now());
if (fail === 0) {
paintBundlePill(btn, n, "saved");
setTimeout(() => { delete btn.dataset.status; paintBundlePill(btn, n); }, 3000);
} else {
const err = String(firstError ?? `${fail} failed`).slice(0, 90);
console.log("[ofsaver] bundle finished with failures:", fail, firstError);
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#c2333a;font:600 11px/1.2 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;max-width:340px;word-break:break-word">${err}</span>`;
setTimeout(() => { delete btn.dataset.status; paintBundlePill(btn, n); }, 8000);
}
}
return;
}
const entry = entries[i++];
const k = i; // 1-based index of the item now starting
if (activeBundle) activeBundle.done = i - 1;
if (btn?.isConnected) paintBundleProgress(btn, `${k}/${n}`, Math.round(((k - 1) / n) * 100));
const opts = qualityOptions(entry);
if (!opts.length) { await step(); return; }
const quality = /^\d+p$/.test(opts[0].label) ? opts[0].label : (opts[0].label === "source" ? "source" : null);
const enriched = { ...entry, username: entry.username ?? pageUsername() };
const msg = opts[0].drm
? { op: "download", media: { ...enriched, responseType: entry.responseType ?? "post" } }
: { op: "downloadUrl", url: opts[0].url, media: enriched, ext: opts[0].ext, quality };
const res = await sendMessageP(msg);
if (res?.ok) {
ok++;
} else {
fail++;
const err = String(res?.error ?? "failed").slice(0, 60);
const line = await probeOffscreenLog();
const shown = line ? `${err} · ${line}` : err;
firstError = firstError ?? shown;
console.log(`[ofsaver] bundle item ${k}/${n} (${entry.type} ${entry.id}) failed:`, shown);
if (btn?.isConnected) paintBundleProgress(btn, `${k}/${n} · ${err.slice(0, 40)}`, null);
}
await step();
};
await step();
}
// ---- injection ---------------------------------------------------------
function expectedCount(root) {
if (!root) return 0;
const countEl = [...root.querySelectorAll("*")].find((el) =>
el.children.length === 0 && /^\s*\d+\s*\/\s*\d+\s*$/.test(el.textContent ?? "")
);
if (!countEl) return 0;
return Number(countEl.textContent.split("/")[1]) || 0;
}
function render() {
const postIds = new Set(
[...media.values()].filter((m) => m.postId != null).map((m) => String(m.postId))
);
for (const postId of postIds) {
const bar = findToolbar(postId);
if (!bar) continue;
const entries = postMedia(postId);
// backfill once when the DOM advertises more media than we indexed
const root = bar.closest('[id^="postId_"],[data-post-id],[data-message-id]');
if (entries.length && entries.length < expectedCount(root)) {
const marker = `bf_${postId}`;
if (!bar.dataset[marker]) {
bar.dataset[marker] = "1";
backfillIfNeeded(postId, entries, root);
}
}
const withOpts = entries.filter((e) => qualityOptions(e).length);
// BUNDLE pill first (toolbars clip on the right; it must stay visible)
if (withOpts.length > 1) {
const key = `b_${postId}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
runBundle(postId, withOpts, btn);
});
bar.prepend(btn);
}
if (btn.dataset.status !== "loading") paintBundlePill(btn, withOpts.length, btn.dataset.status);
}
for (const entry of withOpts) {
const key = `m_${entry.id}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
toggleMenu(btn, entry);
});
bar.appendChild(btn);
}
paintPill(btn, entry, btn.dataset.status);
}
}
renderChat();
}
// MAIN world pushes the full store whenever new media shows up
window.addEventListener("ofsaver-media-data", (e) => {
for (const it of e.detail ?? []) media.set(it.id, it);
render();
});
// id → handle pairs seen in any API response (naming fallback)
const userNames = new Map();
window.addEventListener("ofsaver-users", (e) => {
for (const [id, u] of e.detail ?? []) userNames.set(String(id), u);
});
chrome.runtime.onMessage.addListener((msg, _s, sendResponse) => {
if (msg.op === "ingest" && msg.data) {
// refreshed media data (fresh DRM signatures) from the background
window.dispatchEvent(new CustomEvent("ofsaver-ingest", { detail: msg.data }));
sendResponse({ ok: true });
return;
}
if (msg.op === "whoIs") {
// sender username for a media id, straight from what the page has
// already shown us — no API call needed (naming fallback)
let username = null;
outer: for (const st of chatState.values()) {
for (const m of st.chrono) {
if ((m.media ?? []).some((x) => String(x.id) === String(msg.mediaId))) {
username = m.username ?? null;
break outer;
}
}
}
if (!username && msg.creatorId != null) username = userNames.get(String(msg.creatorId)) ?? null;
sendResponse({ ok: true, username });
return;
}
if (msg.op === "getAuth") {
// session identity captured by the MAIN-world hook from the page's own
// signed API requests — correct even in incognito
try {
const raw = document.documentElement.getAttribute("data-ofsaver-auth");
sendResponse({ ok: true, auth: raw ? JSON.parse(raw) : null });
} catch { sendResponse({ ok: true, auth: null }); }
return;
}
if (msg.op === "dlProgress") {
const pct = Math.max(0, Math.min(100, Number(msg.pct) || 0));
pendingTouches.get(String(msg.id))?.(); // activity: re-arm the watchdog
const btn = buttons.get(`m_${msg.id}`);
if (btn && btn.dataset.status === "loading") paintPillProgress(btn, pct);
if (activeBundle && activeBundle.btn?.isConnected) {
const n = activeBundle.items.length;
const k = Math.min(n, activeBundle.done + 1); // item in flight
const overall = Math.min(100, Math.round(((activeBundle.done + pct / 100) / n) * 100));
paintBundleProgress(activeBundle.btn, `${k}/${n} · ${overall}%`, overall);
}
return;
}
if (msg.op === "savedUpdated") {
for (const id of msg.ids ?? []) savedSet.set(String(id), Date.now());
render();
sendResponse({});
return;
}
if (msg.op === "licensePost") {
// same-origin relay: the page's origin is what OF's CORS check accepts
(async () => {
try {
const body = Uint8Array.from(atob(msg.bodyB64), (c) => c.charCodeAt(0));
const res = await fetch(msg.url, { method: "POST", credentials: "include", headers: msg.headers, body });
const buf = new Uint8Array(await res.arrayBuffer());
let bin = "";
for (const b of buf) bin += String.fromCharCode(b);
if (!res.ok) console.log("[ofsaver] license relay status:", res.status);
sendResponse({ ok: res.ok, status: res.status, bodyB64: btoa(bin) });
} catch (e) {
sendResponse({ ok: false, error: String(e.message ?? e) });
}
})();
return true;
}
});
// orphaned instances (extension reloaded under us) must stop rendering —
// otherwise they keep re-adding duplicate pills forever. The LAST injected
// instance owns the token; older ones see a mismatch and self-terminate.
const myToken = Math.random().toString(36).slice(2);
document.documentElement.setAttribute("data-ofsaver-inst", myToken);
const renderTimer = setInterval(() => {
try {
if (document.documentElement.getAttribute("data-ofsaver-inst") !== myToken) {
throw new Error("superseded");
}
void chrome.runtime.id;
render();
} catch {
clearInterval(renderTimer);
document.querySelectorAll("[data-ofsaver-media]").forEach((el) => {
if (el.__ofsaverMine) el.remove();
});
}
}, 1500);
// ---- chat pills (new OF chat UI) ----------------------------------------
// Chat rows carry [at-attr="chat_message"] but expose NO message/media ids.
// Rows are mapped to API messages positionally (the messages list order
// mirrors the row order); locked media (no files in the API) get a
// duration pill instead of a download. Pills mount in their own
// flex-wrap block at the bottom of the row — never inside
// .b-chat__message__controls (a non-wrapping flex strip that shoves the
// media swiper off-view when filled).
document.documentElement.dataset.ofsaverV = "0.5.14";
const diagTick = () => { document.documentElement.dataset.ofsaverMediaCount = String(media.size); };
const CHAT_ROW_SEL = '.b-chat__messages-wrapper [at-attr="chat_message"]';
const chatState = new Map(); // chatId -> { chrono: [], seen: Set }
const TYPE_LABELS = { video: "Videos", photo: "Photos", gif: "GIFs", audio: "Audio" };
function paintGroupPill(btn, label, count, status, pct) {
const saved = status === "saved";
const loading = status === "loading";
const text = loading ? (pct != null ? `Downloading ${pct}%` : "Downloading…") : saved ? "Saved" : label;
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(loading && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(loading ? SPINNER : "") +
`<span data-blabel>${text}</span>` +
(!loading && !saved ? `<span style="color:#888;font-size:11px">${count}</span>` : "") +
(saved ? `<span style="color:#23a55a;font:600 12px -apple-system,system-ui,sans-serif">✓</span>` : "") +
`</span>`;
}
function attachPills(bar, entries, groupKey) {
// bundles: one pill per media type ("Videos 3", "Photos 22") instead of a
// pill per media — individual pills overflow post toolbars and flood
// chat rows. Single media keeps the quality menu.
if (entries.length > 1) {
const groups = new Map();
for (const e of entries) {
const t = TYPE_LABELS[e.type] ? e.type : "video";
if (!groups.has(t)) groups.set(t, []);
groups.get(t).push(e);
}
const single = groups.size === 1;
for (const [t, list] of groups) {
const key = `b_${groupKey}_${t}`;
const btn = pillEl(key);
const label = single ? `Download all` : (TYPE_LABELS[t] ?? t);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
runBundle(null, list, btn);
});
}
bar.appendChild(btn);
// loading pills are owned by runBundle/dlProgress (live k/N + pct) —
// repainting here fights them and the label flickers every tick
if (btn.dataset.status !== "loading") paintGroupPill(btn, label, list.length, btn.dataset.status);
}
return;
}
const entry = entries[0];
const key = `m_${entry.id}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
toggleMenu(btn, entry);
});
bar.appendChild(btn);
}
paintPill(btn, entry, btn.dataset.status);
}
window.addEventListener("ofsaver-chat-batch", (e) => {
try {
const { chatId, msgs } = e.detail ?? {};
if (!chatId || !Array.isArray(msgs) || !msgs.length) return;
let st = chatState.get(chatId);
if (!st) { st = { chrono: [], seen: new Set() }; chatState.set(chatId, st); }
const chrono = [...msgs].reverse(); // oldest → newest
const nums = chrono.map((m) => Number(m.id)).filter((x) => !Number.isNaN(x));
if (st.seen.size === 0) {
st.chrono = chrono;
} else {
const seenNums = [...st.seen].map(Number).filter((x) => !Number.isNaN(x));
const minSeen = seenNums.length ? Math.min(...seenNums) : Infinity;
const maxSeen = seenNums.length ? Math.max(...seenNums) : -Infinity;
const batchMin = nums.length ? Math.min(...nums) : Infinity;
const batchMax = nums.length ? Math.max(...nums) : -Infinity;
if (batchMax < minSeen) st.chrono = [...chrono, ...st.chrono]; // history scroll-up
else if (batchMin > maxSeen) st.chrono = [...st.chrono, ...chrono]; // live messages
}
for (const m of chrono) st.seen.add(String(m.id));
render();
} catch {}
});
function currentChatId() {
// both routes: classic /my/chats/chat/{id} and the newer /chat/{id} SPA
const m = location.pathname.match(/\/(?:my\/chats\/)?chat\/([^/]+)/);
return m ? m[1] : null;
}
/** Stable hex tokens for a media file url (file-id hash + shard dir). */
function fileTokens(url) {
const out = new Set();
if (!url) return out;
const segs = String(url).split("?")[0].split("/").filter(Boolean);
const last = decodeURIComponent(segs[segs.length - 1] ?? "");
const m = last.match(/^(?:\d+x\d+_)?([0-9a-f]{16,})(?:_frame_\d+)?\.(?:jpe?g|png|webp|gif|mp4|webm|mov|m4v)$/i);
if (m) out.add(m[1].toLowerCase());
const dir = segs[segs.length - 2];
if (dir && /^[0-9a-f]{16,}$/i.test(dir)) out.add(dir.toLowerCase());
return out;
}
function entryTokens(entry) {
const out = new Set();
const files = entry.raw?.files ?? {};
const urls = [
files.full?.url,
files.preview?.url,
files.source?.url,
...(files.source?.sources ?? []).map((s) => s?.url),
...(entry.raw?.videoSources ?? []).map((s) => s?.url),
].filter(Boolean);
for (const u of urls) for (const t of fileTokens(u)) out.add(t);
return out;
}
function rowTokens(row) {
const out = new Set();
for (const el of row.querySelectorAll("img, video, source")) {
const urls = [el.currentSrc || "", el.getAttribute("src") || "", el.tagName === "VIDEO" ? el.poster || "" : ""];
for (const u of urls.filter(Boolean)) for (const t of fileTokens(u)) out.add(t);
}
return out;
}
function renderChat() {
try {
diagTick();
const chatId = currentChatId();
const st = chatId ? chatState.get(chatId) : null;
const rows = [...document.querySelectorAll(CHAT_ROW_SEL)];
for (let ri = 0; ri < rows.length; ri++) {
const row = rows[ri];
let bar = row.querySelector(":scope > .ofsaver-chat-pills");
if (!bar) {
bar = document.createElement("div");
bar.className = "ofsaver-chat-pills";
bar.style.cssText = "display:flex;flex-wrap:wrap;gap:4px;align-items:center;margin:6px 0 2px;width:100%;";
row.appendChild(bar);
}
// positional mapping: rows are chronological, aligned from the bottom
const rowEntries = [];
if (st && st.chrono.length) {
const msg = st.chrono[Math.max(0, st.chrono.length - rows.length + ri)];
if (msg) {
for (const mm of msg.media) {
let entry = media.get(mm.id) ?? media.get(Number(mm.id));
// the sender's handle names the file — the store entry may lack
// it, but the batch always knows who sent the message
if (entry && !entry.username && msg.username) entry = { ...entry, username: msg.username };
rowEntries.push({ mm, entry });
}
}
}
// fallback: match by file-hash tokens between row thumbs and index
if (!rowEntries.length) {
const rowTok = rowTokens(row);
if (rowTok.size) {
for (const e of media.values()) {
const toks = entryTokens(e);
if (!toks.size) continue;
let hit = false;
for (const t of toks) if (rowTok.has(t)) { hit = true; break; }
if (hit && !rowEntries.some((x) => String(x.entry?.id) === String(e.id))) rowEntries.push({ mm: null, entry: e });
}
}
}
const downloadable = rowEntries.map((r) => r.entry).filter((e) => e && qualityOptions(e).length);
if (downloadable.length) attachPills(bar, downloadable, "c" + String(downloadable[0].id));
// locked media (no files in the API) — one pill per media, with the
// video duration like ofcheck shows
for (const r of rowEntries) {
if (r.entry && qualityOptions(r.entry).length) continue;
const key = `l_${r.mm?.id ?? "h" + String(r.entry?.id ?? "")}`;
const btn = pillEl(key);
if (!btn.isConnected) {
const dur = r.mm && fmtDuration(r.mm.duration);
btn.innerHTML =
`<span style="background:#ececee;border-radius:8px;color:#8b8b93;font:600 12px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:4px;margin-left:8px;vertical-align:middle">Locked${dur ? ` <span style="color:#e5484d;font-size:11px">${dur}</span>` : ""}</span>`;
bar.appendChild(btn);
}
}
// row has media we never saw in any batch — generic locked marker
const hasMedia = row.matches(".m-has-media") || row.querySelector(".b-chat__message__media-wrapper");
if (!rowEntries.length && hasMedia && !row.dataset.ofsaverLocked) {
row.dataset.ofsaverLocked = "1";
const lbtn = document.createElement("div");
lbtn.dataset.ofsaverMedia = "locked";
lbtn.innerHTML =
`<span style="background:#ececee;border-radius:8px;color:#8b8b93;font:600 12px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;margin-left:8px;vertical-align:middle">Locked</span>`;
bar.appendChild(lbtn);
}
}
} catch (e) {
console.log("[ofsaver] renderChat error:", e.message);
}
}
})();