export function utc(value) {
if (value === null || value === undefined || value === "") {
return "";
}
if (typeof value !== "string") {
return String(value);
}
const at = new Date(value);
if (Number.isNaN(at.getTime())) {
return value;
}
const iso = at.toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC+00:00`;
}
const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
export function instant(value) {
if (typeof value !== "string") {
return "";
}
const found = DATE_TIME.exec(value);
if (found === null) {
return "";
}
const [year, month, day, hour, minute, second] = found.slice(1, 7).map(Number);
const sign = found[7] === "-" ? -1 : 1;
const offsetHours = Number(found[8] ?? 0);
const offsetMinutes = Number(found[9] ?? 0);
if (hour > 23 || minute > 59 || second > 59 || offsetHours > 23 || offsetMinutes > 59) {
return "";
}
const local = new Date(0);
local.setUTCFullYear(year, month - 1, day);
if (local.getUTCFullYear() !== year || local.getUTCMonth() !== month - 1) {
return "";
}
local.setUTCHours(hour, minute, second, 0);
const at = new Date(local.getTime() - sign * (offsetHours * 60 + offsetMinutes) * 60000);
if (at.getUTCFullYear() < 1 || at.getUTCFullYear() > 9999) {
return "";
}
return utc(at.toISOString());
}
const MASKABLE_DIGITS = 8;
export function maskTel(value) {
if (typeof value !== "string") {
return "number hidden";
}
const digits = value.replace(/\D/g, "");
if (digits.length < MASKABLE_DIGITS) {
return "number hidden";
}
return `number ending ${digits.slice(-4)}`;
}
export function maskMail(value) {
if (typeof value !== "string") {
return "address hidden";
}
const at = value.lastIndexOf("@");
const domain = at < 0 ? "" : value.slice(at + 1).trim().toLowerCase();
if (at < 1 || domain === "") {
return "address hidden";
}
return `address at ${domain}`;
}
function isObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function partyLine(party, index) {
const label = `Party ${index + 1}`;
if (!isObject(party)) {
return `${label}: not an object`;
}
const parts = [];
if ("tel" in party) {
parts.push(maskTel(party.tel));
}
if ("mailto" in party) {
parts.push(maskMail(party.mailto));
}
if ("name" in party) {
parts.push("name hidden");
}
return parts.length === 0 ? `${label}: no number, address or name` : `${label}: ${parts.join("; ")}`;
}
function decoded(text) {
if (typeof text !== "string" || !/^[A-Za-z0-9_-]+$/.test(text)) {
return null;
}
try {
const bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
return isObject(value) ? value : null;
} catch {
return null;
}
}
function items(value) {
return Array.isArray(value) ? value : [];
}
const DIALOG_TYPES = ["recording", "text", "transfer", "incomplete"];
function isIndex(value) {
return Number.isInteger(value) && value >= 0;
}
function partiesOf(parties) {
if (isIndex(parties)) {
return `party ${parties + 1}`;
}
if (Array.isArray(parties) && parties.length > 0 && parties.every(isIndex)) {
return `parties ${parties.map((p) => p + 1).join(", ")}`;
}
return "no parties";
}
export function dialogLine(dialog, index) {
const label = `Dialog ${index + 1}`;
if (!isObject(dialog)) {
return `${label}: not an object`;
}
const type = DIALOG_TYPES.includes(dialog.type) ? dialog.type : "other type";
const start = instant(dialog.start) || "no start";
const length = typeof dialog.duration === "number" && dialog.duration > 0 ? `${dialog.duration} s` : "no length";
let content = "no content";
if (typeof dialog.body === "string" && dialog.body !== "") {
content = "content hidden";
} else if (typeof dialog.url === "string" && dialog.url !== "") {
content = "content at a link outside the server";
}
return `${label}: ${type}, ${start}, ${length}, ${partiesOf(dialog.parties)}; ${content}`;
}
const LINKED = [
["dialog", "dialog"],
["attachments", "attachment"],
["analysis", "analysis"],
];
function linksOf(vcon) {
const found = [];
for (const [part, noun] of LINKED) {
items(vcon[part]).forEach((item, index) => {
if (isObject(item) && typeof item.url === "string" && item.url !== "") {
found.push({ where: `${noun} ${index + 1}`, url: item.url });
}
});
}
return found;
}
function readable(text) {
let vcon;
try {
vcon = JSON.parse(text);
} catch {
return null;
}
if (!isObject(vcon) || "ciphertext" in vcon) {
return null;
}
if ("payload" in vcon && "signatures" in vcon) {
return decoded(vcon.payload);
}
return vcon;
}
export function links(text) {
const vcon = readable(text);
return vcon === null ? [] : linksOf(vcon);
}
export const DISPLAY_LIMIT = 2 * 1024 * 1024;
export function shown(text, limit = DISPLAY_LIMIT) {
if (text.length <= limit) {
return { text, left: 0 };
}
return { text: text.slice(0, limit), left: text.length - limit };
}
const MEDIA_ENCODINGS = ["base64url", "base64"];
function listed(value) {
const made = items(value);
if (made.length === 0) {
return "none";
}
const readableItems = made.map((item) => {
if (isObject(item) && MEDIA_ENCODINGS.includes(item.encoding) && typeof item.body === "string") {
return { ...item, body: `[${item.body.length} characters of ${item.encoding}, not shown]` };
}
return item;
});
return shown(JSON.stringify(readableItems, null, 2)).text;
}
const SECTIONS = new Map([
["parties", (vcon) => listed(vcon.parties)],
["subject", (vcon) => (typeof vcon.subject === "string" && vcon.subject !== "" ? vcon.subject : "none")],
["dialog", (vcon) => listed(vcon.dialog)],
["analysis", (vcon) => listed(vcon.analysis)],
]);
export function section(text, name) {
const make = SECTIONS.get(name);
const vcon = readable(text);
return make === undefined || vcon === null ? null : make(vcon);
}
function empty(form, subject) {
return {
form,
created: "",
subject,
parties: [],
dialogs: 0,
dialog: [],
seconds: 0,
attachments: 0,
analyses: 0,
links: 0,
signature: null,
};
}
function counted(vcon, form) {
const dialog = items(vcon.dialog);
let seconds = 0;
for (const d of dialog) {
if (isObject(d) && typeof d.duration === "number" && d.duration > 0) {
seconds += d.duration;
}
}
return {
form,
created: instant(vcon.created_at),
subject: typeof vcon.subject === "string" && vcon.subject !== "" ? "present, hidden" : "none",
parties: items(vcon.parties).map(partyLine),
dialogs: dialog.length,
dialog: dialog.map(dialogLine),
seconds,
attachments: items(vcon.attachments).length,
analyses: items(vcon.analysis).length,
links: linksOf(vcon).length,
signature: null,
};
}
function textField(header, name) {
return header !== null && typeof header[name] === "string" ? header[name] : "";
}
export function summary(text) {
let vcon;
try {
vcon = JSON.parse(text);
} catch {
return empty("not JSON", "not readable");
}
if (!isObject(vcon)) {
return empty("not a JSON object", "not readable");
}
if ("ciphertext" in vcon) {
return empty("encrypted (JWE)", "not readable");
}
if ("payload" in vcon && "signatures" in vcon) {
const first = items(vcon.signatures)[0];
const header = isObject(first) ? decoded(first.protected) : null;
const payload = decoded(vcon.payload);
const made = payload === null ? empty("signed (JWS)", "not readable") : counted(payload, "signed (JWS)");
made.signature = {
alg: textField(header, "alg"),
kid: textField(header, "kid"),
x5t: textField(header, "x5t"),
};
return made;
}
return counted(vcon, "unsigned");
}
const WRONG_LISTENER = "/problems/wrong-listener";
function advice(status, type) {
if (typeof type === "string" && type.endsWith(WRONG_LISTENER)) {
return (
"Open the console at the server's other address and sign in there: " +
"one address serves tenant keys and the other serves operator keys."
);
}
if (status === 401) {
return "Sign in again with a key the server accepts.";
}
if (status === 403) {
return "Sign in with a key that holds the scope this needs.";
}
if (status === 404) {
return "Check the uuid or id: it may be deleted or belong to another tenant.";
}
if (status === 410) {
return "It was deleted: a key with the legal scope can still find it in the Legal view.";
}
if (status === 409) {
return "Reload the view and check its state before trying again.";
}
if (status === 412) {
return "It changed since you opened it: open it again, then repeat the change.";
}
if (status === 413) {
return "Send a smaller file.";
}
if (status === 400 || status === 415 || status === 422) {
return "Correct what was sent and try again.";
}
if (status === 429) {
return "Wait a minute, then try again.";
}
if (status >= 500) {
return "Try again; if it repeats, tell the server's operator.";
}
return "Try again.";
}
export function refusalText(status, title, type = undefined) {
if (status === 0) {
return "The server could not be reached. Check the connection and try again.";
}
const what = typeof title === "string" && title !== "" ? `${title} (${status})` : `HTTP ${status}`;
return `${what}. ${advice(status, type)}`;
}
export const REVEAL_PARTS = Object.freeze(["parties", "subject", "dialog", "analysis", "links", "all", "audio"]);
export function revealPath(path, part) {
if (part === null) {
return path;
}
if (!REVEAL_PARTS.includes(part)) {
throw new RangeError(`not a part a reveal can name: ${part}`);
}
if (path.includes("?") || path.includes("#")) {
throw new RangeError("a reveal is the only parameter of its read");
}
return `${path}?reveal=${part}`;
}
export function audioSignature(bytes) {
if (startsWith(bytes, "RIFF") && startsWith(bytes, "WAVE", 8)) {
return "audio/wav";
}
if (startsWith(bytes, "ID3") || isMpegFrame(bytes)) {
return "audio/mpeg";
}
if (startsWith(bytes, "OggS")) {
return startsWith(bytes, "OpusHead", 28) ? "audio/opus" : "audio/ogg";
}
return null;
}
function isMpegFrame(bytes) {
return (
bytes.length >= 4 &&
bytes[0] === 0xff &&
(bytes[1] & 0xe0) === 0xe0 &&
(bytes[1] & 0x18) !== 0x08 &&
(bytes[1] & 0x06) !== 0x00 &&
(bytes[2] & 0xf0) !== 0xf0 &&
(bytes[2] & 0x0c) !== 0x0c
);
}
function startsWith(bytes, text, offset = 0) {
if (bytes.length < offset + text.length) {
return false;
}
for (let i = 0; i < text.length; i++) {
if (bytes[offset + i] !== text.charCodeAt(i)) {
return false;
}
}
return true;
}
const BASE64 = /^(?:[A-Za-z0-9+/]*|[A-Za-z0-9_-]*)={0,2}$/;
function bytesOf(body) {
if (!BASE64.test(body)) {
return null;
}
let text;
try {
text = atob(body.replaceAll("-", "+").replaceAll("_", "/"));
} catch {
return null;
}
const bytes = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
bytes[i] = text.charCodeAt(i);
}
return bytes;
}
function offered(dialog, index, limit) {
const what = `Dialog ${index + 1}'s recording`;
if (typeof dialog.body !== "string" || dialog.body === "") {
if (typeof dialog.url === "string" && dialog.url !== "") {
return refused(`${what} is at a link outside the server, which the console never loads.`);
}
return refused(`Dialog ${index + 1} has no recording inside the vCon.`);
}
if (!MEDIA_ENCODINGS.includes(dialog.encoding)) {
return refused(`Dialog ${index + 1} holds text or data, not an encoded recording.`);
}
const type = declaredType(dialog);
if (type === "") {
return refused(`${what} does not say what type it is, so the console does not play it. Download the vCon to examine it.`);
}
let played;
if (AUDIO_TYPES.includes(type)) {
played = type;
} else if (Object.hasOwn(AUDIO_ALIASES, type)) {
played = AUDIO_ALIASES[type];
}
if (played === undefined) {
const named = type.length > TYPE_SHOWN ? `${type.slice(0, TYPE_SHOWN)}…` : type;
return refused(
`${what} is declared as ${named}, which the console does not play. ` +
`It plays ${AUDIO_TYPES.slice(0, -1).join(", ")} and ${AUDIO_TYPES.at(-1)}. ` +
"Download the vCon to use the recording another way.",
);
}
const size = Math.floor((dialog.body.replace(/=+$/, "").length * 3) / 4);
if (size > limit) {
return refused(
`${what} is about ${size} bytes, and the console plays at most ${limit}. ` +
"Download the vCon to hear it another way.",
);
}
return { ok: true, type: played, declared: type };
}
export function recording(text, index, limit = AUDIO_LIMIT) {
const vcon = readable(text);
if (vcon === null) {
return refused("This vCon cannot be read in parts, so the console cannot play from it.");
}
const dialog = isIndex(index) ? items(vcon.dialog)[index] : undefined;
if (!isObject(dialog)) {
return refused("The vCon has no such dialog to play.");
}
const offer = offered(dialog, index, limit);
if (!offer.ok) {
return offer;
}
const what = `Dialog ${index + 1}'s recording`;
const bytes = bytesOf(dialog.body);
if (bytes === null) {
return refused(`${what} cannot be decoded: its body is not base64. Download the vCon to examine it.`);
}
if (!isDeclared(bytes, offer.type)) {
return refused(
`${what} is declared as ${offer.declared}, but its bytes are not ${offer.type}. ` +
"The console does not play it. Download the vCon to examine the recording.",
);
}
return { ok: true, type: offer.type, bytes };
}
export function recordings(text, limit = AUDIO_LIMIT) {
const found = [];
const vcon = readable(text);
items(vcon === null ? null : vcon.dialog).forEach((dialog, index) => {
const offer = isObject(dialog) ? offered(dialog, index, limit) : refused("");
if (offer.ok) {
found.push({ index, type: offer.type });
}
});
return found;
}
export function isDeclared(bytes, type) {
const found = audioSignature(bytes);
return found !== null && (found === type || (found === "audio/opus" && type === "audio/ogg"));
}
function declaredType(dialog) {
const declared = "mediatype" in dialog ? dialog.mediatype : dialog.mimetype;
return typeof declared === "string" ? declared.split(";")[0].trim().toLowerCase() : "";
}
const TYPE_SHOWN = 80;
function refused(reason) {
return { ok: false, reason };
}
export const AUDIO_LIMIT = 100 * 1024 * 1024;
export const AUDIO_ALIASES = Object.freeze({
"audio/x-wav": "audio/wav",
"audio/wave": "audio/wav",
"audio/vnd.wave": "audio/wav",
"audio/x-mp3": "audio/mpeg",
"audio/mp3": "audio/mpeg",
"audio/x-ogg": "audio/ogg",
});
export const AUDIO_TYPES = Object.freeze(["audio/wav", "audio/mpeg", "audio/ogg", "audio/opus"]);
const LABEL_LIMIT = 200;
export const HAND_OVER = "recording";
export function handed(data, limit = AUDIO_LIMIT) {
if (!isObject(data) || data.kind !== HAND_OVER) {
return null;
}
if (!(data.bytes instanceof ArrayBuffer) || data.bytes.byteLength > limit) {
return null;
}
if (!AUDIO_TYPES.includes(data.type) || !isDeclared(new Uint8Array(data.bytes), data.type)) {
return null;
}
if (typeof data.label !== "string" || data.label === "" || data.label.length > LABEL_LIMIT) {
return null;
}
return { type: data.type, label: data.label, bytes: data.bytes };
}
export function handOver(found, uuid, index) {
const { bytes } = found;
const whole = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength;
return {
kind: HAND_OVER,
type: found.type,
label: `Dialog ${index + 1} of ${uuid}, ${found.type}`,
bytes: whole ? bytes.buffer : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
};
}
export function accepts(event, sender, origin) {
return sender !== null && sender !== undefined && event.origin === origin && event.source === sender;
}
export const PLAYER_READY = "player-ready";
export const PLAYER_CLOSED = "player-closed";