File size: 2,663 Bytes
54a51e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Shared loader for sceneSample: media lives in a gated dataset and is fetched
// with the viewer's own HF OAuth token (scope: gated-repos). Nothing here is secret.
(function () {
  const REPO = 'faradayfuture/sceneSample';
  const BASE = 'https://huggingface.co/datasets/' + REPO + '/resolve/main/';
  const KEY = 'sceneSample_oauth';
  const cache = new Map();

  const KEYS = [KEY, 'sv_oauth'];   // shared with the Sample Viewer sign-in page (gate.html)
  function session() {
    for (const k of KEYS) {
      try {
        const s = JSON.parse(localStorage.getItem(k) || 'null');
        if (s && s.accessToken && (!s.accessTokenExpiresAt || new Date(s.accessTokenExpiresAt) > new Date())) return s;
      } catch (e) {}
    }
    return null;
  }
  function save(s) { for (const k of KEYS) { try { localStorage.setItem(k, JSON.stringify(s)); } catch (e) {} } }
  function clear() { for (const k of KEYS) { try { localStorage.removeItem(k); } catch (e) {} } }

  const nativeFetch = window.fetch.bind(window);

  async function get(path) {
    const s = session();
    const r = await nativeFetch(BASE + path, { headers: s ? { Authorization: 'Bearer ' + s.accessToken } : {} });
    if (!r.ok) { const e = new Error(path + ' → HTTP ' + r.status); e.status = r.status; throw e; }
    return r;
  }
  function blobURL(path) {
    if (!cache.has(path)) cache.set(path, get(path).then(r => r.blob()).then(b => URL.createObjectURL(b)));
    return cache.get(path);
  }

  // Map a URL on this Space under /sceneSample/ to a dataset path, else null.
  function datasetPath(u) {
    let url;
    try { url = new URL(typeof u === 'string' ? u : u.url, location.href); } catch (e) { return null; }
    if (url.origin !== location.origin) return null;
    const m = url.pathname.match(/\/sceneSample\/((?:b2|b3)\/data\/.+)$/);
    return m ? decodeURIComponent(m[1]) : null;
  }
  // Viewers keep their original relative fetches; redirect data files to the dataset.
  window.fetch = function (u, opts) {
    const p = datasetPath(u);
    return p ? get(p) : nativeFetch(u, opts);
  };

  async function hydrate(root) {
    const els = [...(root || document).querySelectorAll('[data-ss-src],[data-ss-poster],[data-ss-bg]')];
    await Promise.all(els.map(async el => {
      try {
        if (el.dataset.ssPoster) el.poster = await blobURL(el.dataset.ssPoster);
        if (el.dataset.ssBg) el.style.backgroundImage = 'url(' + await blobURL(el.dataset.ssBg) + ')';
        if (el.dataset.ssSrc) el.src = await blobURL(el.dataset.ssSrc);
      } catch (e) { console.warn(e); }
    }));
  }

  window.SS = { REPO, session, save, clear, get, blobURL, hydrate };
})();