2020-10-30 20:34:04 +00:00
|
|
|
// Copyright 2020 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2023-10-30 16:24:28 +00:00
|
|
|
import type { AttachmentType } from '../types/Attachment';
|
2024-05-02 17:11:34 +00:00
|
|
|
import { downloadAttachment as doDownloadAttachment } from '../textsecure/downloadAttachment';
|
2020-07-07 00:39:55 +00:00
|
|
|
|
2024-04-16 00:11:48 +00:00
|
|
|
export class AttachmentNotFoundOnCdnError extends Error {}
|
2020-07-07 00:39:55 +00:00
|
|
|
export async function downloadAttachment(
|
2021-07-09 19:36:10 +00:00
|
|
|
attachmentData: AttachmentType
|
2024-04-16 00:11:48 +00:00
|
|
|
): Promise<AttachmentType> {
|
2021-07-09 19:36:10 +00:00
|
|
|
let migratedAttachment: AttachmentType;
|
|
|
|
|
2022-06-13 21:39:35 +00:00
|
|
|
const { server } = window.textsecure;
|
|
|
|
if (!server) {
|
|
|
|
throw new Error('window.textsecure.server is not available!');
|
|
|
|
}
|
|
|
|
|
2021-07-09 19:36:10 +00:00
|
|
|
const { id: legacyId } = attachmentData;
|
|
|
|
if (legacyId === undefined) {
|
|
|
|
migratedAttachment = attachmentData;
|
|
|
|
} else {
|
|
|
|
migratedAttachment = {
|
|
|
|
...attachmentData,
|
|
|
|
cdnId: String(legacyId),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-07-07 00:39:55 +00:00
|
|
|
let downloaded;
|
|
|
|
try {
|
2022-06-13 21:39:35 +00:00
|
|
|
downloaded = await doDownloadAttachment(server, migratedAttachment);
|
2020-07-07 00:39:55 +00:00
|
|
|
} catch (error) {
|
2024-02-09 02:17:52 +00:00
|
|
|
// Attachments on the server expire after 30 days, then start returning 404 or 403
|
|
|
|
if (error && (error.code === 404 || error.code === 403)) {
|
2024-04-16 00:11:48 +00:00
|
|
|
throw new AttachmentNotFoundOnCdnError(error.code);
|
2020-07-07 00:39:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return downloaded;
|
|
|
|
}
|