/* eslint-disable no-console */ import Inject, { RegisterScoped, ServiceObject, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import { join, parse } from "path"; import DBConfig from "../DBConfig.js"; import TempFileService from "../../storage/TempFileService.js"; import SiteDiskContentCache from "./SiteDiskContentCache.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import { cacheFor, ICacheContainer, ObjectCache } from "../../../common/cacheFor.js"; import WebContentTranspileService from "./web-content/WebContentTranspileService.js"; import { ISiteFolder } from "./ISiteFolder.js"; import EncryptionService from "../encryption/EncryptionService.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import ReplicaReader from "../replica/ReplicaReader.js"; import HtmlForEmailService from "../html/HtmlForEmailService.js"; import { Base36 } from "../../../common/Base36.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import type WebSite from "../../model/entities/WebSite.js"; import { globalEnv } from "../../../common/globalEnv.js"; import ApexDomain from "../../../common/ApexDomain.js"; const cacheVersion = "c3"; /** * We cannot read from replica as relative path can change anytime, only absolute file content id can be read from replica. */ @RegisterScoped export default class WebSiteContentService extends ServiceObject implements ICacheContainer { @Inject dbConfig: DBConfig; @Inject siteCache: SiteDiskContentCache; cache: ObjectCache; @Inject replicaReader: ReplicaReader; @Inject tfs: TempFileService; @Inject ecs: EncryptionService; @Inject db: SocialMailContext; postInit() { this.cache = this.siteCache.cache; } @cacheFor() async isMailDomain(host) { const { domain, subdomain } = ApexDomain.getApexDomain(host); if (subdomain && /mail|social/i.test(subdomain)) { return this.db.hostedDomains.where({ domain }, (x, p) => x.domain.name === p.domain).first(); } return null; } @cacheFor() async getCurrentSnapshotFolder(host: string) { let site: WebSite; let draftMode = false; let cacheKey: string; // we will only decrypt site info form server-[site-info].root as the cluster may not want to // lookup every website in every virtual server and no one outside cluster can route here const { groups } = /^(?\d{1,16})\-(?[^\.]{1,400})\.sites\./i.exec(host) ?? {}; const siteInfo = groups?.siteInfo; if (siteInfo) { let [folderID, time] = this.ecs.general.decrypt(siteInfo, "hex").split("-"); // for safety, time should not be more than 24 hours folderID = Base36.decode(folderID); time = Base36.decode(time); const dt = DateTime.from(time); if (dt.msSinceEpoch < DateTime.now.addDays(-1).msSinceEpoch) { throw new EntityAccessError("Invalid draft url, please regenerate the url again"); } site = await this.db.websiteFolders.where({ folderID }, (x, p) => x.folderID === p.folderID as any) .first(); if (!site) { console.warn(`Site ${folderID} not found`); return null; } // we need to create disk snapshot of the last time here... draftMode = true; cacheKey = `${site.folderID.toString(36)}-${site.lastModified ? DateTime.from(site.lastModified).msSinceEpoch.toString(36) : "z"}`; } else { site = await this.db.websiteFolders.where({ host }, (x, p) => x.hosts.some((h) => h.host === p.host) && x.isSuspended === false) .first(); } if (!site) { return null; } if (!draftMode && !site.currentVersionID) { return null; } if(!draftMode) { cacheKey = site.currentVersionID.toString(); } let remoteUrl = site.remoteUrl?.trim(); if(remoteUrl?.endsWith("/")) { remoteUrl = remoteUrl.slice(0, -1); } return { snapshotFolderID: site.currentVersionID, folderID: site.folderID, isDesign: site.isDesign, icon: site.icon, eSiteID: this.ecs.general.encrypt(site.folderID.toString()), remoteUrl: site.remoteUrl, isTemplate: site.isTemplate, hasEmailTemplates: site.hasEmailTemplates, draftMode, cacheKey: site.cacheKey ?? cacheKey, pageReadyDelayMS: site.pageReadyDelayMS, previewAnimated: site.previewAnimated, previewAnimatedMobile: site.previewAnimatedMobile, host } as ISiteFolder; } async getCurrentSnapshot(folderID, currentVersionID) { const siteHost = await this.db.websiteFolderHosts.where({ folderID }, (x, p) => x.folderID === p.folderID ) .include((x) => x.folder) .first(); if (!siteHost) { return null; } const { folder: site, host } = siteHost; site.currentVersionID = currentVersionID; return { snapshotFolderID: site.currentVersionID, folderID: site.folderID, isDesign: site.isDesign, eSiteID: this.ecs.general.encrypt(site.folderID.toString()), remoteUrl: site.remoteUrl, isTemplate: site.isTemplate, hasEmailTemplates: site.hasEmailTemplates, draftMode: false, icon: site.icon, cacheKey: site.cacheKey ?? site.currentVersionID.toString(), pageReadyDelayMS: site.pageReadyDelayMS, previewAnimated: site.previewAnimated, previewAnimatedMobile: site.previewAnimatedMobile, host } as ISiteFolder; } async getWebSiteFolder(folderID) { return this.db.websiteFolders.where({ folderID }, (x, p) => x.folderID === p.folderID) .first(); } @cacheFor() async getWildcardHostFor(folderID, preview) { const w = globalEnv.wildcardDomain; return this.replicaReader.query((db) => db.websiteFolderHosts.where({ folderID, w }, (x, p) => x.folderID === p.folderID) .orderByDescending({ w, preview: !!preview }, (x, p) => Sql.text.endsWith(x.host ,p.w) === p.preview) .first()); } @cacheFor() async getWebSite(host) { const folder = await this.replicaReader.query((db) => db.websiteFolders.where({ host }, (x, p) => x.hosts.some((s) => s.host === p.host)) .first()); if (!folder) { return null; } const { folderID, currency, fromEmail, supportEmail, emailBCC } = folder; return { folderID, currency, fromEmail, supportEmail, emailBCC }; } async getFile(_v: string | ISiteFolder, folderID, ... path: string[]) { const fileInfo = await this.getFileInfo(_v, folderID, ... path); if (!fileInfo) { return; } if (fileInfo.isFolder) { return; } return this.tfs.downloadFileContent(fileInfo.fileContentID, fileInfo); } async getDbFile(site: ISiteFolder, folderID, ... path: string[]) { const fileInfo = await this.getDbFileInfo(site.cacheKey, folderID, path); if (!fileInfo) { return; } if (fileInfo.isFolder) { return; } return this.tfs.downloadFileContent(fileInfo.fileContentID, fileInfo); } getFileFromInfo(fileInfo: IFileInfo) { return this.tfs.downloadFileContent(fileInfo.fileContentID, fileInfo); } async getFileInfo(s: ISiteFolder | string, folderID, ... segments: string[]): Promise { if (typeof s === "string") { return this._getFileInfo(s, folderID, segments); } if (s.draftMode) { return this.getDbFileInfo(s.cacheKey, folderID, segments); } return this._getFileInfo(s.cacheKey, folderID, segments); } async getNamedPageContent(host: string, files: string[]) { const site = await this.getCurrentSnapshotFolder(host); for (const file of files) { const contentFile = await this.getSnapshotFile(site, [file]); if (contentFile) { return contentFile; } } } /** * The reason we are not storing in Cached as we do not want to * save `@latest` replacements as we may want to clear out cache * immediately. * @param folderID * @param path * @param src * @returns */ async getSnapshotFile(siteFolder: ISiteFolder, path: string[]) { const { snapshotFolderID, draftMode, folderID , cacheKey } = siteFolder; const src = await this.getFile(siteFolder, draftMode ? folderID : snapshotFolderID, ... path); if (!src) { return; } const fileName = path.pop(); const addPreview = fileName === "index.html" && path.length === 0; if (/html$/i.test(src.contentType)) { const currentPath = path.join("/"); const filePath = join(cacheKey, "transformed", ... path, fileName); return this.siteCache.htmlCache.getOrCreateAsync(filePath, async (dest) => { const ts = ServiceProvider.resolve(this, WebContentTranspileService); let content = await ts.transformHtml(siteFolder, src, currentPath, addPreview); if (siteFolder.hasEmailTemplates) { // transform email templates.. const { folderID: siteID, host } = siteFolder; const url = `https://${host}/${currentPath}`; const es = ServiceProvider.resolve(this, HtmlForEmailService); content = await es.prepareHtml({ html: content, siteID, path, url }); } await dest.writeAllText(content); }); } if (/css$/i.test(src.contentType)) { const currentPath = path.join("/"); const filePath = join(cacheKey, "transformed", ... path, fileName); return this.siteCache.htmlCache.getOrCreateAsync(filePath, async (dest) => { const ts = ServiceProvider.resolve(this, WebContentTranspileService); const content = await ts.transformCss(siteFolder, src, currentPath); await dest.writeAllText(content); }); } return src; } async toEditorDraftCDNUrl({ folderID = void 0, eSiteID = void 0 }, file: { fileContentID, name, contentType }) { const cdn = globalEnv.cdn ? `https://${globalEnv.cdn}` : ""; const eFileContentID = this.ecs.general.encrypt(file.fileContentID.toString()); const { name, ext } = parse(file.name); eSiteID ??= this.ecs.general.encrypt(folderID.toString()); // this case is only for the draft mode // as in draft mode, fileContentID will be direct descendent of the site folder // using CDN could be reasonable if users in same region are viewing draft again and again in team if (/^image\//i.test(file.contentType)) { // avif must be resized as avif only if (/avif/i.test(file.contentType)) { return `${cdn}/social-mail/public/file/avif(900)/${eSiteID}/${eFileContentID}/${name}.${cacheVersion}.avif`; } // but not svg if (!/svg/i.test(file.contentType)) { return `${cdn}/social-mail/public/file/max(900)/${eSiteID}/${eFileContentID}/${name}.${cacheVersion}.webp`; } } return `${cdn}/social-mail/public/file/view/${eSiteID}/${eFileContentID}/${name}.${cacheVersion}${ext}`; } async toDraftCDNUrl({ folderID = void 0, eSiteID = void 0, draftMode = void 0 }, file: { fileContentID, name, contentType }) { const cdn = globalEnv.cdn ? `https://${globalEnv.cdn}` : ""; const eFileContentID = this.ecs.general.encrypt(file.fileContentID.toString()); const { name, ext } = parse(file.name); eSiteID ??= this.ecs.general.encrypt(folderID.toString()); // this case is only for the draft mode // as in draft mode, fileContentID will be direct descendent of the site folder // using CDN could be reasonable if users in same region are viewing draft again and again in team if (draftMode) { // using CDN could be reasonable if users in same region are viewing draft again and again in team return `${cdn}/social-mail/public/file/view/${eSiteID}/${eFileContentID}/${name}.${cacheVersion}${ext}`; } return `${cdn}/social-mail/site/snapshot/view/${eSiteID}/${eFileContentID}/${name}.${cacheVersion}${ext}`; } @cacheFor() async getDbFileInfo(_v: string | number, folderID, segments: string[]): Promise { const [top, ... paths] = segments; const eTop = top.replace(/(\%|\_)/i, (x) => "\\" + x); const child = await this.db.appFiles .where({ folderID, eTop },(x, p) => x.parentID === p.folderID && Sql.text.iLike(x.name, p.eTop)) .orderBy((x) => x.isDeleted) .thenByDescending({ top }, (x, p) => x.name === p.top) .first(); if (!child) { return null; } if (paths.length === 0) { const { name, contentType, appFileID, isFolder, url, fileContentID, path } = child; return { name, contentType, appFileID, isFolder, url, fileContentID, path }; } return await this.getDbFileInfo(_v, child.appFileID, paths); } @cacheFor() private async _getFileInfo(_v: string | number, folderID, segments: string[]): Promise { const [top, ... paths] = segments; const eTop = top.replace(/(\%|\_)/i, (x) => "\\" + x); const child = await this.replicaReader.query((db) => db.appFiles .where({ folderID, eTop },(x, p) => x.parentID === p.folderID && Sql.text.iLike(x.name, p.eTop)) .orderBy((x) => x.isDeleted) .thenByDescending({ top }, (x, p) => x.name === p.top) .first()); if (!child) { return null; } if (paths.length === 0) { const { name, contentType, appFileID, isFolder, url, fileContentID, path } = child; return { name, contentType, appFileID, isFolder, url, fileContentID, path }; } return await this._getFileInfo(_v, child.appFileID, paths); } } export interface IFileInfo { name: string; contentType: string; appFileID: number; isFolder: boolean; url: string; path: string; fileContentID: number; }