UNPKG

@adonis-agora/media

Version:

Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a

119 lines • 6.14 kB
import { DEFAULT_DELIVERY_SIGNED_TTL_SECONDS } from '../delivery.js'; import { openWithMetadata, utf8Of } from '../disk_read.js'; import { ConversionArtifactMissingError, MediaNotFoundError, TransformNotReadyError, } from '../errors.js'; import { HLS_PLAYLIST_CONTENT_TYPE, hlsArtifactContentType, resolvePackagePath, rewriteHlsPlaylist, } from './playlist.js'; /** * Framework-agnostic HLS read path — the {@link MediaDeliveryHandler} of a transformer-generated * HLS package. One route of yours receives `(:mediaId, :file?)` and delegates here; the handler * resolves the record's HLS conversion, validates the requested file against the package's * persisted artifact list, and: * * - for a **playlist**: returns its content with every relative reference rewritten — sub-playlist * references through your `urlForPlaylist` (auth stays yours), media references through * `urlForSegment` or a presigned URL; * - for a **media file**: returns a `redirect` (presigned) or a `stream`, per `segmentDelivery`. * * ```ts * const hls = new HlsDeliveryHandler({ * library: media, * urlForPlaylist: ({ mediaId, file }) => router.makeUrl('videos.hls', { id: mediaId, file }), * }) * * router.get('/videos/:id/hls/:file?', async ({ params, response, auth }) => { * await authorize(auth.user, params.id) // ← the app's job, as everywhere * const result = await hls.handle({ mediaId: params.id, file: params.file }) * if (result.kind === 'redirect') return response.redirect(result.url) * if (result.kind === 'stream') { * response.header('content-type', result.mimeType) * return response.stream(result.stream) * } * response.header('content-type', result.contentType) * return response.send(result.content) * }).use(middleware.auth()) * ``` * * **This handler performs NO authorization** — the same split as {@link MediaDeliveryHandler} and * `TusUploadHandler`: guard the route before calling `handle`. Note that a presigned segment URL * (the default) is itself a capability: whoever holds it can fetch that segment until the TTL * expires. That is the standard HLS trade-off — keep `segmentTtlSeconds` short, or use * `segmentDelivery: 'stream'` with a segment `urlForSegment` pointing back at your route to keep * every byte behind your auth. */ export class HlsDeliveryHandler { library; conversion; urlForPlaylist; urlForSegment; segmentTtlSeconds; segmentDelivery; constructor(options) { const source = options.library; this.library = 'library' in source ? source.library : source; this.conversion = options.conversion ?? 'video'; this.urlForPlaylist = options.urlForPlaylist; this.urlForSegment = options.urlForSegment; this.segmentTtlSeconds = options.segmentTtlSeconds ?? DEFAULT_DELIVERY_SIGNED_TTL_SECONDS; this.segmentDelivery = options.segmentDelivery ?? 'redirect'; } async handle(request) { const { mediaId } = request; const record = await this.library.find(mediaId); if (!record) throw new MediaNotFoundError(mediaId); const variant = record.conversions[this.conversion]; if (!variant) throw new TransformNotReadyError(mediaId, this.conversion); if (variant.path === undefined || variant.disk === undefined) { throw new ConversionArtifactMissingError(mediaId, this.conversion); } // The package's shape comes from what the transformer persisted; a hand-registered // single-file conversion degrades to a one-file package. const prefix = variant.prefix ?? variant.path.slice(0, variant.path.lastIndexOf('/') + 1); const files = new Set(variant.files ?? [variant.path.slice(prefix.length)]); const entry = variant.path.slice(prefix.length); const requested = request.file === undefined || request.file === '' ? entry : request.file; // Membership in the persisted artifact list is the whole access check: no path arithmetic on // caller input ever reaches the disk, so traversal is structurally impossible. if (!files.has(requested)) { throw new MediaNotFoundError(`${mediaId}#${this.conversion}:${requested}`); } const disk = this.library.storage.disk(variant.disk); const key = `${prefix}${requested}`; if (requested.toLowerCase().endsWith('.m3u8')) { const content = utf8Of(await disk.getBytes(key)); const rewritten = await rewriteHlsPlaylist(content, async (ref) => { const target = resolvePackagePath(requested, ref.uri); // A relative reference that escapes the package or names a file the transformer never // wrote is not ours to rewrite — leave it exactly as it was. if (target === null || !files.has(target)) return ref.uri; if (ref.kind === 'playlist') return this.urlForPlaylist({ mediaId, file: target }); if (this.urlForSegment) return this.urlForSegment({ mediaId, file: target }); return disk.getSignedUrl(`${prefix}${target}`, { expiresIn: this.segmentTtlSeconds }); }); return { kind: 'playlist', content: rewritten, contentType: HLS_PLAYLIST_CONTENT_TYPE, fileName: requested, }; } if (this.segmentDelivery === 'redirect') { return { kind: 'redirect', url: await disk.getSignedUrl(key, { expiresIn: this.segmentTtlSeconds }), }; } const { metadata, stream } = await openWithMetadata(disk, key); return { kind: 'stream', stream, mimeType: metadata.contentType ?? hlsArtifactContentType(requested) ?? 'application/octet-stream', size: metadata.contentLength, fileName: requested.slice(requested.lastIndexOf('/') + 1), }; } } //# sourceMappingURL=delivery.js.map