import { ForeignKeyFilter } from "@entity-access/entity-access/dist/model/events/EntityEvents.js"; import AppFile from "../entities/AppFile.js"; import { IEntityQuery } from "@entity-access/entity-access/dist/model/IFilterWithParameter.js"; import AuthenticatedEvents from "./AuthenticatedEvents.js"; import ChangeEntry from "@entity-access/entity-access/dist/model/changes/ChangeEntry.js"; import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import CryptoService from "../../services/CryptoService.js"; import SocialMailContext from "../SocialMailContext.js"; import BaseStorage from "../../storage/BaseStorage.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import FileTagService from "../../services/tags/FileTagService.js"; import TempFileService from "../../storage/TempFileService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import FileVersionService from "../../services/files/FileVersionService.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import UpdateFolderSize from "../../workflows/storage/files/UpdateFolderSize.js"; import FileAccessService from "../../services/files/FileAccessService.js"; import ExternalQuery from "@entity-access/server-pages/dist/decorators/ExternalQuery.js"; import EmailLogService from "../../services/email-logs/EmailLogService.js"; import Page from "@entity-access/server-pages/dist/Page.js"; import StoreConfigService from "../../services/store/StoreConfigService.js"; import WebSiteChannelService from "../../smtp/services/WebSiteChannelService.js"; import { StoreMediaFile } from "../entities/StoreMediaFile.js"; import { Email } from "../entities/Email.js"; import WebSite from "../entities/WebSite.js"; import EncryptionService from "../../services/encryption/EncryptionService.js"; import SessionSecurity from "@entity-access/server-pages/dist/services/SessionSecurity.js"; import ChannelEmail from "../entities/ChannelEmail.js"; import FilePathService from "../../services/files/FilePathService.js"; import { AppWorkflowContext } from "../../workflows/AppWorkflowContext.js"; import ChannelUrlService from "../../services/channels/ChannelUrlService.js"; import AppFileDownloadService from "../../services/files/AppFileDownloadService.js"; export default class AppFileEvents extends AuthenticatedEvents { @Inject cryptoService: CryptoService; @Inject db: SocialMailContext; @Inject storage: BaseStorage; @Inject tagService: FileTagService; @Inject tempFileService: TempFileService; @Inject versionService: FileVersionService; @Inject fileAccessService: FileAccessService; @Inject eternity: AppWorkflowContext; @Inject encryptionService: EncryptionService; @Inject sessionSecurity: SessionSecurity; @Inject fps: FilePathService; @ExternalQuery async storeItemFiles(folderID) { const page = ServiceProvider.resolve(this, Page as any) as Page; const host = page.request.host; const storeConfig = ServiceProvider.resolve(this, StoreConfigService); const db = ServiceProvider.resolve(this, SocialMailContext); const folder = await storeConfig.getRootFolder(folderID, host); const path = folder.path + "%"; return db.appFiles.where({ path }, (x, p) => Sql.text.like(x.path, p.path)); } @ExternalQuery async channelPostFiles(post: Email | ChannelEmail) { return this.db.appFiles.where(post, (x, p) => x.emailID === p.emailID); } // @ExternalQuery // async channelAllFiles(post: Mailbox) { // return this.db.appFiles.where(post, (x, p) => x.email.status === "published" // && x.email.channelEmails.some((m) => m.mailboxID === p.mailboxID)); // } // async channelFiles(emailID) { // } @ExternalQuery async channelEmailFiles(emailID) { const page = ServiceProvider.resolve(this, Page as any) as Page; const host = page.request.host; const wcs = ServiceProvider.resolve(this, WebSiteChannelService); const { mailboxes, domains } = await wcs.getChannelAssociations(host); let q = mailboxes ? this.db.appFiles.where({ mailboxes }, (x, p) => x.email.status === "published" && x.email.channelEmails.some((mc)=> Sql.in(mc.mailboxID, p.mailboxes ))) : this.db.appFiles.where({ domains }, (x, p) => x.email.status === "published" && x.email.channelEmails.some((mc)=> Sql.in(mc.mailbox.domainID, p.domains ))) ; if (emailID) { q = q.where({ emailID} , (x, p) => x.emailID === p.emailID); } return q; } @ExternalQuery async channelFiles(mailboxID) { const page = ServiceProvider.resolve(this, Page as any) as Page; const host = page.request.host; const wcs = ServiceProvider.resolve(this, WebSiteChannelService); const { mailboxes, domains } = await wcs.getChannelAssociations(host); let q = this.db.appFiles.where((x) => x.email.status === "published"); if (mailboxID) { q = q.where({ mailboxID }, (x, p) => x.email.channelEmails.some((m) => m.mailboxID === p.mailboxID)); } else { if (mailboxes) { q = q.where({ mailboxes }, (x, p) => x.email.channelEmails.some((mc)=> Sql.in(mc.mailboxID, p.mailboxes ))); } else { q = q.where({ domains }, (x, p) => x.email.channelEmails.some((mc)=> Sql.in(mc.mailbox.domainID, p.domains ))); } } return q; } @ExternalQuery async children(folderID, path: string, sha256: string) { const { readFileAccess } = this.sessionUser; let q = this.db.appFiles .where({ folderID }, (x, p) => x.appFileID === p.folderID); if (!this.sessionUser.isGlobalEditor) { q = q.where({ readFileAccess}, (x, p) => Sql.text.likeAny(x.path, p.readFileAccess)); } let file = await q.firstOrFail(); let last: string; if (path) { const names = path.split("/"); last = names.pop(); for (const name of names) { file = await this.db.appFiles .where({ folderID, name }, (x, p) => x.parentID === p.folderID && x.name === p.name && x.isDeleted === false) .first(); if(!file) { return this.db.appFiles.where(void 0, (x, p) => x.appFileID === 0); } folderID = file.appFileID; } } q = this.db.appFiles.where({ folderID }, (x, p) => x.parentID === p.folderID && x.isDeleted === false); if (last) { q = q.where({ last }, (x, p) => x.name === p.last); } if (sha256) { q = q.where({ sha256 }, (x, p) => x.fileContent.contentHash === p.sha256); } return q; } @ExternalQuery async templateSnapshot(websiteFolderID) { this.sessionUser.ensureLoggedIn(); const db = ServiceProvider.resolve(this, SocialMailContext); const current = await db.appFiles .where({ websiteFolderID }, (x, p) => x.currentVersionWebSites.some((v) => v.folderID === p.websiteFolderID && v.isTemplate === true ) ) .first(); const path = current.path + "%"; return db.appFiles.where({ path }, (x, p) => Sql.text.like(x.path, p.path)); } filter(query: IEntityQuery): IEntityQuery { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (this.sessionUser.isGlobalEditor) { return query; } const { userID, readFileAccess } = this.sessionUser; const tmpFolder= `/tmp-${userID}`; return query.where({ userID, tmpFolder, readFileAccess }, (x, p) => x.creatorID === p.userID || Sql.text.likeAny(x.path, p.readFileAccess) /** Template creator must assign read/write permission separately */ // || x.templates.some((t) => // t.domain.domainUsers.some((d) => d.userID === p.userID) // || t.mailbox.userMailboxes.some((u) => u.userID === p.userID) // || t.mailbox.domain.domainUsers.some((u) => u.userID === p.userID)) /** Email Attachment will be downloaded directly */ // || x.email.mailboxes.some((mb) => // mb.mailbox.userMailboxes.some((um) => um.userID === p.userID) // || mb.mailbox.domain.hostedDomain.domainUsers.some((du) => du.userID === p.userID ) ); } modify(query: IEntityQuery): IEntityQuery { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (this.sessionUser.isGlobalEditor) { return query; } const { userID, writeFileAccess } = this.sessionUser; const tmpFolder= `/tmp-${userID}`; return query.where({ userID, tmpFolder, writeFileAccess }, (x, p) => x.creatorID === p.userID || Sql.text.likeAny(x.path, p.writeFileAccess) /** Email Attachments cannot be manipulated anyway */ // || x.email.mailboxes.some((mb) => // mb.mailbox.userMailboxes.some((um) => um.userID === p.userID) // || mb.mailbox.domain.hostedDomain.domainUsers.some((du) => du.userID === p.userID ) // ) ); } delete(query: IEntityQuery): IEntityQuery { return this.modify(query); } includeFilter(query: IEntityQuery, type?: any, key?: string): IEntityQuery { if (type === StoreMediaFile) { return query; } if (type === WebSite) { return query; } if (type === Email) { return query; } if (type === ChannelEmail) { return query; } return this.filter(query); } async beforeInsert(entity: AppFile, entry: ChangeEntry) { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if(entity.parentID === null && entity.isFolder && !entity.snapshotParentID) { // only admin can create root drives... if(this.verify) { if(!this.sessionUser.isAdmin) { throw new EntityAccessError("Only admin can create root folder") } } } if (this.sessionUser?.userID) { if (!this.sessionUser.isGlobalEditor) { entity.creatorID = this.sessionUser.userID; } else { entity.creatorID ??= this.sessionUser.userID; } } const now = DateTime.now; entity.dateCreated = entity.dateUpdated = now; if (entity.isFolder) { entity.contentType ||= "folder"; } // moved to after insert // if(entity.isFolder && !entity.parentID) { // // create permissions... // entity.accessList ??= []; // entity.accessList.push(this.db.fileAccessList.add({ // dateCreated: now, // dateUpdated: now, // type: "delegate" // })); // } await this.saveSourceFile(entity); } async afterInsert(entity: AppFile, entry: ChangeEntry) { const userID = entity.creatorID ?? this.sessionUser?.userID; if(userID && entity.isFolder && !entity.parentID) { // create permissions... // entity.accessList ??= []; // entity.accessList.push(this.db.fileAccessList.add({ // dateCreated: now, // dateUpdated: now, // type: "delegate" // })); const now = DateTime.now; await this.db.fileAccessList.statements.insert({ fileID: entity.appFileID, userID, dateCreated: now, dateUpdated: now, type: "delegate" }); } await this.updateFilePath(entity); if (entity.fileContentID && entity.parentID) { await this.versionService.saveVersion(this.sessionUser, entity); } await this.updateFolderSize(entity); } async beforeDelete(entity: AppFile, entry: ChangeEntry) { // ensure we do not have any children of this file const hasChildren = await this.db.appFiles.where(entity, (x, p) => x.parentID === p.appFileID).some(); if (hasChildren) { throw new EntityAccessError(`Folder is not empty`); } if (entity.emailID) { const isDraft = await this.db.emails.where(entity, (x, p) => x.emailID === p.emailID && x.status === "draft").some(); if (!isDraft) { throw new EntityAccessError(`Attachment cannot be deleted since it is not in draft`); } // we will delete attachments... await this.db.fileContents.where(entity, (x, p) => x.appFiles.some((f) => f.emailID === p.emailID)) .update((x) => ({ deleted: true })); return; } if (this.sessionUser.isGlobalEditor) { // we will allow delete return; } if (entity.parentID) { entity.isDeleted = true; entry.status = "modified"; return; } } async beforeUpdate(entity: AppFile, entry: ChangeEntry) { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (this.sessionUser?.userID) { entity.creatorID = this.sessionUser.userID; } if (entry.isModified("parentID")) { if (entity.parentID && entity.path) { const pf = await this.db.appFiles.where(entity, (x, p) => x.appFileID === p.parentID).first(); if (pf.path !== entity.path && pf.path.startsWith(entity.path)) { throw new EntityAccessError(`Circular path detected ${pf.path} starts with ${entity.path}`); } } } if (entry.isModified("isDeleted")) { if (!entity.isDeleted) { // since this entity is undeleted // we have to rename the folder if the parent contains same named item... const originalName = entity.name; while(true) { const cf = await this.db.appFiles .where(entity, (x, p) => x.parentID === p.parentID && x.name === p.name && x.appFileID !== p.appFileID && x.isDeleted === false) .first(); if (cf) { entity.name = `${originalName}-${Date.now()}`; continue; } break; } // we need to undelete all ancestors or else file will not be visible const parentIDs: any[] = entity.path.split("/").filter((x) => x); await this.db.appFiles .where({ parentIDs}, (x, p) => Sql.in(x.appFileID, p.parentIDs) && x.isDeleted === true ) .update(() => ({ isDeleted: false })); } else { if (entity.isFolder) { // we need to delete all descendents of this file... const path = entity.path + "%"; const { appFileID } = entity; await this.db.appFiles .where({ appFileID, path}, (x, p) => x.appFileID !== p.appFileID && Sql.text.like(x.path, p.path)) .update((x) => ({ isDeleted: true })); } } } await this.saveSourceFile(entity); entity.dateUpdated = DateTime.now; } async afterUpdate(entity: AppFile, entry: ChangeEntry) { if (entry.isUpdated("parentID")) { await this.updateFilePath(entity); } if (entity.parentID && entity.fileContentID) { if (entry.isUpdated("fileContentID") || entry.isModified("parentID")) { await this.versionService.saveVersion(this.sessionUser, entity); } } if (entry.isUpdated("parentID")) { await this.updateFolderSize(entity); } } onForeignKeyFilter(filter: ForeignKeyFilter): IEntityQuery { if (filter.is((x) => x.creator)) { return null; } if (filter.is((x) => x.fileContent)) { return null; } } async saveSourceFile(entity: AppFile) { const { sourceUrl, sourceEmailLogID } = entity; let { file } = entity; // copy from sourceUrl if (sourceUrl) { // added easy way to copy if (sourceUrl.startsWith("/social-mail/fd/")) { // we should download the image with conversion here... const [_sm, _fd, type, eFileID, eFileContentID, name ] = sourceUrl.substring(1).split("/"); const afds = ServiceProvider.resolve(this, AppFileDownloadService); file = await afds.getConverted({ type, eFileContentID, eFileID, name }); } else { file = await this.tempFileService.download(sourceUrl); } } if (sourceEmailLogID) { const els = ServiceProvider.resolve(this, EmailLogService); file = await els.load({ logID: sourceEmailLogID }); } if (file) { const fileContent = await this.storage.saveFileContent(file); entity.fileContentID = fileContent.fileContentID; entity.fileSize = fileContent.contentSize; entity.contentType ||= file.contentType; // entity.tags = await this.db.appFileTags.where(entity, (x, p) => x.appFileID === p.appFileID).toArray(); // entity.tags ??= []; this.db.queuePostSaveTask(async () => { const tags = await this.tagService.getTags(file.fileName, file.contentType); const { appFileID} = entity; for(const { tagID } of tags) { await this.db.appFileTags .withKeys({ appFileID, tagID }) .selectOrInsert(); } }); // const tags = await this.tagService.getTags(file.fileName, file.contentType); // for (const { tagID } of tags) { // if (entity.tags.some((t) => t.tagID === tagID)) { // continue; // } // entity.tags.push(this.db.appFileTags.add({ tagID })); // } } if (file) { await file.delete(); } } // @ExternalInvoke // async download(appFile: AppFile, type: string, fileContentID: any, fileName: string) { // fileContentID = this.encryptionService.general.decrypt(fileContentID.toString()) as any; // const fcs = ServiceProvider.resolve(this, FileConversionService); // const tfr = new TempFileResult(await fcs.downloadConvertedFile({ // appFile, // fileName, // fileContentID, // type // }), { // cacheControl: `public, max-age=3461421` // }); // return tfr; // } // @ExternalInvoke // async downloadChild(appFile: AppFile, ... segments: string[]) { // const { db } = this; // for (const element of segments) { // appFile = await db.appFiles.statements.select({}, { parentID: appFile.appFileID, name: element }); // } // const fcs = ServiceProvider.resolve(this, FileConversionService); // const tfr = new TempFileResult(await fcs.downloadConvertedFile({ // appFile, // fileName: appFile.name, // fileContentID: appFile.fileContentID, // type: "download" // }), { // cacheControl: `public, max-age=3461421` // }); // return tfr; // } preJson(entity: AppFile): AppFile { let { emailID: postID } = entity; if (postID) { this.sessionSecurity.injectPublicKey(entity); } else { this.sessionSecurity.injectKey(entity); } const { $key } = entity as any; let { fileContentID } = entity; if (postID) { let domain = entity.watermark; // we will climb up to see if we are a part of channel email // we will use domain of the page... if(!domain) { const page = ServiceProvider.resolve(this, Page as any) as Page; domain = page.request.URL.hostname; } const urlService = ServiceProvider.resolve(this, ChannelUrlService); const eDomain = this.encryptionService.general.encrypt(domain); fileContentID = this.encryptionService.general.encrypt(fileContentID.toString()) as any; postID = this.encryptionService.general.encrypt(postID.toString()) as any; const isPublished = entity.watermark || /published/i.test(entity.email?.status) || entity.email?.channelEmails?.some((x) => x.datePublished !== null); Object.defineProperty(entity, "postID", { value: postID, enumerable: true }); if (isPublished) { Object.defineProperty(entity, "url", { value: urlService.toChannelFileUrl({ eDomain, file: entity, postID, publicRead: true }) , enumerable: true }); } else { Object.defineProperty(entity, "url", { value: `/social-mail/fd/view/${$key}/${fileContentID}/${entity.name}`, enumerable: true }); } // Object.defineProperty(entity, "downloadUrl", { value: `/social-mail/fd/download/${$key}/${fileContentID}/${entity.name}`, enumerable: true }); } else { if (fileContentID) { fileContentID = this.encryptionService.general.encrypt(fileContentID.toString()) as any; Object.defineProperty(entity, "url", { value: `/social-mail/fd/view/${$key}/${fileContentID}/${entity.name}`, enumerable: true }); // Object.defineProperty(entity, "downloadUrl", { value: `/social-mail/fd/download/${$key}/${fileContentID}/${entity.name}`, enumerable: true }); } } if (entity.contentType === "application/site") { Object.defineProperty(entity, "url", { value: `/social-mail/site/draft/${$key}/`, enumerable: true }); } return entity; } private async updateFolderSize(entity: AppFile) { if (entity.parentID) { await this.eternity.queue(UpdateFolderSize, entity.parentID, { id: `update-folder-size-${entity.parentID}` }); } } private updateFilePath(entity: AppFile) { return this.fps.update(entity); } }