import Inject from "@entity-access/entity-access/dist/di/di.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js" import TempFileService from "../../storage/TempFileService.js"; import BaseStorage from "../../storage/BaseStorage.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import { globalEnv } from "../../../common/globalEnv.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import PendingPostReceiveWorkflow from "../pending/PendingPostReceiveWorkflow.js"; export default class DownloadExternalAttachmentWorkflow extends Workflow { async run() { for(let i = 0; i<10; i++) { if(await this.download(i)) { return "ok"; } await this.delay(TimeSpan.fromSeconds(5 * (i + 1))); } } @UniqueActivity async download( attempt, @Inject db?: SocialMailContext, @Inject tfs?: TempFileService, @Inject storage?: BaseStorage ) { try { const attachmentID = this.input; const ea = await db.externalAttachments.withKeys({ attachmentID }).select(); if(!ea) { throw new EntityAccessError("Could not load external attachment"); } const { name, emailID, contentID } = ea; let { link } = ea; const url = new URL(link); if(url.hostname === globalEnv.cdn) { // need to replace cdn as we are probably on same server... url.hostname = globalEnv.host; link = url.toString(); } console.log(`Downloading external ${link}`); const file = await tfs.download(link, name); await storage.saveFile(file, { emailID, name, contentType: file.contentType, contentID }); await db.externalAttachments.withKeys({ attachmentID }).delete(); await PendingPostReceiveWorkflow.queue(this.context); } catch (error) { console.error(error); return false; } return true; } }