2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2020 Signal Messenger, LLC
|
2021-07-28 21:37:09 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
import { isNumber, omit } from 'lodash';
|
|
|
|
|
|
|
|
import { strictAssert } from '../util/assert';
|
|
|
|
import { dropNull } from '../util/dropNull';
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { DownloadedAttachmentType } from '../types/Attachment';
|
2021-07-28 21:37:09 +00:00
|
|
|
import * as MIME from '../types/MIME';
|
|
|
|
import * as Bytes from '../Bytes';
|
2021-09-24 00:49:05 +00:00
|
|
|
import { getFirstBytes, decryptAttachment } from '../Crypto';
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { ProcessedAttachment } from './Types.d';
|
2021-07-28 21:37:09 +00:00
|
|
|
import type { WebAPIType } from './WebAPI';
|
|
|
|
|
|
|
|
export async function downloadAttachment(
|
|
|
|
server: WebAPIType,
|
|
|
|
attachment: ProcessedAttachment
|
|
|
|
): Promise<DownloadedAttachmentType> {
|
|
|
|
const cdnId = attachment.cdnId || attachment.cdnKey;
|
|
|
|
const { cdnNumber } = attachment;
|
|
|
|
|
|
|
|
if (!cdnId) {
|
|
|
|
throw new Error('downloadAttachment: Attachment was missing cdnId!');
|
|
|
|
}
|
|
|
|
|
|
|
|
strictAssert(cdnId, 'attachment without cdnId');
|
|
|
|
const encrypted = await server.getAttachment(cdnId, dropNull(cdnNumber));
|
|
|
|
const { key, digest, size, contentType } = attachment;
|
|
|
|
|
|
|
|
if (!digest) {
|
|
|
|
throw new Error('Failure: Ask sender to update Signal and resend.');
|
|
|
|
}
|
|
|
|
|
|
|
|
strictAssert(key, 'attachment has no key');
|
|
|
|
strictAssert(digest, 'attachment has no digest');
|
|
|
|
|
2021-09-24 00:49:05 +00:00
|
|
|
const paddedData = decryptAttachment(
|
2021-07-28 21:37:09 +00:00
|
|
|
encrypted,
|
2021-09-24 00:49:05 +00:00
|
|
|
Bytes.fromBase64(key),
|
|
|
|
Bytes.fromBase64(digest)
|
2021-07-28 21:37:09 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
if (!isNumber(size)) {
|
|
|
|
throw new Error(
|
|
|
|
`downloadAttachment: Size was not provided, actual size was ${paddedData.byteLength}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-09-24 00:49:05 +00:00
|
|
|
const data = getFirstBytes(paddedData, size);
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
...omit(attachment, 'digest', 'key'),
|
|
|
|
|
2021-10-05 22:10:08 +00:00
|
|
|
size,
|
2021-07-28 21:37:09 +00:00
|
|
|
contentType: contentType
|
2021-08-09 20:06:21 +00:00
|
|
|
? MIME.stringToMIMEType(contentType)
|
2021-07-28 21:37:09 +00:00
|
|
|
: MIME.APPLICATION_OCTET_STREAM,
|
|
|
|
data,
|
|
|
|
};
|
|
|
|
}
|