/* eslint-disable no-console */ import { file } from "tmp-promise"; import { promises as fsp } from "fs"; import * as tmp from "tmp"; import * as path from "path"; tmp.setGracefulCleanup(); import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import { Stream } from "stream"; import BaseStorage from "./BaseStorage.js"; import SocialMailContext from "../model/SocialMailContext.js"; import AppFile from "../model/entities/AppFile.js"; import FileContent from "../model/entities/FileContent.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import GZip from "./compression/gz.js"; import DiskCacheService from "../services/cache/DiskCacheService.js"; import { secureFetch } from "../services/root-certs/RootCertificates.js"; import { tempDiskCache } from "./tempDiskCache.js"; import CryptoService from "../services/CryptoService.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import mime from "mime-types"; // @ts-expect-error private const tmpdir = tempDiskCache.root; /** * This service is scoped to timely clean up the temp files after each scope. */ @RegisterScoped export default class TempFileService { private files: LocalFile[] = []; @Inject private storage: BaseStorage; @Inject private diskCache: DiskCacheService; @Inject private cryptoService: CryptoService; async downloadAppFile(appFile: AppFile) { let fc = appFile.fileContent; if (!fc) { const db = ServiceProvider.resolve(this, SocialMailContext); const fileID = appFile.appFileID; fc = await db.fileContents.where({ fileID }, (x, p) => x.appFiles.some((af) => af.appFileID === p.fileID)) .first(); } return this.downloadFileContent(fc, appFile); } async downloadFileContent( fc: FileContent | string | number | bigint, {name, contentType}: Partial): Promise { fc ??= void 0; if (typeof fc !== "object") { const db = ServiceProvider.resolve(this, SocialMailContext); fc = await db.fileContents.where({ id: fc}, (x, p) => x.fileContentID === p.id).first(); } const localCache = await this.storage.downloadFile(fc); const linkedFile = await this.diskCache.link(localCache, name, contentType); this.files.push(linkedFile); return linkedFile; // return this.createLink(name, localCache, contentType); // return new LocalFile(cachedPath, name, contentType, doNothing); } async downloadFileWithoutCache(f: AppFile) { let fc = f.fileContent; if (!fc) { const db = ServiceProvider.resolve(this, SocialMailContext); fc = await db.fileContents.where({ id: f.fileContentID}, (x, p) => x.fileContentID === p.id).first(); } let { stream } = await this.storage.streamFile(fc.cloudPath); if (fc.compression === "gz") { stream = GZip.unzipStream(stream); } const tf = await this.createFrom(f.name, stream, f.contentType); return tf; } async downloadCloudFile(cloudPath: string, fileName: string, contentType?: string) { try { const localFile = await this.diskCache.getOrCreateAsync(cloudPath, async (cf) => { const { stream } = await this.storage.streamFile(cloudPath); await cf.writeAll(stream); } ); if (fileName) { // const { ext } = path.parse(fileName); // const tf = await this.createLink(fileName, localFile, contentType); // return tf; const linkedFile = await this.diskCache.link(localFile, fileName, contentType); this.files.push(linkedFile); return linkedFile; } return localFile; // const cachedPath = path.join(cachePath , cloudPath); // const { dir } = path.parse(cachedPath); // const { ext } = path.parse(fileName); // if (!existsSync(dir)) { // mkdirSync(dir, { recursive: true }); // } // let tries = 10; // while (tries > 0) { // using lock = await LockFile.lock(cloudPath); // if (existsSync(cachedPath)) { // break; // } // const { stream } = await this.storage.streamFile(cloudPath); // try { // await fsp.writeFile(cachedPath, stream); // break; // } catch (error) { // // multiple file write might throw an exception.. // await sleep(1000); // tries--; // if (tries===0) { // throw new EntityAccessError(`Failed to write file due to error ${error.stack ?? error}`); // } // } // } // // const tf = await this.createTempFile(ext, fileName, contentType); // // await fsp.copyFile(cachedPath, tf.path); // // return tf; // return new LocalFile(cachedPath, fileName, contentType, doNothing); } catch (error) { console.error(`Failed to download cloud path ${cloudPath} ${error.stack ?? error}`); throw new Error(`Failed to download file`); } } public async createTempFile2(name: string, mimeType?: string) { mimeType ??= (mime.lookup(name) || "application/octet-stream"); const { ext } = path.parse(name); const tf = await file({ mode: 0o644, prefix: "tmp-" , postfix: ext, tmpdir }); const lf = new LocalFile(tf.path, name, mimeType, () => tf.cleanup()); this.files.push(lf); return lf; } public async createTempFile(ext: string = ".tmp", name?: string, mimeType?: string) { const tf = await file({ mode: 0o644, prefix: "tmp-" , postfix: ext, tmpdir }); const lf = new LocalFile(tf.path, name, mimeType, () => tf.cleanup()); this.files.push(lf); return lf; } public async download(inputUrl: string, name?: string, retry = 1): Promise { try { const parsedUrl = new URL(inputUrl); const urlFilePath = parsedUrl.pathname; const fileInfo = path.parse(urlFilePath); if (name && !name.endsWith(fileInfo.ext)) { name += fileInfo.ext; } const t = await this.createTempFile(fileInfo.ext, name); await this.fetch(inputUrl, t.path); return t; } catch (error) { if(--retry) { return this.download(inputUrl, name, retry); } throw error; } } public async downloadVerify(inputUrl: string, name?: string, contentHash?: string, retry = 1) { try { const parsedUrl = new URL(inputUrl); const urlFilePath = parsedUrl.pathname; const fileInfo = path.parse(urlFilePath); if (name && !name.endsWith(fileInfo.ext)) { name += fileInfo.ext; } const t = await this.createTempFile(fileInfo.ext, name); await this.fetch(inputUrl, t.path); // verify hash... const hash = await this.cryptoService.hashBuffer(t.openRead()); if (hash !== contentHash) { throw new EntityAccessError(`Hash mismatch error while downloading ${inputUrl}`); } return t; } catch (error) { if(--retry) { return this.download(inputUrl, name, retry); } throw error; } } public async createFrom(fileName: string, content: Buffer | Stream, contentType: string) { if (fileName) { fileName = fileName.replace(/([\/\<\>\:\"\\\|\?\*]+)/g, "-"); } else { fileName = "temp.dat"; } const qIndex = fileName.indexOf("?"); if (qIndex !== -1) { fileName = fileName.substring(0, qIndex); } const fileInfo = path.parse(fileName); const tf = await this.createTempFile(fileInfo.ext, fileName, contentType); await fsp.writeFile(tf.path, content as any); return tf; } // public async createLink(fileName: string, src: string | LocalFile, contentType: string) { // const qIndex = fileName.indexOf("?"); // if (qIndex !== -1) { // fileName = fileName.substring(0, qIndex); // } // if (fileName) { // fileName = fileName.replace(/([\/\<\>\:\"\\\|\?\*]+)/g, "-"); // } else { // fileName = "temp.dat"; // } // const fileInfo = path.parse(fileName); // // you can however create symbolic link under a folder // // and remove folder's write permission so file cannot be deleted // const tf = await this.createTempFile(fileInfo.ext, fileName, contentType); // if (platform() !== "win32") { // // this fails in docker alpine // // don't know why... // if (existsSync(tf.path)) { // await fsp.unlink(tf.path); // } // } // // await fsp.symlink(typeof src === "string" ? src : src.path, tf.path); // // This operation would be fast // // Disk Cache can be cleared anytime so we cannot create symbolic link. // // Alternative would be to create a hard link from the cache mount // await fsp.copyFile(typeof src === "string" ? src : src.path, tf.path); // return tf; // } [Symbol.dispose]() { for (const iterator of this.files) { iterator.delete().catch((error) => console.error(error)); } } private async fetch(inputUrl: string, filePath: string) { const rs = await secureFetch(inputUrl); if (rs.status >= 300) { // error... throw new Error(`Download ${inputUrl} failed \r\n${await rs.text()}`); } await fsp.writeFile(filePath, rs.body as any); return filePath; } }