/* eslint-disable no-console */ import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import AppTempFile from "../../model/entities/AppTempFile.js"; import TempFileService from "../../storage/TempFileService.js"; import { parse } from "path"; import BaseStorage from "../../storage/BaseStorage.js"; import { FileType } from "../../../common/FileType.js"; import mime from "mime-types"; import AppFile from "../../model/entities/AppFile.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import { JSDOM } from 'jsdom'; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import AsyncTaskManager from "../../../common/AsyncTaskManager.js"; import { globalEnv } from "../../../common/globalEnv.js"; @RegisterScoped export default class AppTempFileService { @Inject db: SocialMailContext; @Inject tfs: TempFileService; @Inject storage: BaseStorage; taskManager: AsyncTaskManager = new AsyncTaskManager(); async copyTo(folder: AppTempFile, appFile: AppFile, deleteNonExistent = true) { await using tx = await this.db.connection.createTransaction(); const currentPath = `${appFile.path}%`; if (deleteNonExistent) { await this.db.appFiles .where({ folderID: appFile.appFileID, currentPath }, (x, p) => Sql.text.like(x.path, p.currentPath) && x.appFileID !== p.folderID ) .update((x) => ({ isDeleted: true })); await this.db.fileContents .where({ folderID: appFile.appFileID, currentPath }, (x, p) => x.appFiles.some((f) => Sql.text.like(f.path, p.currentPath) && f.appFileID !== p.folderID )) .update((x) => ({ deleted: true })); } const size = await this.copyFolder(folder, "/", appFile, appFile.path); await this.db.appFiles.statements.update({ fileSize: size as any as number}, { appFileID: appFile.appFileID }); await tx.commit(); } async copyFolder(root: AppTempFile, path: string, appFolder: AppFile, currentPath: string) { const rootID = root.tempFileID; const destFolderID = appFolder.appFileID; console.log(`Copying folder ${path} to ${appFolder.path} - ${appFolder.appFileID} - ${appFolder.parentID}`); const children = await this.db.appTempFiles .where({rootID, path: `${path}%`, pathLength: path.length }, (x, p) => x.rootID === p.rootID && Sql.text.like(x.path, p.path) && !Sql.text.includes(Sql.text.substring(x.path, p.pathLength), "/") ) .toArray(); let size = BigInt(0); for (const child of children) { const { name } = child; let existing = await this.db.appFiles.where({ name, destFolderID }, (x, p) => x.parentID === p.destFolderID && x.name === p.name) .first(); if (existing && existing.isFolder !== child.isFolder) { if(existing.fileContentID && existing.fileContentID !== child.fileContentID) { await this.db.fileContents.statements.update({ deleted: true,}, { fileContentID: existing.fileContentID}); } await this.db.appFiles.statements.update({ isDeleted: true,}, { appFileID: existing.appFileID}); existing = null; } if (!existing) { existing = await this.db.appFiles.statements.insert({ fileContentID: child.fileContentID, name: child.name, contentType: child.contentType, dateCreated: child.dateCreated, dateUpdated: child.dateCreated, parentID: destFolderID, isDeleted: false, isFolder: child.isFolder, fileSize: child.fileSize, }); } else { existing.isFolder = child.isFolder; existing.fileContentID = child.fileContentID; existing.contentType = child.contentType; existing.dateCreated = child.dateCreated; existing.dateUpdated = child.dateCreated; existing.parentID = destFolderID; existing.isDeleted = false; existing.fileSize = child.fileSize; if (existing.isFolder) { existing.contentType = "folder"; } await this.db.appFiles.statements.update({ isFolder: child.isFolder, fileContentID: child.fileContentID, contentType: existing.contentType, dateCreated: child.dateCreated, dateUpdated: child.dateCreated, parentID: destFolderID, isDeleted: false, fileSize: child.fileSize }, { appFileID: existing.appFileID }); } size += BigInt(existing.fileSize); const newPath = `${currentPath}${existing.appFileID}/`; existing.path = newPath; let hidden = existing.hidden || false; if (/(image|video|audio)\//i.test(existing.contentType)) { hidden = true; } await this.db.appFiles.statements.update({ path: newPath, hidden }, { appFileID: existing.appFileID}); if (child.isFolder) { const folderSize = await this.copyFolder(root, path + child.name + "/", existing, newPath); await this.db.appFiles.statements.update({ fileSize: folderSize as any as number}, { appFileID: existing.appFileID}); size += folderSize; } } return size; } async downloadTemplate(url: string, transform?: {[key: string]: string}) { const tmp = await this.createFolder(); if (url.endsWith("/")) { url = url.slice(0, -1); } url += "/social-mail/site/download/files"; await this.downloadFolder(tmp, url, "", transform); await this.taskManager.wait(); return tmp; } async createFolder() { return this.db.appTempFiles.statements.insert({ name: "", path: "/", contentType: "folder" }); } async downloadFolder(root: AppTempFile, url: string, path: string, transform: {[key: string]: string}) { const r = await fetch(url); const contentType = r.headers.get("content-type"); if ( /json/i.test(contentType) && r.headers.get("x-content-type") === "folder") { const files: Partial[] = await r.json(); for (const file of files) { const childPath = path + "/" + file.name; const childUrl = url + "/" + file.name; if (file.isFolder) { // we need to create a folder here... const childFolder = await this.db.appTempFiles.statements.insert({ rootID: root.tempFileID, name: file.name, isFolder: true, path: childPath, contentType: "folder" }); (root.descendants ??= []).push(childFolder); await this.downloadFolder(root, childUrl, childPath, transform); continue; } void this.taskManager.run(() => this.downloadFile(root, childUrl, childPath, file.contentHash, transform)) .catch(console.error); } return; } } async downloadFile(folder: AppTempFile, url: string, path: string, contentHash: string, transform: {[key: string]: string}) { const { base: name } = parse(path); let localFile = await this.tfs.downloadVerify(url, name, contentHash, 3); // if transform // do the transform here... const contentType = mime.lookup(name) || "application/octet-stream"; if (/\/html$/i.test(contentType)) { localFile = await this.transformFile(localFile, transform); } const scope = ServiceProvider.from(this); const fc = await this.storage.saveFileContent(localFile, scope, FileType.canBeCompressed({ fileName: name, contentType })); const file = await this.db.appTempFiles.statements.insert({ rootID: folder.tempFileID, fileContentID: fc.fileContentID, contentType, path, name, fileSize: localFile.contentSize }); (folder.descendants ??= []).push(file); return file; } async transformFile(localFile: LocalFile, transform: { [key: string]: string; }) { let modified = false; const text = await localFile.readAsText(); // replace template-part... const window = new JSDOM(text); const document = window.window.document; for(const e of document.documentElement.querySelectorAll("*")) { if (e.tagName === "LINK") { if (e.getAttribute("rel") === "stylesheet" && e.getAttribute("styler-css") === "styler.css") { const href = e.getAttribute("href"); const hrefStyler = `//${globalEnv.uiCDN}/npm/@social-mail/social-mail-client@latest/styler-lite/styler.css`; if (href !== hrefStyler) { modified = true; e.setAttribute("href", hrefStyler); } } } for(const k of Array.from(e.getAttributeNames())) { if (!/^data\-/.test(k)) { continue; } const v = e.getAttribute(k); const tv = transform[v]; if (!tv) { continue; } switch(k) { case "data-template-part": switch(v) { case "name": e.removeAttribute(k); e.textContent = tv; modified = true; break; } break; } } } if (modified) { const savedFile = await this.tfs.createTempFile(".html", localFile.fileName, localFile.contentType); let docType = ""; if (document.doctype?.name === "html") { docType = "\n"; } await savedFile.writeAllText(docType + document.documentElement.outerHTML); return savedFile; } return localFile; } }