Files
sdk/src/health.js

78 lines
1.9 KiB
JavaScript

const MOVIE_PROBE_ID = "936075";
const TV_PROBE_ID = "37854";
const TV_PROBE_SEASON = "1";
const TV_PROBE_EPISODE = "1";
const withTimeout = (promise, ms) =>
Promise.race([
promise,
new Promise(resolve => setTimeout(() => resolve(null), ms))
]);
async function withRetry(fn, attempts = 2, delay = 300) {
for (let i = 0; i < attempts; i++) {
try {
const result = await fn();
if (result != null) return result;
} catch (err) {
if (i === attempts - 1) throw err;
await new Promise(resolve =>
setTimeout(resolve, delay + Math.random() * delay * 0.5)
);
}
}
return null;
}
function hasStream(result) {
const urls = [
result?.url,
...(result?.allUrls || []).map(item => item?.url)
];
return urls.some(url =>
typeof url === "string" && url.startsWith("http")
);
}
export async function probeSource(sdk, cfg, mod) {
const audio = /dub$/.test(cfg.key) ? "dub" : "sub";
const start = Date.now();
const test = async (id, s = null, e = null) => {
const streamArgs = {
id,
s,
e,
clientIP: null,
absoluteBase: null,
audio,
sdk,
config: cfg,
};
const result = await withTimeout(
withRetry(
() => mod.getStream(streamArgs),
cfg.retries,
300
),
cfg.timeout
);
return hasStream(result);
};
const [movie, tv] = await Promise.all([
test(MOVIE_PROBE_ID),
test(TV_PROBE_ID, TV_PROBE_SEASON, TV_PROBE_EPISODE)
]);
return {
ok: movie || tv,
movie,
tv,
ms: Date.now() - start
};
}