@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
174 lines • 7.28 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { userInfo } from 'node:os';
import { BaseCommand, flags } from '@adonisjs/core/ace';
import { allTenants } from '../agora/tenancy.js';
import { buildConsoleService, readConsoleServiceConfig } from '../dashboard/console_service.js';
import { resolveConsoleTenantScope } from '../dashboard/tenant_scope.js';
import { MediaManager } from '../media_manager.js';
/** Who the `media:*` commands act as, in log lines: `cli:<os user>`, or `cli`. */
export function cliActor() {
try {
const name = userInfo().username;
return name ? `cli:${name}` : 'cli';
}
catch {
return 'cli';
}
}
/** A refusal the command reports as is (exit code 1), without a stack. */
export class CommandRefusal extends Error {
}
/**
* Base of the `media:*` console commands. Each one runs the SAME `DashboardService` the media
* console's JSON API and its developer tools run (same disks, same `actions` switch, same tenant
* confinement), built from `config/media_dashboard.ts`. Nothing about storage is reimplemented here.
*
* - `--json` prints one JSON document (the console API's response shape) instead of a table.
* - `--tenant <id>` confines a command to one organization when tenancy is on; without it the
* command sees every organization (the operator running `node ace` is trusted like a console
* viewer granted `tenants: '*'`).
* - A failure prints the reason and exits with code 1.
*/
export class MediaConsoleCommand extends BaseCommand {
static options = { startApp: true };
async run() {
try {
const manager = (await this.app.container.make(MediaManager));
const config = readConsoleServiceConfig(this.app.config);
if (!manager.tenancy?.enabled) {
if (this.tenant !== undefined) {
throw new CommandRefusal('--tenant needs tenancy on (`tenancy` in config/media.ts)');
}
await this.handle(buildConsoleService(manager, config));
return;
}
const scope = resolveConsoleTenantScope({
granted: '*',
own: undefined,
selected: this.tenant,
});
// The command has no request tenant: run across every tenant, confined by the scope above.
await allTenants(() => this.handle(buildConsoleService(manager, config, scope.ids)));
}
catch (error) {
this.fail(error);
}
}
/** Report `error` and exit with code 1. */
fail(error) {
this.logger.error(error instanceof Error ? error.message : String(error));
this.exitCode = 1;
}
/** Print `value` as one JSON document. */
printJson(value) {
this.logger.log(JSON.stringify(value, null, 2));
}
/** Print rows as a table, or `empty` when there are none. */
printTable(head, rows, empty = 'Nothing to show.') {
if (rows.length === 0) {
this.logger.info(empty);
return;
}
const table = this.ui.table();
table.head(head);
for (const row of rows)
table.row(row);
table.render();
}
/** Print `key: value` lines, skipping undefined values. */
printFields(fields) {
for (const [label, value] of fields) {
if (value === undefined)
continue;
this.logger.log(`${label}: ${value === null ? '-' : String(value)}`);
}
}
/** The default disk of the console (the manager default when browsable, else the first). */
defaultDisk(service) {
const disks = service.disks().data;
const disk = disks.find((candidate) => candidate.default) ?? disks[0];
if (!disk)
throw new CommandRefusal('the console has no disks');
return disk.name;
}
/**
* Refuse a change up front when the console's `actions` switch is off (the service refuses it
* too; this only saves asking a question whose answer cannot be acted on).
*/
assertActions(service) {
if (!service.topology().actions) {
throw new CommandRefusal('actions are disabled on this console: set `actions: true` in config/media_dashboard.ts');
}
}
/**
* Ask before a destructive change unless `force`. Returns whether to go ahead; a "no" exits with
* code 1.
*/
async confirmed(force, question) {
if (force)
return true;
const ok = await this.prompt.confirm(question, { default: false });
if (!ok) {
this.logger.info('Cancelled: nothing was changed.');
this.exitCode = 1;
}
return ok;
}
/** Log an action through the app logger, with the actor (`cli:<os user>`). */
async audit(action) {
const line = `[@adonis-agora/media] ${cliActor()}${this.tenant !== undefined ? ` (organization ${this.tenant})` : ''}: ${action}`;
try {
const logger = (await this.app.container.make('logger'));
if (typeof logger?.info === 'function')
logger.info(line);
}
catch {
// No app logger bound: the command's own output already says what happened.
}
}
}
__decorate([
flags.boolean({ description: 'Print JSON instead of a table' })
], MediaConsoleCommand.prototype, "json", void 0);
__decorate([
flags.string({
description: 'Organization (tenant) id to act on when tenancy is on (default: every one)',
})
], MediaConsoleCommand.prototype, "tenant", void 0);
/** A size in bytes for humans (`1.2 MB`), or `-` when unknown. */
export function formatBytes(bytes) {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes))
return '-';
if (bytes < 1024)
return `${bytes} B`;
const units = ['KB', 'MB', 'GB', 'TB'];
let value = bytes / 1024;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${value.toFixed(1)} ${units[unit]}`;
}
/** A query-string-shaped request for the console's list readers (`list_api.ts`). */
export function listRequest(query) {
const qs = {};
for (const [key, value] of Object.entries(query)) {
if (value === undefined)
continue;
if (value !== null && typeof value === 'object') {
const nested = Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
if (Object.keys(nested).length > 0)
qs[key] = nested;
continue;
}
qs[key] = value;
}
return { request: { qs: () => qs } };
}
//# sourceMappingURL=console_command.js.map