@x-tech-laboratories/x-app 0.135.0 → 0.136.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -4
- package/dist/app/desktop.d.ts +8 -2
- package/dist/app/desktop.js +25 -0
- package/dist/app/protocol.d.ts +19 -1
- package/dist/app/protocol.js +1 -1
- package/dist/app/server.js +5 -0
- package/dist/app/services.d.ts +1 -0
- package/dist/app/web/app_page.js +3 -0
- package/dist/app/web/density.d.ts +6 -0
- package/dist/app/web/density.js +40 -0
- package/dist/app/web/hosts.js +2 -0
- package/dist/app/web/portal.js +8 -0
- package/dist/app/web/settings_page.js +5 -1
- package/dist/derived_ids.d.ts +1 -0
- package/dist/derived_ids.js +35 -0
- package/dist/mpv.d.ts +2 -53
- package/dist/mpv.js +3 -66
- package/dist/play_queue.d.ts +110 -0
- package/dist/play_queue.js +380 -0
- package/dist/playback.d.ts +53 -0
- package/dist/playback.js +69 -0
- package/dist/playlist_files.d.ts +17 -0
- package/dist/playlist_files.js +133 -0
- package/dist/server/account_sign_in.d.ts +2 -0
- package/dist/server/account_sign_in.js +27 -0
- package/dist/server/file_ranges.d.ts +11 -0
- package/dist/server/file_ranges.js +80 -0
- package/dist/server/media_links.d.ts +12 -0
- package/dist/server/media_links.js +33 -0
- package/dist/web/audio_engine.d.ts +54 -0
- package/dist/web/audio_engine.js +197 -0
- package/package.json +2 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Playlist files: M3U and M3U8, PLS and XSPF read into the paths they list, and written from a playlist's entries. No
|
|
2
|
+
// `node:` or DOM imports, so a page, a phone and Node read them alike.
|
|
3
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
4
|
+
import { XMLBuilder, XMLParser } from "fast-xml-parser";
|
|
5
|
+
export const playlist_extensions = { m3u: "m3u", m3u8: "m3u", pls: "pls", xspf: "xspf" };
|
|
6
|
+
export function playlist_format(path) {
|
|
7
|
+
const extension = /\.([^./\\]+)$/.exec(path)?.[1]?.toLowerCase();
|
|
8
|
+
return extension ? (playlist_extensions[extension] ?? null) : null;
|
|
9
|
+
}
|
|
10
|
+
// ── Paths ────────────────────────────────────────────────────────────────────
|
|
11
|
+
const is_absolute = (path) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
|
|
12
|
+
const folder_of = (path) => path.slice(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
|
|
13
|
+
// An entry as a path on the playlist's computer: a file URL decoded, a relative path joined to the playlist's folder;
|
|
14
|
+
// other URLs as they are.
|
|
15
|
+
export function resolve_entry(entry, playlist_path) {
|
|
16
|
+
const trimmed = entry.trim();
|
|
17
|
+
if (/^file:\/\//i.test(trimmed)) {
|
|
18
|
+
const path = decodeURIComponent(trimmed.replace(/^file:\/\/(localhost)?/i, ""));
|
|
19
|
+
return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
|
|
20
|
+
}
|
|
21
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) || is_absolute(trimmed))
|
|
22
|
+
return trimmed;
|
|
23
|
+
const separator = playlist_path.includes("\\") && !playlist_path.includes("/") ? "\\" : "/";
|
|
24
|
+
const parts = `${folder_of(playlist_path)}${separator}${trimmed}`.split(/[\\/]/);
|
|
25
|
+
const kept = [];
|
|
26
|
+
for (const part of parts) {
|
|
27
|
+
if (part === ".." && kept.length > 1)
|
|
28
|
+
kept.pop();
|
|
29
|
+
else if (part !== ".")
|
|
30
|
+
kept.push(part);
|
|
31
|
+
}
|
|
32
|
+
return kept.join(separator);
|
|
33
|
+
}
|
|
34
|
+
const lines_of = (text) => text
|
|
35
|
+
.replace(/^/, "")
|
|
36
|
+
.split(/\r?\n/)
|
|
37
|
+
.map((line) => line.trim());
|
|
38
|
+
function read_m3u(text, path) {
|
|
39
|
+
let name = null;
|
|
40
|
+
const entries = [];
|
|
41
|
+
for (const line of lines_of(text)) {
|
|
42
|
+
if (line.startsWith("#PLAYLIST:"))
|
|
43
|
+
name = line.slice("#PLAYLIST:".length).trim() || null;
|
|
44
|
+
else if (line !== "" && !line.startsWith("#"))
|
|
45
|
+
entries.push(resolve_entry(line, path));
|
|
46
|
+
}
|
|
47
|
+
return { name, entries };
|
|
48
|
+
}
|
|
49
|
+
function read_pls(text, path) {
|
|
50
|
+
const files = [];
|
|
51
|
+
for (const line of lines_of(text)) {
|
|
52
|
+
const file = /^File(\d+)=(.*)$/i.exec(line);
|
|
53
|
+
if (file && file[2].trim() !== "")
|
|
54
|
+
files.push([Number(file[1]), resolve_entry(file[2], path)]);
|
|
55
|
+
}
|
|
56
|
+
return { name: null, entries: files.sort((first, second) => first[0] - second[0]).map(([, entry]) => entry) };
|
|
57
|
+
}
|
|
58
|
+
function read_xspf(text, path) {
|
|
59
|
+
const parser = new XMLParser({ ignoreAttributes: true, isArray: (name) => name === "track" || name === "location", parseTagValue: false });
|
|
60
|
+
const document = parser.parse(text);
|
|
61
|
+
if (!document.playlist)
|
|
62
|
+
throw new Error("this is not an XSPF playlist");
|
|
63
|
+
const tracks = document.playlist.trackList?.track ?? [];
|
|
64
|
+
const entries = tracks.flatMap((track) => {
|
|
65
|
+
const location = track.location?.[0];
|
|
66
|
+
return typeof location === "string" && location.trim() !== "" ? [resolve_entry(location, path)] : [];
|
|
67
|
+
});
|
|
68
|
+
const title = document.playlist.title;
|
|
69
|
+
return { name: typeof title === "string" && title.trim() !== "" ? title.trim() : null, entries };
|
|
70
|
+
}
|
|
71
|
+
// The entries of a playlist file, its format known by the path's extension.
|
|
72
|
+
export function read_playlist_file(text, path) {
|
|
73
|
+
const format = playlist_format(path);
|
|
74
|
+
if (format === "pls")
|
|
75
|
+
return read_pls(text, path);
|
|
76
|
+
if (format === "xspf")
|
|
77
|
+
return read_xspf(text, path);
|
|
78
|
+
if (format === "m3u")
|
|
79
|
+
return read_m3u(text, path);
|
|
80
|
+
throw new Error("a playlist file ends in .m3u, .m3u8, .pls or .xspf");
|
|
81
|
+
}
|
|
82
|
+
// The file's name without its folder or extension, for a playlist that names none.
|
|
83
|
+
export function name_from_path(path) {
|
|
84
|
+
return path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1).replace(/\.[^.]+$/, "");
|
|
85
|
+
}
|
|
86
|
+
const shown_name = (entry) => [entry.artist, entry.title].filter((part) => part).join(" - ");
|
|
87
|
+
const seconds = (entry) => (entry.length_ms === null ? -1 : Math.round(entry.length_ms / 1000));
|
|
88
|
+
const one_line = (text) => text.replace(/[\r\n]+/g, " ");
|
|
89
|
+
function write_m3u(name, entries) {
|
|
90
|
+
const lines = ["#EXTM3U", `#PLAYLIST:${one_line(name)}`];
|
|
91
|
+
for (const entry of entries)
|
|
92
|
+
lines.push(`#EXTINF:${seconds(entry)},${one_line(shown_name(entry))}`, entry.path);
|
|
93
|
+
return `${lines.join("\n")}\n`;
|
|
94
|
+
}
|
|
95
|
+
function write_pls(entries) {
|
|
96
|
+
const lines = ["[playlist]"];
|
|
97
|
+
entries.forEach((entry, index) => {
|
|
98
|
+
const number = index + 1;
|
|
99
|
+
lines.push(`File${number}=${entry.path}`, `Title${number}=${one_line(shown_name(entry))}`, `Length${number}=${seconds(entry)}`);
|
|
100
|
+
});
|
|
101
|
+
lines.push(`NumberOfEntries=${entries.length}`, "Version=2");
|
|
102
|
+
return `${lines.join("\n")}\n`;
|
|
103
|
+
}
|
|
104
|
+
// A path as a file URL, each part escaped.
|
|
105
|
+
function file_url(path) {
|
|
106
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path))
|
|
107
|
+
return path;
|
|
108
|
+
const slashed = path.replace(/\\/g, "/");
|
|
109
|
+
return `file://${slashed.startsWith("/") ? "" : "/"}${slashed
|
|
110
|
+
.split("/")
|
|
111
|
+
.map(encodeURIComponent)
|
|
112
|
+
.join("/")
|
|
113
|
+
.replace(/^\/([A-Za-z])%3A/, "/$1:")}`;
|
|
114
|
+
}
|
|
115
|
+
function write_xspf(name, entries) {
|
|
116
|
+
const builder = new XMLBuilder({ ignoreAttributes: false, format: true, attributeNamePrefix: "@" });
|
|
117
|
+
const track = (entry) => ({
|
|
118
|
+
location: file_url(entry.path),
|
|
119
|
+
...(entry.title ? { title: entry.title } : {}),
|
|
120
|
+
...(entry.artist ? { creator: entry.artist } : {}),
|
|
121
|
+
...(entry.length_ms !== null ? { duration: entry.length_ms } : {}),
|
|
122
|
+
});
|
|
123
|
+
const body = builder.build({ playlist: { "@version": "1", "@xmlns": "http://xspf.org/ns/0/", title: name, trackList: { track: entries.map(track) } } });
|
|
124
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n${body}`;
|
|
125
|
+
}
|
|
126
|
+
// A playlist file of the format given, naming each entry's path with its artist, title and length where the format can.
|
|
127
|
+
export function write_playlist_file(format, name, entries) {
|
|
128
|
+
if (format === "pls")
|
|
129
|
+
return write_pls(entries);
|
|
130
|
+
if (format === "xspf")
|
|
131
|
+
return write_xspf(name, entries);
|
|
132
|
+
return write_m3u(name, entries);
|
|
133
|
+
}
|
|
@@ -3,6 +3,7 @@ import type { PageOnlyCalls } from "../api_spec.ts";
|
|
|
3
3
|
import { type AccountPrefsOptions } from "./account_prefs.ts";
|
|
4
4
|
import { type AccountStore, type TokenKind, type TokenScopeInfo } from "./account_store.ts";
|
|
5
5
|
import type { DeclaredToken } from "./declared_tokens.ts";
|
|
6
|
+
import type { MediaLinks } from "./media_links.ts";
|
|
6
7
|
import type { OidcClient } from "./oidc.ts";
|
|
7
8
|
export { is_user_or_device } from "./viewers.ts";
|
|
8
9
|
export interface Viewer {
|
|
@@ -51,6 +52,7 @@ export interface AccountSignInOptions {
|
|
|
51
52
|
address_try_window_seconds?: number;
|
|
52
53
|
second_factor_from?: string | null;
|
|
53
54
|
prefs?: AccountPrefsOptions | null;
|
|
55
|
+
media_links?: MediaLinks | null;
|
|
54
56
|
}
|
|
55
57
|
export declare function calls_under(...prefixes: string[]): (method: string, path: string) => string | null;
|
|
56
58
|
export declare function token_refusal(viewer: Pick<Viewer, "scope">, call: string | null): string;
|
|
@@ -69,6 +69,20 @@ export async function register_accounts(app, options) {
|
|
|
69
69
|
path: "/", httpOnly: true, sameSite: "strict", secure: is_secure(request),
|
|
70
70
|
...(remember ? { maxAge: remembered_seconds ?? longest_cookie_seconds } : {}),
|
|
71
71
|
});
|
|
72
|
+
// A GET of a media path with a link made for it, as the user it was made for, reading only.
|
|
73
|
+
const media_links = options.media_links ?? null;
|
|
74
|
+
// Making a link only lets its path be read, so a token that only reads may make one.
|
|
75
|
+
if (media_links !== null)
|
|
76
|
+
read_only_paths.add(`${prefix}/media_link`);
|
|
77
|
+
const media_viewer = (request) => {
|
|
78
|
+
if (media_links === null || (request.method !== "GET" && request.method !== "HEAD"))
|
|
79
|
+
return null;
|
|
80
|
+
const query = request.url.indexOf("?");
|
|
81
|
+
const link = query < 0 ? null : new URLSearchParams(request.url.slice(query + 1)).get("link");
|
|
82
|
+
const name = link === null ? null : media_links.check(path_of(request), link);
|
|
83
|
+
const user = name === null ? null : accounts.user(name);
|
|
84
|
+
return user === null ? null : as_viewer(user, "token", true, null);
|
|
85
|
+
};
|
|
72
86
|
const identify = (request) => {
|
|
73
87
|
const secret = request.cookies[cookie_name];
|
|
74
88
|
if (secret) {
|
|
@@ -90,6 +104,9 @@ export async function register_accounts(app, options) {
|
|
|
90
104
|
return { name: declared.name, role: declared.role, access: declared.limited_to, via: "token", read_only: declared.read_only, credential_id: null, declared, token_kind: "program" };
|
|
91
105
|
}
|
|
92
106
|
}
|
|
107
|
+
const media = media_viewer(request);
|
|
108
|
+
if (media !== null)
|
|
109
|
+
return media;
|
|
93
110
|
if (proxy !== null && proxy.trusted.has(request.ip)) {
|
|
94
111
|
const header = request.headers[proxy.header.toLowerCase()];
|
|
95
112
|
const user = typeof header === "string" ? accounts.user(header.trim().toLowerCase()) : null;
|
|
@@ -231,6 +248,16 @@ export async function register_accounts(app, options) {
|
|
|
231
248
|
reply.clearCookie(cookie_name, { path: "/" });
|
|
232
249
|
return reply.code(204).send();
|
|
233
250
|
});
|
|
251
|
+
// A link to one media path for an element that cannot send the sign-in, such as <audio>.
|
|
252
|
+
if (media_links !== null) {
|
|
253
|
+
scope.post(`${prefix}/media_link`, async (request, reply) => {
|
|
254
|
+
const body = request.body;
|
|
255
|
+
const path = Array.isArray(body) ? body[0] : body?.path;
|
|
256
|
+
if (typeof path !== "string" || !media_links.allows(path))
|
|
257
|
+
return reply.code(400).send({ error: `A media link is made for a path under ${media_links.prefixes.join(" or ")}.` });
|
|
258
|
+
return { link: `${path}?link=${media_links.sign(path, request.viewer.name)}` };
|
|
259
|
+
});
|
|
260
|
+
}
|
|
234
261
|
// Who is signed in; the page asks when it starts, which also renews a remembered cookie.
|
|
235
262
|
scope.get(routes.me, async (request, reply) => {
|
|
236
263
|
const viewer = request.viewer;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
export declare function media_type(path: string): string;
|
|
3
|
+
export declare function requested_range(header: string | undefined, size: number): {
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
} | "unsatisfiable" | null;
|
|
7
|
+
export interface SendFileOptions {
|
|
8
|
+
type?: string;
|
|
9
|
+
cache_control?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function send_file_ranges(request: FastifyRequest, reply: FastifyReply, path: string, options?: SendFileOptions): Promise<FastifyReply>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// A file on the server's disk sent with HTTP ranges, so an <audio> or <video> element can start anywhere in it and seek
|
|
2
|
+
// without fetching the whole file first: `send_file_ranges` answers one range of bytes with 206, the whole file with 200,
|
|
3
|
+
// HEAD with the size alone, and a range past the end with 416. The route decides which file a request may have; this
|
|
4
|
+
// only sends it.
|
|
5
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
6
|
+
import { createReadStream } from "node:fs";
|
|
7
|
+
import { stat } from "node:fs/promises";
|
|
8
|
+
import { extname } from "node:path";
|
|
9
|
+
// ── Types of media ───────────────────────────────────────────────────────────
|
|
10
|
+
const media_types = {
|
|
11
|
+
".aac": "audio/aac",
|
|
12
|
+
".aif": "audio/aiff",
|
|
13
|
+
".aiff": "audio/aiff",
|
|
14
|
+
".alac": "audio/mp4",
|
|
15
|
+
".flac": "audio/flac",
|
|
16
|
+
".m4a": "audio/mp4",
|
|
17
|
+
".m4b": "audio/mp4",
|
|
18
|
+
".mka": "audio/x-matroska",
|
|
19
|
+
".mkv": "video/x-matroska",
|
|
20
|
+
".mp3": "audio/mpeg",
|
|
21
|
+
".mp4": "video/mp4",
|
|
22
|
+
".oga": "audio/ogg",
|
|
23
|
+
".ogg": "audio/ogg",
|
|
24
|
+
".opus": "audio/ogg",
|
|
25
|
+
".wav": "audio/wav",
|
|
26
|
+
".weba": "audio/webm",
|
|
27
|
+
".webm": "video/webm",
|
|
28
|
+
".wv": "audio/x-wavpack",
|
|
29
|
+
};
|
|
30
|
+
// The media type a file's extension names, or a plain stream of bytes for one it does not.
|
|
31
|
+
export function media_type(path) {
|
|
32
|
+
return media_types[extname(path).toLowerCase()] ?? "application/octet-stream";
|
|
33
|
+
}
|
|
34
|
+
// ── Ranges ───────────────────────────────────────────────────────────────────
|
|
35
|
+
// The one range a Range header asks for in a file of the size given: a whole range, an open end, or the last bytes;
|
|
36
|
+
// null for no header or one asking for several ranges, which then gets the whole file, and "unsatisfiable" for a
|
|
37
|
+
// range past the end.
|
|
38
|
+
export function requested_range(header, size) {
|
|
39
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? "");
|
|
40
|
+
if (!match)
|
|
41
|
+
return null;
|
|
42
|
+
const [, first, last] = match;
|
|
43
|
+
if (first === "" && last === "")
|
|
44
|
+
return null;
|
|
45
|
+
if (first === "") {
|
|
46
|
+
const length = Number(last);
|
|
47
|
+
if (length === 0)
|
|
48
|
+
return "unsatisfiable";
|
|
49
|
+
return { start: Math.max(0, size - length), end: size - 1 };
|
|
50
|
+
}
|
|
51
|
+
const start = Number(first);
|
|
52
|
+
if (start >= size)
|
|
53
|
+
return "unsatisfiable";
|
|
54
|
+
const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
|
|
55
|
+
return end < start ? "unsatisfiable" : { start, end };
|
|
56
|
+
}
|
|
57
|
+
// Sends the file at path, or the range of it the request asks for; a missing file is a 404.
|
|
58
|
+
export async function send_file_ranges(request, reply, path, options = {}) {
|
|
59
|
+
let size;
|
|
60
|
+
try {
|
|
61
|
+
const found = await stat(path);
|
|
62
|
+
if (!found.isFile())
|
|
63
|
+
throw new Error("not a file");
|
|
64
|
+
size = found.size;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return reply.code(404).type("text/plain").send("That file is not on the server.");
|
|
68
|
+
}
|
|
69
|
+
reply.header("accept-ranges", "bytes").header("cache-control", options.cache_control ?? "private, max-age=3600").type(options.type ?? media_type(path));
|
|
70
|
+
const range = requested_range(request.headers.range, size);
|
|
71
|
+
if (range === "unsatisfiable")
|
|
72
|
+
return reply.code(416).header("content-range", `bytes */${size}`).send();
|
|
73
|
+
const { start, end } = range ?? { start: 0, end: size - 1 };
|
|
74
|
+
if (range)
|
|
75
|
+
reply.code(206).header("content-range", `bytes ${start}-${end}/${size}`);
|
|
76
|
+
reply.header("content-length", String(size === 0 ? 0 : end - start + 1));
|
|
77
|
+
if (request.method === "HEAD" || size === 0)
|
|
78
|
+
return reply.send();
|
|
79
|
+
return reply.send(createReadStream(path, { start, end }));
|
|
80
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface MediaLinks {
|
|
2
|
+
readonly prefixes: readonly string[];
|
|
3
|
+
allows: (path: string) => boolean;
|
|
4
|
+
sign: (path: string, user: string, now?: number) => string;
|
|
5
|
+
check: (path: string, link: string, now?: number) => string | null;
|
|
6
|
+
}
|
|
7
|
+
export interface MediaLinkOptions {
|
|
8
|
+
prefixes: readonly string[];
|
|
9
|
+
lifetime_seconds?: number;
|
|
10
|
+
secret?: Uint8Array;
|
|
11
|
+
}
|
|
12
|
+
export declare function create_media_links(options: MediaLinkOptions): MediaLinks;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Links to a server's media that carry their own sign-in, for an <audio> or <video> element, which cannot send a token:
|
|
2
|
+
// a signed-in page asks for a link to one path, such as /api/stream/<id>, and the link lets a GET of that path alone
|
|
3
|
+
// in as that user, read-only, until it runs out. Each link is an HMAC over the path, the user and the moment it ends,
|
|
4
|
+
// keyed by a secret the server makes as it starts, so a restart ends every link.
|
|
5
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
6
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
7
|
+
const base64url = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
8
|
+
export function create_media_links(options) {
|
|
9
|
+
const secret = options.secret ?? randomBytes(32);
|
|
10
|
+
const lifetime = options.lifetime_seconds ?? 12 * 60 * 60;
|
|
11
|
+
const signature = (path, user, ends) => createHmac("sha256", secret).update(`${ends}\n${user}\n${path}`).digest();
|
|
12
|
+
const allows = (path) => options.prefixes.some((prefix) => path.startsWith(prefix) && path.length > prefix.length) && !/[?#]/.test(path) && !path.split("/").includes("..");
|
|
13
|
+
return {
|
|
14
|
+
prefixes: options.prefixes,
|
|
15
|
+
allows,
|
|
16
|
+
sign: (path, user, now = Date.now()) => {
|
|
17
|
+
const ends = Math.floor(now / 1000) + lifetime;
|
|
18
|
+
return `${ends}.${base64url(Buffer.from(user))}.${base64url(signature(path, user, ends))}`;
|
|
19
|
+
},
|
|
20
|
+
check: (path, link, now = Date.now()) => {
|
|
21
|
+
if (!allows(path))
|
|
22
|
+
return null;
|
|
23
|
+
const [ends_text, user_text, given] = link.split(".");
|
|
24
|
+
const ends = Number(ends_text);
|
|
25
|
+
if (!Number.isInteger(ends) || user_text === undefined || given === undefined || ends < Math.floor(now / 1000))
|
|
26
|
+
return null;
|
|
27
|
+
const user = Buffer.from(user_text, "base64url").toString();
|
|
28
|
+
const expected = signature(path, user, ends);
|
|
29
|
+
const presented = Buffer.from(given, "base64url");
|
|
30
|
+
return presented.length === expected.length && timingSafeEqual(presented, expected) ? user : null;
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { EngineListener, LoadOptions, PlaybackEngine } from "../playback.ts";
|
|
2
|
+
export interface AudioLike {
|
|
3
|
+
src: string;
|
|
4
|
+
currentTime: number;
|
|
5
|
+
readonly duration: number;
|
|
6
|
+
volume: number;
|
|
7
|
+
preload: string;
|
|
8
|
+
readonly error: {
|
|
9
|
+
code: number;
|
|
10
|
+
message?: string;
|
|
11
|
+
} | null;
|
|
12
|
+
play(): Promise<void>;
|
|
13
|
+
pause(): void;
|
|
14
|
+
load(): void;
|
|
15
|
+
removeAttribute(name: string): void;
|
|
16
|
+
addEventListener(type: string, listener: () => void): void;
|
|
17
|
+
removeEventListener(type: string, listener: () => void): void;
|
|
18
|
+
}
|
|
19
|
+
export interface AudioEngineOptions {
|
|
20
|
+
make_audio?: () => AudioLike;
|
|
21
|
+
resolve?: (uri: string) => string | Promise<string>;
|
|
22
|
+
position_interval_in_milliseconds?: number;
|
|
23
|
+
}
|
|
24
|
+
export declare class AudioEngine implements PlaybackEngine {
|
|
25
|
+
private readonly listeners;
|
|
26
|
+
private readonly options;
|
|
27
|
+
private audio;
|
|
28
|
+
private next;
|
|
29
|
+
private loaded;
|
|
30
|
+
private volume;
|
|
31
|
+
private state;
|
|
32
|
+
private last_report;
|
|
33
|
+
private detach;
|
|
34
|
+
constructor(options?: AudioEngineOptions);
|
|
35
|
+
private make;
|
|
36
|
+
private emit;
|
|
37
|
+
private set_state;
|
|
38
|
+
private duration_ms;
|
|
39
|
+
private apply_volume;
|
|
40
|
+
private attach;
|
|
41
|
+
private on_time;
|
|
42
|
+
private finish;
|
|
43
|
+
private describe;
|
|
44
|
+
load(uri: string, options?: LoadOptions): Promise<void>;
|
|
45
|
+
preload(uri: string, options?: LoadOptions): Promise<void>;
|
|
46
|
+
play(): Promise<void>;
|
|
47
|
+
pause(): Promise<void>;
|
|
48
|
+
stop(): Promise<void>;
|
|
49
|
+
seek(position_in_milliseconds: number): Promise<void>;
|
|
50
|
+
set_volume(volume: number): Promise<void>;
|
|
51
|
+
subscribe(listener: EngineListener): () => void;
|
|
52
|
+
private drop;
|
|
53
|
+
dispose(): Promise<void>;
|
|
54
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// A PlaybackEngine on the page's own <audio> element, for a page that plays what its server streams, such as a music
|
|
2
|
+
// app in a browser or on a phone, where there is no mpv: the same PlayQueue then runs in the page. A part of a file
|
|
3
|
+
// plays from its start to its end with positions counted from that start, a gain becomes a lower volume (an element
|
|
4
|
+
// cannot play louder than its file), and the next file is fetched ahead on a second element, which takes over when it
|
|
5
|
+
// is loaded, so the join is as short as the browser allows.
|
|
6
|
+
// What MediaError's codes mean, in words for the listener.
|
|
7
|
+
const media_errors = {
|
|
8
|
+
1: "Playing was stopped before the file loaded.",
|
|
9
|
+
2: "The file could not be fetched; check the connection to the server.",
|
|
10
|
+
3: "The file could not be decoded.",
|
|
11
|
+
4: "This file's format cannot be played here.",
|
|
12
|
+
};
|
|
13
|
+
export class AudioEngine {
|
|
14
|
+
listeners = new Set();
|
|
15
|
+
options;
|
|
16
|
+
audio;
|
|
17
|
+
next = null;
|
|
18
|
+
loaded = null;
|
|
19
|
+
volume = 100;
|
|
20
|
+
state = "idle";
|
|
21
|
+
last_report = -Infinity;
|
|
22
|
+
detach = () => undefined;
|
|
23
|
+
constructor(options = {}) {
|
|
24
|
+
this.options = options;
|
|
25
|
+
this.audio = this.make();
|
|
26
|
+
}
|
|
27
|
+
make() {
|
|
28
|
+
const audio = this.options.make_audio?.() ?? new Audio();
|
|
29
|
+
audio.preload = "auto";
|
|
30
|
+
return audio;
|
|
31
|
+
}
|
|
32
|
+
emit = (event, payload) => {
|
|
33
|
+
for (const listener of this.listeners)
|
|
34
|
+
listener(event, payload);
|
|
35
|
+
};
|
|
36
|
+
set_state(state, error) {
|
|
37
|
+
this.state = state;
|
|
38
|
+
this.emit("state", error === undefined ? { state } : { state, error });
|
|
39
|
+
}
|
|
40
|
+
duration_ms() {
|
|
41
|
+
if (!this.loaded)
|
|
42
|
+
return null;
|
|
43
|
+
if (this.loaded.end_ms !== null)
|
|
44
|
+
return this.loaded.end_ms - this.loaded.start_ms;
|
|
45
|
+
const duration = this.audio.duration;
|
|
46
|
+
return Number.isFinite(duration) && duration > 0 ? Math.round(duration * 1000) - this.loaded.start_ms : null;
|
|
47
|
+
}
|
|
48
|
+
apply_volume() {
|
|
49
|
+
this.audio.volume = Math.max(0, Math.min(1, (this.volume / 100) * (this.loaded?.gain ?? 1)));
|
|
50
|
+
}
|
|
51
|
+
// Listens to the element now playing, and stops listening to the one before.
|
|
52
|
+
attach(audio) {
|
|
53
|
+
this.detach();
|
|
54
|
+
const on = {
|
|
55
|
+
playing: () => this.set_state("playing"),
|
|
56
|
+
pause: () => {
|
|
57
|
+
if (this.state === "playing")
|
|
58
|
+
this.set_state("paused");
|
|
59
|
+
},
|
|
60
|
+
timeupdate: () => this.on_time(),
|
|
61
|
+
ended: () => this.finish(),
|
|
62
|
+
error: () => {
|
|
63
|
+
if (!this.loaded)
|
|
64
|
+
return;
|
|
65
|
+
const error = audio.error;
|
|
66
|
+
this.set_state("error", (error && media_errors[error.code]) ?? error?.message ?? "The file could not be played.");
|
|
67
|
+
},
|
|
68
|
+
loadedmetadata: () => {
|
|
69
|
+
if (this.loaded && this.loaded.start_ms > 0 && audio.currentTime * 1000 < this.loaded.start_ms)
|
|
70
|
+
audio.currentTime = this.loaded.start_ms / 1000;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
for (const [type, listener] of Object.entries(on))
|
|
74
|
+
audio.addEventListener(type, listener);
|
|
75
|
+
this.detach = () => {
|
|
76
|
+
for (const [type, listener] of Object.entries(on))
|
|
77
|
+
audio.removeEventListener(type, listener);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
on_time() {
|
|
81
|
+
if (!this.loaded)
|
|
82
|
+
return;
|
|
83
|
+
const absolute = this.audio.currentTime * 1000;
|
|
84
|
+
if (this.loaded.end_ms !== null && absolute >= this.loaded.end_ms) {
|
|
85
|
+
this.finish();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const position = Math.max(0, Math.round(absolute - this.loaded.start_ms));
|
|
89
|
+
const interval = this.options.position_interval_in_milliseconds ?? 250;
|
|
90
|
+
if (Math.abs(position - this.last_report) < interval)
|
|
91
|
+
return;
|
|
92
|
+
this.last_report = position;
|
|
93
|
+
this.emit("position", { position_in_milliseconds: position, duration_in_milliseconds: this.duration_ms() });
|
|
94
|
+
}
|
|
95
|
+
finish() {
|
|
96
|
+
if (this.state === "ended" || !this.loaded)
|
|
97
|
+
return;
|
|
98
|
+
this.audio.pause();
|
|
99
|
+
this.state = "ended";
|
|
100
|
+
this.emit("ended", {});
|
|
101
|
+
}
|
|
102
|
+
async describe(uri, options) {
|
|
103
|
+
return {
|
|
104
|
+
uri: await (this.options.resolve?.(uri) ?? uri),
|
|
105
|
+
start_ms: options?.start_in_milliseconds ?? 0,
|
|
106
|
+
end_ms: options?.end_in_milliseconds ?? null,
|
|
107
|
+
gain: options?.gain_in_decibels == null ? 1 : 10 ** (options.gain_in_decibels / 20),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
async load(uri, options) {
|
|
111
|
+
const loaded = await this.describe(uri, options);
|
|
112
|
+
const ahead = this.next;
|
|
113
|
+
this.next = null;
|
|
114
|
+
// The file before stops without telling the listener it paused.
|
|
115
|
+
this.detach();
|
|
116
|
+
this.audio.pause();
|
|
117
|
+
if (ahead && ahead.loaded.uri === loaded.uri && ahead.loaded.start_ms === loaded.start_ms) {
|
|
118
|
+
// The file fetched ahead takes over.
|
|
119
|
+
this.drop(this.audio);
|
|
120
|
+
this.audio = ahead.audio;
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
if (ahead)
|
|
124
|
+
this.drop(ahead.audio);
|
|
125
|
+
this.audio.src = loaded.uri;
|
|
126
|
+
this.audio.load();
|
|
127
|
+
}
|
|
128
|
+
this.loaded = loaded;
|
|
129
|
+
this.last_report = -Infinity;
|
|
130
|
+
this.attach(this.audio);
|
|
131
|
+
if (loaded.start_ms > 0)
|
|
132
|
+
this.audio.currentTime = loaded.start_ms / 1000;
|
|
133
|
+
this.apply_volume();
|
|
134
|
+
this.set_state("loading");
|
|
135
|
+
}
|
|
136
|
+
async preload(uri, options) {
|
|
137
|
+
const loaded = await this.describe(uri, options);
|
|
138
|
+
if (this.next)
|
|
139
|
+
this.drop(this.next.audio);
|
|
140
|
+
const audio = this.make();
|
|
141
|
+
audio.src = loaded.uri;
|
|
142
|
+
audio.load();
|
|
143
|
+
if (loaded.start_ms > 0)
|
|
144
|
+
audio.currentTime = loaded.start_ms / 1000;
|
|
145
|
+
this.next = { audio, loaded };
|
|
146
|
+
}
|
|
147
|
+
async play() {
|
|
148
|
+
if (!this.loaded)
|
|
149
|
+
return;
|
|
150
|
+
await this.audio.play();
|
|
151
|
+
if (this.state !== "playing")
|
|
152
|
+
this.set_state("playing");
|
|
153
|
+
}
|
|
154
|
+
async pause() {
|
|
155
|
+
if (!this.loaded)
|
|
156
|
+
return;
|
|
157
|
+
this.audio.pause();
|
|
158
|
+
this.set_state("paused");
|
|
159
|
+
}
|
|
160
|
+
async stop() {
|
|
161
|
+
this.loaded = null;
|
|
162
|
+
this.drop(this.audio);
|
|
163
|
+
this.audio = this.make();
|
|
164
|
+
this.set_state("idle");
|
|
165
|
+
}
|
|
166
|
+
async seek(position_in_milliseconds) {
|
|
167
|
+
if (!this.loaded)
|
|
168
|
+
return;
|
|
169
|
+
this.audio.currentTime = (this.loaded.start_ms + Math.max(0, position_in_milliseconds)) / 1000;
|
|
170
|
+
this.last_report = -Infinity;
|
|
171
|
+
this.emit("position", { position_in_milliseconds, duration_in_milliseconds: this.duration_ms() });
|
|
172
|
+
}
|
|
173
|
+
async set_volume(volume) {
|
|
174
|
+
this.volume = Math.max(0, Math.min(100, volume));
|
|
175
|
+
this.apply_volume();
|
|
176
|
+
}
|
|
177
|
+
subscribe(listener) {
|
|
178
|
+
this.listeners.add(listener);
|
|
179
|
+
return () => void this.listeners.delete(listener);
|
|
180
|
+
}
|
|
181
|
+
// Lets go of an element, so it stops fetching.
|
|
182
|
+
drop(audio) {
|
|
183
|
+
if (audio === this.audio)
|
|
184
|
+
this.detach();
|
|
185
|
+
audio.pause();
|
|
186
|
+
audio.removeAttribute("src");
|
|
187
|
+
audio.load();
|
|
188
|
+
}
|
|
189
|
+
async dispose() {
|
|
190
|
+
if (this.next)
|
|
191
|
+
this.drop(this.next.audio);
|
|
192
|
+
this.next = null;
|
|
193
|
+
this.loaded = null;
|
|
194
|
+
this.drop(this.audio);
|
|
195
|
+
this.listeners.clear();
|
|
196
|
+
}
|
|
197
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-tech-laboratories/x-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.136.0",
|
|
4
4
|
"description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|
|
@@ -252,6 +252,7 @@
|
|
|
252
252
|
"emojibase": "^18.0.0",
|
|
253
253
|
"emojibase-data": "^18.0.0",
|
|
254
254
|
"es-module-lexer": "^3.0.4",
|
|
255
|
+
"fast-xml-parser": "^5.12.1",
|
|
255
256
|
"fflate": "^0.8.3",
|
|
256
257
|
"force-graph": "^1.52.0",
|
|
257
258
|
"frimousse": "^0.4.0",
|