Null-DRM-Official/apps/streamd/internal/ui/static/js/api.js
404errordeveloper 8fc7e4c0b8 streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
2026-10-10 18:05:51 +02:00

187 lines
7.1 KiB
JavaScript

// API client. Carries the CSRF token on mutations and routes a 401 back to
// the sign-in screen rather than leaving a half-dead page.
let csrfToken = "";
const onUnauthorized = [];
export function setCSRF(token) {
csrfToken = token || "";
}
export function getCSRF() {
return csrfToken;
}
/** Register a callback for when the session turns out to be gone. */
export function onAuthLost(fn) {
onUnauthorized.push(fn);
}
export class ApiError extends Error {
constructor(message, status, body) {
super(message);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
async function request(method, path, body, opts = {}) {
const headers = {};
let payload;
if (body !== undefined && body !== null) {
headers["Content-Type"] = "application/json";
payload = JSON.stringify(body);
}
// The session cookie is HttpOnly, so the double-submit token is what proves
// this request came from the dashboard and not from another origin.
if (method !== "GET" && method !== "HEAD" && csrfToken) {
headers["X-CSRF-Token"] = csrfToken;
}
const res = await fetch(path, {
method,
headers,
body: payload,
credentials: "same-origin",
signal: opts.signal,
});
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
if (res.status === 401) {
// allow401 lets boot/login/setup read the JSON body (e.g. needs_setup)
// without treating it as a hard failure or kicking the session.
if (opts.allow401) return data;
for (const fn of onUnauthorized) fn(data);
throw new ApiError((data && data.error) || "not signed in", 401, data);
}
if (!res.ok) {
const msg = (data && data.error) || res.statusText || `request failed (${res.status})`;
throw new ApiError(msg, res.status, data);
}
return data;
}
export const api = {
get: (p, opts) => request("GET", p, null, opts),
post: (p, b, opts) => request("POST", p, b ?? {}, opts),
patch: (p, b, opts) => request("PATCH", p, b ?? {}, opts),
put: (p, b, opts) => request("PUT", p, b ?? {}, opts),
del: (p, opts) => request("DELETE", p, null, opts),
// --- session ---
me: () => request("GET", "/api/me", null, { allow401: true }),
login: (username, password) => request("POST", "/api/login", { username, password }, { allow401: true }),
setup: (setup_token, username, password) =>
request("POST", "/api/setup", { setup_token, username, password }, { allow401: true }),
logout: () => request("POST", "/api/logout", {}),
setupState: () => request("GET", "/api/setup", null, { allow401: true }),
// --- streams ---
health: () => request("GET", "/api/health", null, { allow401: true }),
overview: () => api.get("/api/overview"),
streams: () => api.get("/api/streams"),
stream: (id, reveal) => api.get(`/api/streams/${id}${reveal ? "?reveal=1" : ""}`),
createStream: (body) => api.post("/api/streams", body),
patchStream: (id, body) => api.patch(`/api/streams/${id}`, body),
deleteStream: (id) => api.del(`/api/streams/${id}`),
action: (id, what) => api.post(`/api/streams/${id}/${what}`),
bulk: (ids, action) => api.post("/api/streams/bulk", { ids, action }),
duplicate: (id, body) => api.post(`/api/streams/${id}/duplicate`, body),
probe: (id, mpd) => api.post(`/api/streams/${id}/probe`, mpd ? { mpd } : {}),
capture: (id) => api.post(`/api/streams/${id}/capture`),
credentials: (id, body) => api.post(`/api/streams/${id}/credentials`, body),
// --- history ---
events: (id, limit = 100) => api.get(`/api/streams/${id}/events?limit=${limit}`),
metrics: (id, window = "1h") => api.get(`/api/streams/${id}/metrics?window=${encodeURIComponent(window)}`),
logs: (id, source, variant) => {
const q = new URLSearchParams({ source, tail: "600" });
if (variant) q.set("variant", variant);
return api.get(`/api/streams/${id}/logs?${q}`);
},
// --- schedules ---
schedules: (id) => api.get(`/api/streams/${id}/schedules`),
allSchedules: () => api.get("/api/schedules"),
upcoming: (limit = 10) => api.get(`/api/schedules?upcoming=1&limit=${limit}`),
createSchedule: (id, body) => api.post(`/api/streams/${id}/schedules`, body),
patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body),
deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`),
// --- egress tunnels ---
egress: () => api.get("/api/egress"),
egressProfiles: () => api.get("/api/egress"),
egressProfile: (name) => api.get(`/api/egress/${encodeURIComponent(name)}`),
createEgress: (body) => api.post("/api/egress", body),
saveEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body),
updateEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body),
deleteEgress: (name) => api.del(`/api/egress/${encodeURIComponent(name)}`),
egressUp: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/up`),
egressDown: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/down`),
egressTest: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/test`),
egressConf: (name, conf) =>
api.put(`/api/egress/${encodeURIComponent(name)}/conf`, { conf }),
// --- admin ---
settings: () => api.get("/api/settings"),
saveSettings: (body) => api.put("/api/settings", body),
users: () => api.get("/api/users"),
createUser: (body) => api.post("/api/users", body),
patchUser: (id, body) => api.patch(`/api/users/${id}`, body),
deleteUser: (id) => api.del(`/api/users/${id}`),
setPassword: (id, body) => api.post(`/api/users/${id}/password`, body),
apiKeys: () => api.get("/api/apikeys"),
createKey: (body) => api.post("/api/apikeys", body),
revokeKey: (id) => api.del(`/api/apikeys/${id}`),
audit: (limit = 200) => api.get(`/api/audit?limit=${limit}`),
agents: () => api.get("/api/agents"),
apps: () => api.get("/api/apps"),
// --- modules ---
modules: () => api.get("/api/modules"),
module: (name, includeYaml) =>
api.get(`/api/modules/${encodeURIComponent(name)}${includeYaml ? "?include=yaml" : ""}`),
saveModuleYAML: (name, yaml) =>
api.put(`/api/modules/${encodeURIComponent(name)}`, { yaml }),
deleteModule: (name) => api.del(`/api/modules/${encodeURIComponent(name)}`),
uploadModuleZip: async (file, name) => {
const fd = new FormData();
fd.append("file", file, file.name || "module.zip");
if (name) fd.append("name", name);
const headers = {};
if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
const res = await fetch("/api/modules/upload", {
method: "POST",
headers,
body: fd,
credentials: "same-origin",
});
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
if (res.status === 401) {
for (const fn of onUnauthorized) fn(data);
throw new ApiError((data && data.error) || "not signed in", 401, data);
}
if (!res.ok) {
const msg = (data && data.error) || res.statusText || `upload failed (${res.status})`;
throw new ApiError(msg, res.status, data);
}
return data;
},
};