Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

5.8 KB
Raw Blame
// Generated by build:capture-runtime from x-video-capture.js and resource-policy.js.
(function installXVideoObserver({ timeoutMs, maxBytes, maxMedia }) {
  const key = "__PROMPTDIRECTOR_X_VIDEO__";
  const postId = /^\/(?:[^/]+\/status|i\/web\/status)\/(\d+)/u.exec(location.pathname)?.[1];
  if (!postId || !/(^|\.)(x|twitter)\.com$/u.test(location.hostname) || globalThis[key]) return;
  const state = { postId, media: [], done: false };
  globalThis[key] = state;
  const mediaUrl = (value) => {
    try {
      const url = new URL(value);
      return url.protocol === "https:" && url.hostname === "video.twimg.com" ? url.href : "";
    } catch { return ""; }
  };
  const ingest = (payload) => {
    if (state.done) return;
    const pending = [payload];
    while (pending.length) {
      const node = pending.pop();
      if (!node || typeof node !== "object") continue;
      const legacy = node.legacy || node;
      if (String(node.rest_id || legacy.id_str || "") === postId) {
        const own = node.result || node;
        const quoted = own.quoted_status_result?.result || own.quoted_tweet_results?.result;
        const media = [own, quoted].filter(Boolean).flatMap(tweet => {
          const details = tweet.legacy || tweet;
          const ownerId = String(tweet.rest_id || details.id_str || '');
          return (tweet.media_entities2 || details.extended_entities?.media || []).filter(item =>
            !item.source_status_id_str || item.source_status_id_str === ownerId).flatMap(item => {
            let workUrl = '';
            if (ownerId !== postId) {
              try {
                const url = new URL(item.expanded_url);
                if (url.protocol !== 'https:' || !/^(?:www\.)?(?:x|twitter)\.com$/u.test(url.hostname)
                  || url.username || url.password || url.pathname.match(/^\/[^/]+\/status\/(\d+)\/video\/\d+$/u)?.[1] !== ownerId) return [];
                url.pathname = url.pathname.replace(/\/video\/\d+$/u, ''); url.search = ''; url.hash = '';
                workUrl = url.href;
              } catch { return []; }
            }
            const variants = (item.video_info?.variants || []).flatMap(variant => {
              const url = mediaUrl(variant.url);
              return url && ['video/mp4', 'application/x-mpegURL'].includes(variant.content_type)
                && !/\/(?:vid|aud)\/[^/]+\/\d+\/\d+\//u.test(new URL(url).pathname)
                ? [{ url, mimeType: variant.content_type, bitrate: Number(variant.bitrate) || 0 }] : [];
            });
            variants.sort((a, b) => Number(b.mimeType === 'video/mp4') - Number(a.mimeType === 'video/mp4') || b.bitrate - a.bitrate);
            return variants.length ? [{ id: String(item.id_str || ''), posterUrl: String(item.media_url_https || ''), variants,
              ...(workUrl ? { workUrl } : {}) }] : [];
          });
        }).slice(0, maxMedia);
        if (media.length) { state.media = media; state.stop(); return; }
      }
      // A quote is its own post; matching by ID above prevents unrelated reply/quote substitution.
      pending.push(...Object.values(node).filter(value => value && typeof value === "object"));
    }
  };
  const isResponseUrl = (value) => {
    try {
      const url = new URL(value, location.href);
      return url.origin === location.origin && url.pathname.startsWith("/i/api/");
    } catch { return false; }
  };
  const parse = (text) => {
    if (!state.done && typeof text === "string" && text.length <= maxBytes) {
      try { ingest(JSON.parse(text)); } catch { /* Unrelated or non-JSON response. */ }
    }
  };
  const originalFetch = globalThis.fetch;
  const Xhr = globalThis.XMLHttpRequest;
  const originalOpen = Xhr?.prototype.open;
  const originalSend = Xhr?.prototype.send;
  const requests = new WeakSet();
  const observedFetch = async function (...args) {
    const response = await originalFetch.apply(this, args);
    if (!state.done && response.ok && isResponseUrl(response.url || args[0]?.url || args[0])) {
      const copy = response.clone();
      (async () => {
        const reader = copy.body.getReader();
        const chunks = []; let bytes = 0;
        try {
          while (!state.done) {
            const part = await reader.read();
            if (part.done) break;
            bytes += part.value.byteLength;
            if (bytes > maxBytes) return;
            chunks.push(part.value);
          }
          if (!state.done) parse(await new Blob(chunks).text());
        } finally { await reader.cancel().catch(() => undefined); }
      })().catch(() => undefined);
    }
    return response;
  };
  const observedOpen = function (method, url, ...rest) {
    requests.delete(this);
    if (isResponseUrl(url)) requests.add(this);
    return originalOpen.call(this, method, url, ...rest);
  };
  const observedSend = function (...args) {
    if (requests.has(this)) this.addEventListener("loadend", () => {
      if (state.done || this.status < 200 || this.status >= 300) return;
      try {
        if (this.responseType === "json") parse(JSON.stringify(this.response));
        else if (!this.responseType || this.responseType === "text") parse(this.responseText);
      } catch { /* Page response type changed. */ }
    }, { once: true });
    return originalSend.apply(this, args);
  };
  let timer;
  state.stop = () => {
    state.done = true;
    clearTimeout(timer);
    if (globalThis.fetch === observedFetch) globalThis.fetch = originalFetch;
    if (Xhr?.prototype.open === observedOpen) Xhr.prototype.open = originalOpen;
    if (Xhr?.prototype.send === observedSend) Xhr.prototype.send = originalSend;
  };
  if (originalFetch) globalThis.fetch = observedFetch;
  if (Xhr) { Xhr.prototype.open = observedOpen; Xhr.prototype.send = observedSend; }
  timer = setTimeout(state.stop, timeoutMs);
})({"timeoutMs":30000,"maxBytes":67108864,"maxMedia":9007199254740991});