import Inject from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../../../../server/model/SocialMailContext.js"; import { TempFileResult } from "@entity-access/server-pages/dist/Content.js"; import Page from "@entity-access/server-pages/dist/Page.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import { globalEnv } from "../../../../../common/globalEnv.js"; import TimedCache from "@entity-access/entity-access/dist/common/cache/TimedCache.js"; import FileConversionService from "../../../../../server/services/convert/FileConversionService.js"; const cache = new TimedCache(); /** * Snapshot url format * * /api/site/snapshot/{type}/{snapshotID}/{fileContentID}/{fileName} */ export default class extends Page { @Inject private db: SocialMailContext; @Inject private fcs: FileConversionService; async run() { const [type, siteID, fileContentID, _fileName] = this.childPath as any[]; this.db.verifyFilters = false; this.db.raiseEvents = false; const appFile = await this.getFile(siteID, fileContentID); const hostName = this.request.hostName?.toLocaleLowerCase(); const cors = await cache.getOrCreateAsync(hostName, async (x1) => { if (globalEnv.cdn === hostName || globalEnv.host === hostName) { return "*"; } const host = await this.db.websiteFolderHosts .where({ siteID, hostName }, (x, p) => x.folderID === p.siteID && x.host === p.hostName) .first(); if (host) { return "*"; } return null; }); if (cors) { this.response.setHeader("Access-Control-Allow-Origin", cors); } this.cacheControl = "public, max-age=2592000, immutable"; const fileName = this.childPath[this.childPath.length-1]; const file = await this.fcs.downloadConvertedFile({ type, appFile, fileName }); return new TempFileResult( file, { contentDisposition: "inline", immutable: true, etag: false } ); } async getFile(siteID: any, fileContentID: any) { const path = `${siteID}/%`; let appFile = await this.db.appFiles.where({ path, fileContentID}, (x, p) => Sql.text.like(x.path, p.path) && x.fileContentID === p.fileContentID ).first(); if (appFile) { return appFile; } const q = this.db.websiteVersions.where({ siteID }, (x, p) => x.folderID === p.siteID) .orderByDescending((x) => x.snapshotFolderID); let max; while(true) { const root = max ? await q .where({ start: max }, (x, p) => x.snapshotFolderID < p.start) .include((x) => x.snapshotFolder) .first() : await q.include((x) => x.snapshotFolder) .first(); if (!root) { throw new Error("Snapshot file not found"); } max = root.snapshotFolderID; const rootPath = root.snapshotFolder.path + "%"; appFile = await this.db.appFiles .where({ rootPath, fileContentID }, (x, p) => Sql.text.like(x.path, p.rootPath) && x.fileContentID === p.fileContentID) .include((x) => x.fileContent) .first(); if (appFile) { return appFile; } } } }