/* eslint-disable no-console */ import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import TempFileService from "../../storage/TempFileService.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import AppFile from "../../model/entities/AppFile.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import CacheService from "../cache/CacheService.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import { globalEnv } from "../../../common/globalEnv.js"; import { join, parse } from "path"; import { rmdir, unlink } from "fs/promises"; import { randomBytes } from "crypto"; import { fetch, Agent } from "undici"; import { connect } from "net"; import { existsSync, mkdirSync } from "fs"; import Content from "@entity-access/server-pages/dist/Content.js"; import { Readable } from "stream"; interface IDownloadConvertedFile { appFile: AppFile; fileContentID?: number; type: string; fileName: string; senderDomain?: string; key?: string; } const newFolder = (root) => { for(;;) { const f = join(root, Date.now().toString(36) + "-" + randomBytes(8).readBigUInt64BE().toString(36)); if(!existsSync(f)) { mkdirSync(f, { recursive: true}); return f; } } }; const connectArgs = {} as any; let port = globalEnv.fcs.port as any; if (/^\d+$/i.test(port)) { port = Number(port); connectArgs.port = port; connectArgs.host = globalEnv.fcs.host; } else { connectArgs.path = port; } const dispatcher = new Agent({ connect: (options, callback) => { try { const s= connect(connectArgs, () => callback(null, s)); s.on("error", (e) => { if (e.name !== "InformationalError") { console.error(e); } callback(e, null); }); } catch (error) { callback(error, null); } } }); @RegisterScoped export default class FileConversionService { @Inject private tempFileService: TempFileService; @Inject private cacheService: CacheService; async transform(type: string, source: LocalFile, { fileName = void 0, senderDomain = void 0, ... extra } = {}) { fileName ??= source.fileName; await using fcsSource = await this.copyToFCS(source); const u = new URL(`http://localhost/convert/${type}/${encodeURIComponent(fileName)}`); u.searchParams.set("filePath", fcsSource.path); if (senderDomain) { u.searchParams.set("senderDomain", senderDomain); } const rs = await fetch(u, { dispatcher }); if (rs.status > 399) { throw new Error(await rs.text()); } const { ext, base } = parse(fileName); const tf = await this.tempFileService.createTempFile(ext, base, source.contentType); await tf.writeAll(rs.body as any); return tf; } async extractText(source: LocalFile) { await using fcsSource = await this.copyToFCS(source); const u = new URL(`http://localhost/extract/text/${encodeURIComponent(source.fileName)}`); u.searchParams.set("filePath", fcsSource.path); const rs = await fetch(u, { dispatcher }); if (rs.status > 399) { throw new Error(await rs.text()); } const tf = await this.tempFileService.createTempFile(".txt", "output.txt", "text/plain"); await tf.writeAll(rs.body as any); return tf; } async generateCaptcha(code: string) { const u = new URL(`http://localhost/cached/captcha/v2/${code}`); const rs = await fetch(u, { dispatcher }); if (rs.status > 399) { throw new Error(await rs.text()); } return Content.readable( Readable.fromWeb(rs.body) , { status: 200, headers: { "content-disposition": "inline", "content-type": "image/avif" } }); } async copyToFCS(src: LocalFile) { const name = src.fileName; const folder = newFolder("/fcs/cache"); const fp = join(folder, name); const f = new LocalFile(fp, name, void 0, () => unlink(fp).then(() => rmdir(folder), console.error).catch(console.error)); await src.copyTo(f); return f; } async downloadConvertedFile({ appFile, fileContentID, type, fileName, key = `/file-1/${type}/${fileContentID ?? appFile.fileContentID}/${fileName}`, senderDomain }: IDownloadConvertedFile ): Promise { const ttl = TimeSpan.fromDays(30); let transform = false; // transform here... if (/^(size|max|jpg|png|webp|gif|face\-circle|remove-bg)\(?/i.test(type)) { transform = true; } if (/^webm\-branded?$/i.test(type)) { transform = true; } if (/^(webm|mp4)/i.test(type)) { transform = true; } if (/^(pdf|html)$/i.test(type)) { transform = true; } if(/^(webp|avif)\-animated$/i.test(type)) { transform = true; } if(!transform) { return await this.downloadFileContent(appFile, fileContentID); } return await this.cacheService.get({ key, ttl, factory: async () => { const f = await this.downloadFileContent(appFile); return await this.transform(type, f, { fileName, senderDomain }); }}); } async downloadFileContent(appFile: AppFile, fileContentID?: number) { if(!fileContentID || fileContentID === appFile.fileContentID) { return this.tempFileService.downloadAppFile(appFile); } const { appFileID } = appFile; const db = ServiceProvider.resolve(this, SocialMailContext); const fc = await db.fileContents .where({ fileContentID, appFileID }, (x, p) => x.fileContentID === p.fileContentID && x.versions.some((v) => v.fileID === p.appFileID) ) .firstOrFail(); return this.tempFileService.downloadFileContent(fc, appFile); } }