///
import {
GetObjectCommand,
ListObjectsV2Command,
S3Client,
} from "@aws-sdk/client-s3";
import { generateTimeStringForFileName } from "../util.ts";
import { getLogger } from "../logger.ts";
import { AwsContext, s3MoveObject } from "./context.ts";
import { getConfig } from "../config.ts";
export class AwsMailRetriever {
readonly liveMailPrefix = "mail/live/";
readonly archiveMailPrefix = "mail/archive/";
readonly mailBucket = getConfig().getValue("awsMailBucket");
private readonly s3Client;
private readonly liveMailRecyclerAborter = new AbortController();
constructor(
aws: AwsContext,
private readonly callback: (rawMail: string) => Promise,
) {
const { region, credentials } = aws;
this.s3Client = new S3Client({ region, credentials });
}
setupLiveMailRecycler() {
Deno.cron("live-mail-recycler", "0 */6 * * *", {
signal: this.liveMailRecyclerAborter.signal,
}, () => {
});
}
generateArchivePrefix(instant: Date | Temporal.Instant): string {
return `${this.archiveMailPrefix}${
generateTimeStringForFileName(instant, true)
}/`;
}
async listLiveMails(): Promise {
const listCommand = new ListObjectsV2Command({
Bucket: this.mailBucket,
Prefix: this.liveMailPrefix,
});
const res = await this.s3Client.send(listCommand);
if (res.Contents == null) {
getLogger().warn("Listing live mails in S3 returns null Content.");
return [];
}
const result: string[] = [];
for (const object of res.Contents) {
if (object.Key != null) {
result.push(object.Key);
} else {
getLogger().warn(
"Listing live mails in S3 returns an object with no Key.",
);
}
}
return result;
}
async deliverS3MailObject(messageId: string) {
const mailPath = `${this.liveMailPrefix}${messageId}`;
const command = new GetObjectCommand({
Bucket: this.mailBucket,
Key: mailPath,
});
const res = await this.s3Client.send(command);
if (res.Body == null) {
// TODO: Better error.
throw new Error();
}
const rawMail = await res.Body.transformToString();
await this.callback(rawMail);
// TODO: Continue here.
await s3MoveObject(this.s3Client, this.mailBucket, mailPath, );
}
async recycleLiveMails() {
const mails = await this.listLiveMails();
}
}