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

190 lines • 9.34 kB
import type { Readable } from 'node:stream'; import { type MediaAction, type MediaAuthorizer, type MediaIdentityResolver, type MediaSubject } from './access.js'; import type { DeliveryMode } from './delivery.js'; import type { MediaLibrary } from './media_library.js'; import type { MediaRecord } from './media_record.js'; import type { ResponsiveImage, ResponsiveImageOptions } from './responsive_image.js'; import { type MediaStream } from './streaming.js'; /** * The slice of an AdonisJS `HttpContext` the delivery route uses — typed structurally so the * route works with the real context and with a test double alike. */ export interface DeliveryRouteContext { params: Record<string, unknown>; request: { qs(): Record<string, unknown>; header(name: string): string | undefined | null; }; response: { status(code: number): { json(body: unknown): unknown; } | unknown; header(name: string, value: string): unknown; redirect(url: string): unknown; stream(stream: Readable): unknown; }; } export interface MediaDeliveryRouteOptions { /** * Who may read. Default: the record's collection `access.read`. With neither, every request is * refused — the route never serves by default. */ authorize?: MediaAuthorizer; /** Route parameter holding the media id. Default `'id'`. */ param?: string; /** * `Cache-Control` for what the route serves. Default `'private, max-age=60'`: a personal file * must not be kept by a shared cache, and a minute absorbs a page rendering it many times. */ cacheControl?: string; /** Override `delivery.mode` for this route. */ mode?: DeliveryMode; /** Signed-URL lifetime when the resolved mode is `signed`. */ signedTtlSeconds?: number; } /** {@link DeliveryRouteContext}, plus the `response.send` a manifest is answered with. */ export interface StreamRouteContext extends DeliveryRouteContext { response: DeliveryRouteContext['response'] & { send(body: unknown): unknown; }; } export interface MediaStreamRouteOptions { /** Who may watch. Default: the record's collection `access.read`; neither ⇒ refused. */ authorize?: MediaAuthorizer; /** `Cache-Control` for manifests and redirects. Default `'private, max-age=60'`. */ cacheControl?: string; /** * `Cache-Control` for segments streamed through the app (`mode: 'proxy'`). Default * `'private, max-age=86400'`: a segment never changes once written. */ segmentCacheControl?: string; /** How segments reach the player. Default `delivery.mode`. */ mode?: DeliveryMode; /** Lifetime of the signed URL a segment request is redirected to, in `signed` mode. */ signedTtlSeconds?: number; /** * Lifetime of the package signature handed to the player with `delivery.signing`, in seconds. * Default `delivery.signing.expiresIn`, never shorter than the video plus an hour. */ expiresIn?: number; } /** * Authorization for media, wired to the app's identity (`access.identity` — authkit, AdonisJS * auth or your own) and the collections' `access` policies. `media.access` on the manager. * * The library still never decides authorization by itself: every rule comes from the app — * a collection's `access`, or an `authorize` passed in. This is the plumbing that applies them. */ export declare class MediaAccess { #private; constructor(options: { library: MediaLibrary; identity?: MediaIdentityResolver | undefined; }); /** The current user per the configured identity resolver, or `null`. */ subject(ctx: unknown): Promise<MediaSubject | null>; /** * May the current user perform `action`? `target` is the record (read) or the collection a file * is going into (write). The rule is `authorize` when given, otherwise the collection's * `access[action]`; neither ⇒ `false`. */ can(ctx: unknown, action: MediaAction, target: MediaRecord | { collection: string; }, authorize?: MediaAuthorizer): Promise<boolean>; /** * {@link can}, throwing {@link MediaAccessDeniedError} when refused — `401` for an anonymous * request, `403` otherwise. Use it in your own controllers and upload policies: * * ```ts * // DirectUploadPolicy.onInitiate * await media.access.authorize(ctx, 'write', { collection: 'avatar' }) * ``` */ authorize(ctx: unknown, action: MediaAction, target: MediaRecord | { collection: string; }, authorize?: MediaAuthorizer): Promise<void>; /** * `media.library.image(id)` for the current user: checks read access first (the collection's * `access.read`, or `authorize`), so the URLs it hands out — signed ones especially, which * carry their authorization — only ever reach someone allowed to see the file. */ image(ctx: unknown, id: string, options?: ResponsiveImageOptions & { authorize?: MediaAuthorizer; }): Promise<ResponsiveImage>; /** * `media.library.stream(id)` for the current user: checks read access first (the collection's * `access.read`, or `authorize`), then returns the HLS/DASH manifest URLs a player needs — for * `useMediaStream` from `@adonis-agora/media-react`. * * ```ts * return inertia.render('lessons/show', { video: await media.access.stream(ctx, lesson.videoMediaId) }) * ``` */ stream(ctx: unknown, id: string, options?: { conversions?: readonly string[]; expiresIn?: number; authorize?: MediaAuthorizer; }): Promise<MediaStream>; /** * Authorize and answer one request for a file of a streaming package (HLS or DASH) — the core * of {@link streamRoute}, for a controller that finds the record its own way. * * A request carrying a valid package signature (`?exp=&sig=`, from `media.library.stream()` * with `delivery.signing`) is served without asking the app again; anything else is authorized * like a read. A manifest is answered as text, with the signature carried onto its references * (a fresh one when the request was authorized by session), so the player's segment requests * stay authorized. Segments are redirected to storage or streamed, per `mode`. */ serveStream(ctx: StreamRouteContext, target: MediaRecord | string | null | undefined, conversion: string, file: string, options?: MediaStreamRouteOptions): Promise<unknown>; /** * A ready AdonisJS route handler for HLS/DASH packages — the read side of `transformers.video()`: * * ```ts * const serveStream = media.access.streamRoute() * router.get('/media/:id/stream/:conversion/*', serveStream) * ``` * * The URL mirrors the package: `/media/<id>/stream/<conversion>/<file>`, so the relative * references a manifest stores resolve back to this same route. See {@link serveStream}. */ streamRoute(options?: MediaStreamRouteOptions): (ctx: StreamRouteContext) => Promise<unknown>; /** * Authorize and answer one media read — the core of {@link deliveryRoute}, for a controller that * finds the record its own way (a stable `/profiles/:id/photo` URL, a record looked up by its * owner): * * ```ts * async show(ctx) { * const [avatar] = await media.library.list('User', ctx.params.id, 'avatar') * return media.access.serve(ctx, avatar, { authorize: canSeeProfile }) * } * ``` * * `target` is the record, its id, or `null`/`undefined` (answered 404). Everything else is as in * {@link deliveryRoute}: the read is authorized unless the URL carries a valid signature, the query * (`?conversion`, `?w`, `?q`, `?exp`, `?sig`) and `Accept` are honoured, the file is redirected or * streamed with its headers, and the library's errors are answered as HTTP. */ serve(ctx: DeliveryRouteContext, target: MediaRecord | string | null | undefined, options?: Omit<MediaDeliveryRouteOptions, 'param'>): Promise<unknown>; /** * A ready AdonisJS route handler that serves a media record — the delivery route every app was * hand-writing: * * ```ts * const serveMedia = media.access.deliveryRoute({ authorize: authorizers.owner() }) * router.get('/media/:id', serveMedia) * ``` * * - authorizes the read (`authorize`, or the collection's `access.read`; neither ⇒ refused), * unless the URL carries a valid `delivery.signing` signature — that signature IS the * authorization the app made when it issued the URL; * - passes `?conversion`, `?w`, `?q`, `Accept`, `?exp`, `?sig` through (on-demand resize, * format negotiation, signed URLs); * - redirects or streams per `delivery.mode`, with `Content-Type`, `Content-Length`, * `Content-Disposition: inline`, `Cache-Control` (private by default) and `Vary: Accept`; * - answers the library's errors as HTTP: 404 (unknown record or conversion), 400 (size not * allowed, not an image), 401/403 (not signed in / not allowed / bad signature). */ deliveryRoute(options?: MediaDeliveryRouteOptions): (ctx: DeliveryRouteContext) => Promise<unknown>; } //# sourceMappingURL=media_access.d.ts.map