aboutsummaryrefslogtreecommitdiffstats
path: root/src/media-upload.js
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-09-30 18:03:33 +0000
committerAdam Soltys <[email protected]>2026-09-30 18:03:33 +0000
commit0570f48910ddc4ea10d27fb8ab7992fbd013a0b7 (patch)
treedbc1e5ece94bc71fcd8bb7e89f61043933c1992c /src/media-upload.js
parent95eaf11d116260b101c81346ba41810aacf49a7d (diff)
parentcfeacb1a7a10766565ed3eaab13154096478c837 (diff)
downloadcoinosv3-0570f48910ddc4ea10d27fb8ab7992fbd013a0b7.tar.gz
coinosv3-0570f48910ddc4ea10d27fb8ab7992fbd013a0b7.zip
Merge remote-tracking branch 'cs/prod'
Diffstat (limited to 'src/media-upload.js')
-rw-r--r--src/media-upload.js115
1 files changed, 115 insertions, 0 deletions
diff --git a/src/media-upload.js b/src/media-upload.js
new file mode 100644
index 0000000..9301939
--- /dev/null
+++ b/src/media-upload.js
@@ -0,0 +1,115 @@
+import { sha256 } from '@noble/hashes/sha256';
+import { bytesToHex } from '@noble/hashes/utils';
+
+// Independent public hosts: a phone upload should not fail just because one
+// provider is down or rejects a particular container. nostr.build is the
+// widely-used Blossom home and goes first; nostr.download (which advertises
+// large image/video/audio uploads) is the fallback — it was unreachable for
+// hours on 2026-09-30, and every upload waited on it.
+export const PUBLIC_MEDIA_SERVERS = ['https://blossom.nostr.build', 'https://nostr.download'];
+
+export class MediaUploadError extends Error {
+ constructor(code, details = '') {
+ super(code);
+ this.name = 'MediaUploadError';
+ this.code = code;
+ this.details = details;
+ }
+}
+
+async function fileHash(file) {
+ const hash = sha256.create();
+ const chunk = 4 * 1024 * 1024;
+ for (let at = 0; at < file.size; at += chunk)
+ hash.update(new Uint8Array(await file.slice(at, at + chunk).arrayBuffer()));
+ return bytesToHex(hash.digest());
+}
+
+const responseUrl = (body) => body?.url
+ || body?.data?.[0]?.url
+ || (body?.tags || []).find((x) => x?.[0] === 'url')?.[1]
+ || null;
+
+function mediaUrl(url, server, file) {
+ const out = new URL(url, server);
+ const tail = out.pathname.split('/').at(-1) || '';
+ if (/^[0-9a-f]{64}$/i.test(tail)) {
+ const named = String(file.name || '').match(/\.([a-z0-9]{1,8})$/i)?.[1];
+ const byType = { 'video/quicktime': 'mov', 'video/mp4': 'mp4', 'video/webm': 'webm',
+ 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif' }[file.type];
+ const ext = (named || byType || '').toLowerCase();
+ if (ext) out.pathname += '.' + ext;
+ }
+ return out.href;
+}
+
+// A PUT that reports how much of the body has gone out: fetch() can't, so in
+// the browser (with the real fetch) it's XMLHttpRequest. Answers like fetch.
+function putWithProgress(url, { body, headers, signal }, onProgress) {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('PUT', url);
+ for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
+ xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); };
+ xhr.onload = () => resolve(new Response(xhr.responseText, {
+ status: xhr.status, headers: { 'x-reason': xhr.getResponseHeader('x-reason') || '' } }));
+ xhr.onerror = () => reject(new Error('network error'));
+ xhr.ontimeout = () => reject(new Error('timeout'));
+ if (signal) signal.addEventListener('abort', () => { xhr.abort(); reject(new Error('timeout')); });
+ xhr.send(body);
+ });
+}
+
+// BUD-02 upload. `signEvent` is deliberately injected: the app can use its
+// always-available wallet identity, while tests need no secret key.
+export async function uploadPublicMedia(file, signEvent, {
+ servers = PUBLIC_MEDIA_SERVERS,
+ fetcher = globalThis.fetch,
+ timeoutMs = 5 * 60_000,
+ onProgress = null, // (fraction 0..1) as the bytes go out
+} = {}) {
+ const tracked = onProgress && typeof XMLHttpRequest !== 'undefined' && fetcher === globalThis.fetch;
+ if (!file || !file.size || typeof signEvent !== 'function') throw new MediaUploadError('failed');
+ const x = await fileHash(file);
+ const now = Math.floor(Date.now() / 1000);
+ const auth = await signEvent({
+ kind: 24242, created_at: now - 5, content: 'upload',
+ tags: [['t', 'upload'], ['x', x], ['expiration', String(now + Math.ceil(timeoutMs / 1000) + 120)]],
+ });
+ if (!auth) throw new MediaUploadError('failed');
+ const authorization = 'Nostr ' + btoa(JSON.stringify(auth));
+ const failures = [];
+ for (const [i, server] of servers.entries()) {
+ // A host that doesn't answer at all costs a few seconds, not the whole
+ // upload timeout. Any HTTP answer, even an error, means it's there.
+ if (i < servers.length - 1) {
+ try { await fetcher(server.replace(/\/$/, '') + '/upload', { method: 'HEAD', signal: AbortSignal.timeout(5000) }); }
+ catch (error) { failures.push({ status: 0, reason: 'unreachable' }); continue; }
+ }
+ try {
+ const init = {
+ method: 'PUT', body: file, signal: AbortSignal.timeout(timeoutMs),
+ headers: {
+ authorization,
+ 'content-type': file.type || 'application/octet-stream',
+ 'x-sha-256': x,
+ 'x-content-length': String(file.size),
+ },
+ };
+ if (onProgress) onProgress(0);
+ const target = server.replace(/\/$/, '') + '/upload';
+ const response = tracked ? await putWithProgress(target, init, onProgress) : await fetcher(target, init);
+ let body = null;
+ try { body = await response.json(); } catch {}
+ const url = response.ok && responseUrl(body);
+ if (url) return mediaUrl(url, server, file);
+ failures.push({ status: response.status, reason: response.headers.get('x-reason') || body?.message || '' });
+ } catch (error) {
+ failures.push({ status: 0, reason: error?.message || '' });
+ }
+ }
+ const details = failures.map((x) => [x.status, x.reason].filter(Boolean).join(' ')).filter(Boolean).join('; ');
+ if (failures.length && failures.every((x) => x.status === 413)) throw new MediaUploadError('too-big', details);
+ if (failures.length && failures.every((x) => x.status === 415)) throw new MediaUploadError('unsupported', details);
+ throw new MediaUploadError('failed', details);
+}