Spaces:
Running

oops / clip-store.js
OmarLaymounNvidia's picture
Publish the 13-round game with individual voting rooms
3ed011e verified
Raw History Blame Contribute Delete
2.38 kB
(function (global) {
'use strict';
const clips = new Map();
function decode(data) {
const raw = atob(data), bytes = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
return URL.createObjectURL(new Blob([bytes], {type: 'video/mp4'}));
}
// Classic scripts retain the host's normal authentication inside its sandbox.
// Each immutable payload is downloaded completely before a local video is made.
global.__hwmClipReady = (key, data) => {
const entry = clips.get(key);
if (!entry || entry.done) return;
try {
entry.url = decode(data);
entry.finish();
entry.resolve(entry.url);
} catch (_) {
entry.fail(new Error('This clip could not load.'));
}
};
function load(segment) {
const key = typeof segment === 'string' ? segment : segment.key;
if (clips.has(key)) return clips.get(key).promise;
if (typeof segment === 'string') {
const url = decode(segment);
const entry = {url, promise: Promise.resolve(url)};
clips.set(key, entry);
return entry.promise;
}
const entry = {};
entry.promise = new Promise((resolve, reject) => {
let script, timer, attempt = 0;
entry.resolve = resolve;
entry.finish = () => { entry.done = true; clearTimeout(timer); if (script) script.remove(); };
entry.fail = error => { if (entry.done) return; entry.finish(); clips.delete(key); reject(error); };
const request = () => {
script = document.createElement('script');
script.async = true;
script.src = segment.bundle;
script.onload = () => { if (!entry.url) entry.fail(new Error('This clip could not load.')); };
script.onerror = () => {
if (entry.done) return;
script.remove();
if (attempt++ === 0) request();
else entry.fail(new Error('This clip could not load. Check your connection.'));
};
document.head.append(script);
};
entry.start = () => {
timer = setTimeout(() => entry.fail(new Error('This clip is taking too long to load.')), 90000);
request();
};
});
clips.set(key, entry);
entry.start();
return entry.promise;
}
global.ClipStore = Object.freeze({
load,
warm(segment) { try { load(segment).catch(() => {}); } catch (_) {} }
});
})(window);