Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import type { SubsonicClient } from "./subsonic/client";
/** * A share link lives for a day. The server would happily keep one forever — * Navidrome stores no expiry when the param is omitted — and this is the most * exposed artifact the app can make: a public, unauthenticated page that streams * the file to anyone holding the URL, sitting in someone's chat history. A link * sent "here's this track" has finished its job within a day; one that outlives * that is only a liability with a longer tail. */export const SHARE_LIFETIME_MS = 24 * 60 * 60 * 1000;
export interface ShareResult { url: string; /** Whether the browser let us put it on the clipboard. */ copied: boolean; /** * What the browser said when it refused, verbatim — `NotAllowedError: Document is * not focused` is an actionable sentence and `copy failed` is not. Empty when * `copied`, and the caller prints it rather than logging it: the toolbar line is * where the user already is looking, and this is the only place the reason appears. */ why: string;}
/** The reason for the case where there is nothing to refuse with. */const NO_CLIPBOARD = "no clipboard API (needs https)";
/** * Share one track: ask the server for a link, then put it on the clipboard. * * The clipboard rather than a dialog, because this app has no dialog layer and a * keyboard user's next action is a paste somewhere else, not a read here. `copied` * is reported instead of assumed, and `why` is reported instead of swallowed — a * clipboard that will not say which of its three refusals it means turns a * successful share into a dead end the user cannot diagnose. * * The description becomes the share page's headline, and the server falls back to * its own idea of the contents when it is empty, so it is worth sending the two * fields a human actually scans for. */export async function shareSong( client: SubsonicClient, song: { id: string; title: string; artist?: string | null },): Promise<ShareResult> { // Asked for first, and awaited only after the clipboard has been claimed below: // the two have to be in flight together, because the clipboard write has to be // *initiated* inside the keypress and the text it writes is on the other end of // this request. Awaiting here would put the claim after the gesture. const pending = client .createShare(song.id, { description: song.artist ? `${song.artist} — ${song.title}` : song.title, expiresAt: new Date(Date.now() + SHARE_LIFETIME_MS), }) .then((share) => client.shareUrl(share));
const claimed = claim(pending); // synchronous on purpose; see `claim` const url = await pending; return { url, ...(await copyText(url, claimed)) };}
/** * Put the link on the clipboard, by whichever of the three routes this browser allows, * in the order that costs the user the least to notice. * * Each route is tried only because the one above it refused, and the first refusal that * came from an actual API is what gets reported: they share a cause, so the last one * adds no information, and "this browser has no Clipboard API" is only the finding when * there is nothing else to say about it. */async function copyText( url: string, claimed: Promise<string> | null,): Promise<{ copied: boolean; why: string }> { // 1. The write issued inside the keypress, while the activation is alive. let modern: string | undefined; if (claimed) { const refused = await claimed; if (refused === "") return { copied: true, why: "" }; modern = refused; }
// 2. The plain write — the route for a browser that will not hold a promised entry // open, and the one that answers when the activation outlived the request anyway. const box = typeof navigator === "undefined" ? undefined : navigator.clipboard; if (box?.writeText) { try { await box.writeText(url); return { copied: true, why: "" }; } catch (error) { modern ??= why(error); } }
// 3. And for an http page, where there is no Clipboard API to refuse: select the text // and copy the selection, which is the one route the secure-context gate never // reached. It says only yes or no — the sentence worth printing is the one the real // API would have given, and there was none. if (writeBySelection(url)) return { copied: true, why: "" };
return { copied: false, why: modern ?? NO_CLIPBOARD };}
/** * Copy text to the clipboard *while the keypress is still counted*. * * A clipboard write is gated on transient user activation: the browser remembers * that a key went down for a few seconds (Chrome) or about a second (Safari), and * outside that window the write is refused. `createShare` is a round trip to a * server that may be on the other side of a tailnet, so the obvious order — await * the share, then write — spends the activation waiting for the response and then * reports a refusal the user cannot explain. * * `ClipboardItem` is what breaks the deadlock. Its entry values may be promises, * so the write can be *issued* inside the gesture with the URL still in flight, and * the browser resolves the content when it arrives. That is the only shape of * async copy that survives a slow server. * * Returns the promise to await, or `null` for "this browser cannot take a promised * entry" (no `ClipboardItem`, or a constructor that demands a value) — in which case * the caller falls back to writing after the response, which is the old best effort * and is at least honest about failing. */function claim(pending: Promise<string>): Promise<string> | null { const box = typeof navigator === "undefined" ? undefined : navigator.clipboard; if (!box?.write || typeof ClipboardItem !== "function") return null; try { const text = pending.then((url) => new Blob([url], { type: "text/plain" })); return box.write([new ClipboardItem({ "text/plain": text })]).then(() => "", why); } catch { // A constructor that refuses a promised entry is a fact about the browser, not // an error the user can act on; the late write is the honest next attempt. return null; }}
/** What the last resort said when it also said no. *//** * The copy from before the Clipboard API: select the text and ask the browser to copy * the selection. Deprecated, and the only route that is not gated on a secure context * — which is the whole reason it is here. The Clipboard API is a *read* API as much as * a write one, and a clipboard holding a password or a 2FA code is not something a * network attacker should be handed, so an origin that can be forged or downgraded by * whoever is on the path simply does not get it. That gate is sensible about reading * and collateral damage about writing a link this app minted thirty milliseconds ago, * and the selection route has no such gate because it is the same thing a keyboard * Ctrl-C does — deprecated does not mean unused: it is what every "copy" button on the * web did until 2015 and what every http page still uses today. * * It needs the page focused, so it is not a way around "Document is not focused"; it is * a way around http. The textarea is fixed at the viewport origin rather than parked * off-screen, because focusing an off-screen element scrolls the page, and `readonly` * because a textarea that takes focus raises the on-screen keyboard on a phone — the * last thing wanted is a keyboard opening over the toolbar line the user is reading. */function writeBySelection(text: string): boolean { if (typeof document === "undefined" || typeof document.execCommand !== "function") { return false; } const was = document.activeElement; const box = document.createElement("textarea"); box.value = text; box.readOnly = true; box.tabIndex = -1; box.setAttribute("aria-hidden", "true"); box.style.position = "fixed"; box.style.top = "0"; box.style.left = "0"; box.style.width = "1px"; box.style.height = "1px"; box.style.opacity = "0"; box.style.border = "none"; box.style.outline = "none"; document.body.appendChild(box); box.select(); let copied = false; try { copied = document.execCommand("copy"); } catch { copied = false; } box.remove(); // The select moved the caret into the box and, with it, the focus; the list has no // focus to speak of, but a bar button that had it should keep it. if (was instanceof HTMLElement && was !== document.body) was.focus(); return copied;}
/** * The browser's own words, which are worth more than a category. Three refusals * reach here and they have three different fixes — no `navigator.clipboard` at all * (insecure context: serve it over https), `NotAllowedError: Document is not * focused` (DevTools has the focus; click the page and press the key again), and * `NotAllowedError: Write to clipboard permission denied` (a denied site * permission) — and collapsing them into `copy failed` is what made this unfixable * from a bug report. */function why(error: unknown): string { const e = error as { name?: string; message?: string } | null; if (!e) return "copy failed"; return e.message ? `${e.name ?? "copy failed"}: ${e.message}` : (e.name ?? "copy failed");}