improve media mime type inferring + added uploadToEntity in media api

This commit is contained in:
dswbx
2025-02-14 18:02:43 +01:00
parent 4bd201d454
commit fb76f8d789
12 changed files with 147 additions and 69 deletions

View File

@@ -126,9 +126,8 @@ export class AppMedia extends Module<typeof mediaConfigSchema> {
const payload = this.uploadedEventDataToMediaPayload(e.params);
await mutator.insertOne(payload);
mutator.__unstable_toggleSystemEntityCreation(true);
console.log("App:storage:file uploaded", e);
},
"sync"
{ mode: "sync", id: "add-data-media" }
);
// when file is deleted, sync with media entity
@@ -144,7 +143,7 @@ export class AppMedia extends Module<typeof mediaConfigSchema> {
console.log("App:storage:file deleted", e);
},
"sync"
{ mode: "sync", id: "delete-data-media" }
);
}

View File

@@ -1,5 +1,10 @@
import type { FileListObject } from "media";
import { type BaseModuleApiOptions, ModuleApi, type PrimaryFieldType } from "modules/ModuleApi";
import {
type BaseModuleApiOptions,
ModuleApi,
type PrimaryFieldType,
type TInput
} from "modules/ModuleApi";
import type { FileWithPath } from "ui/elements/media/file-selector";
export type MediaApiOptions = BaseModuleApiOptions & {};
@@ -53,12 +58,24 @@ export class MediaApi extends ModuleApi<MediaApiOptions> {
});
}
protected uploadFile(body: File | ReadableStream, filename?: string) {
let type: string = "application/octet-stream";
let name: string = filename || "";
protected uploadFile(
body: File | ReadableStream,
opts?: {
filename?: string;
path?: TInput;
_init?: Omit<RequestInit, "body">;
}
) {
const headers = {
"Content-Type": "application/octet-stream",
...(opts?._init?.headers || {})
};
let name: string = opts?.filename || "";
try {
type = (body as File).type;
if (!filename) {
if (typeof (body as File).type !== "undefined") {
headers["Content-Type"] = (body as File).type;
}
if (!opts?.filename) {
name = (body as File).name;
}
} catch (e) {}
@@ -67,32 +84,67 @@ export class MediaApi extends ModuleApi<MediaApiOptions> {
name = name.split("/").pop() || "";
}
const init = {
...(opts?._init || {}),
headers
};
if (opts?.path) {
return this.post(opts.path, body, init);
}
if (!name || name.length === 0) {
throw new Error("Invalid filename");
}
return this.post(["upload", name], body, {
headers: {
"Content-Type": type
}
});
return this.post(opts?.path ?? ["upload", name], body, init);
}
async upload(item: Request | Response | string | File | ReadableStream, filename?: string) {
async upload(
item: Request | Response | string | File | ReadableStream,
opts: {
filename?: string;
_init?: Omit<RequestInit, "body">;
path?: TInput;
} = {}
) {
if (item instanceof Request || typeof item === "string") {
const res = await this.fetcher(item);
if (!res.ok || !res.body) {
throw new Error("Failed to fetch file");
}
return this.uploadFile(res.body, filename);
return this.uploadFile(res.body, opts);
} else if (item instanceof Response) {
if (!item.body) {
throw new Error("Invalid response");
}
return this.uploadFile(item.body, filename);
return this.uploadFile(item.body, {
...(opts ?? {}),
_init: {
...(opts._init ?? {}),
headers: {
...(opts._init?.headers ?? {}),
"Content-Type": item.headers.get("Content-Type") || "application/octet-stream"
}
}
});
}
return this.uploadFile(item, filename);
return this.uploadFile(item, opts);
}
async uploadToEntity(
entity: string,
id: PrimaryFieldType,
field: string,
item: Request | Response | string | File | ReadableStream,
opts?: {
_init?: Omit<RequestInit, "body">;
}
) {
return this.upload(item, {
...opts,
path: ["entity", entity, id, field]
});
}
deleteFile(filename: string) {

View File

@@ -1,5 +1,6 @@
import { type EmitsEvents, EventManager } from "core/events";
import { type TSchema, isFile } from "core/utils";
import { isMimeType } from "media/storage/mime-types-tiny";
import * as StorageEvents from "./events";
import type { FileUploadedEventData } from "./events";
@@ -80,37 +81,33 @@ export class Storage implements EmitsEvents {
noEmit?: boolean
): Promise<FileUploadedEventData> {
const result = await this.#adapter.putObject(name, file);
if (typeof result === "undefined") {
throw new Error("Failed to upload file");
}
let info: FileUploadPayload;
let info: FileUploadPayload = {
name,
meta: {
size: 0,
type: "application/octet-stream"
},
etag: typeof result === "string" ? result : ""
};
switch (typeof result) {
case "undefined":
throw new Error("Failed to upload file");
case "string": {
if (isFile(file)) {
info = {
name,
meta: {
size: file.size,
type: file.type
},
etag: result
};
break;
} else {
// get object meta
const meta = await this.#adapter.getObjectMeta(name);
if (!meta) {
throw new Error("Failed to get object meta");
}
if (typeof result === "object") {
info = result;
} else if (isFile(file)) {
info.meta.size = file.size;
info.meta.type = file.type;
}
info = { name, meta, etag: result };
}
break;
// try to get better meta info
if (!isMimeType(info?.meta.type, ["application/octet-stream", "application/json"])) {
const meta = await this.#adapter.getObjectMeta(name);
if (!meta) {
throw new Error("Failed to get object meta");
}
case "object":
info = result;
break;
info.meta = meta;
}
const eventData = {

View File

@@ -17,5 +17,6 @@ export function getRandomizedFilename(file: File | string, length = 16): string
throw new Error("Invalid file name");
}
// @todo: use uuid instead?
return [randomString(length), getExtension(filename)].filter(Boolean).join(".");
}