signal-desktop/ts/util/queueAttachmentDownloads.ts

496 lines
14 KiB
TypeScript
Raw Normal View History

2023-01-03 19:55:46 +00:00
// Copyright 2020 Signal Messenger, LLC
2022-03-04 21:14:52 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
import { partition } from 'lodash';
import * as AttachmentDownloads from '../messageModifiers/AttachmentDownloads';
import * as log from '../logging/log';
import { isLongMessage } from '../types/MIME';
import { getMessageIdForLogging } from './idForLogging';
2022-03-04 21:14:52 +00:00
import {
copyStickerToAttachments,
savePackMetadata,
getStickerPackStatus,
} from '../types/Stickers';
import dataInterface from '../sql/Client';
import type { AttachmentType } from '../types/Attachment';
import type { EmbeddedContactType } from '../types/EmbeddedContact';
import type {
2023-03-27 23:48:57 +00:00
EditHistoryType,
MessageAttributesType,
QuotedMessageType,
} from '../model-types.d';
import * as Errors from '../types/errors';
2023-03-27 23:48:57 +00:00
import {
getAttachmentSignature,
isDownloading,
isDownloaded,
} from '../types/Attachment';
import type { StickerType } from '../types/Stickers';
import type { LinkPreviewType } from '../types/message/LinkPreviews';
import { isNotNil } from './isNotNil';
2022-03-04 21:14:52 +00:00
type ReturnType = {
bodyAttachment?: AttachmentType;
2022-03-04 21:14:52 +00:00
attachments: Array<AttachmentType>;
2023-03-27 23:48:57 +00:00
editHistory?: Array<EditHistoryType>;
preview: Array<LinkPreviewType>;
2022-03-04 21:14:52 +00:00
contact: Array<EmbeddedContactType>;
quote?: QuotedMessageType;
sticker?: StickerType;
2022-03-04 21:14:52 +00:00
};
// Receive logic
// NOTE: If you're changing any logic in this function that deals with the
// count then you'll also have to modify ./hasAttachmentsDownloads
export async function queueAttachmentDownloads(
message: MessageAttributesType
): Promise<ReturnType | undefined> {
const attachmentsToQueue = message.attachments || [];
const messageId = message.id;
const idForLogging = getMessageIdForLogging(message);
let count = 0;
let bodyAttachment;
2022-03-04 21:14:52 +00:00
2023-03-27 23:48:57 +00:00
const idLog = `queueAttachmentDownloads(${idForLogging}})`;
2022-03-04 21:14:52 +00:00
log.info(
2023-03-27 23:48:57 +00:00
`${idLog}: Queueing ${attachmentsToQueue.length} attachment downloads`
2022-03-04 21:14:52 +00:00
);
const [longMessageAttachments, normalAttachments] = partition(
attachmentsToQueue,
attachment => isLongMessage(attachment.contentType)
);
if (longMessageAttachments.length > 1) {
2023-03-27 23:48:57 +00:00
log.error(`${idLog}: Received more than one long message attachment`);
2022-03-04 21:14:52 +00:00
}
log.info(
2023-03-27 23:48:57 +00:00
`${idLog}: Queueing ${longMessageAttachments.length} long message attachment downloads`
2022-03-04 21:14:52 +00:00
);
if (longMessageAttachments.length > 0) {
count += 1;
[bodyAttachment] = longMessageAttachments;
}
if (!bodyAttachment && message.bodyAttachment) {
count += 1;
bodyAttachment = message.bodyAttachment;
}
if (bodyAttachment) {
await AttachmentDownloads.addJob(bodyAttachment, {
2022-03-04 21:14:52 +00:00
messageId,
type: 'long-message',
index: 0,
});
}
log.info(
2023-03-27 23:48:57 +00:00
`${idLog}: Queueing ${normalAttachments.length} normal attachment downloads`
2022-03-04 21:14:52 +00:00
);
2023-03-27 23:48:57 +00:00
const { attachments, count: attachmentsCount } = await queueNormalAttachments(
idLog,
messageId,
normalAttachments,
message.editHistory?.flatMap(x => x.attachments ?? [])
2022-03-04 21:14:52 +00:00
);
2023-03-27 23:48:57 +00:00
count += attachmentsCount;
2022-03-04 21:14:52 +00:00
const previewsToQueue = message.preview || [];
log.info(
2023-03-27 23:48:57 +00:00
`${idLog}: Queueing ${previewsToQueue.length} preview attachment downloads`
2022-03-04 21:14:52 +00:00
);
2023-03-27 23:48:57 +00:00
const { preview, count: previewCount } = await queuePreviews(
idLog,
messageId,
previewsToQueue,
message.editHistory?.flatMap(x => x.preview ?? [])
2022-03-04 21:14:52 +00:00
);
2023-03-27 23:48:57 +00:00
count += previewCount;
2022-03-04 21:14:52 +00:00
log.info(
`${idLog}: Queueing ${message.quote?.attachments?.length ?? 0} ` +
'quote attachment downloads'
);
const { quote, count: thumbnailCount } = await queueQuoteAttachments(
idLog,
messageId,
message.quote,
message.editHistory?.map(x => x.quote).filter(isNotNil) ?? []
);
count += thumbnailCount;
2022-03-04 21:14:52 +00:00
const contactsToQueue = message.contact || [];
log.info(
2023-03-27 23:48:57 +00:00
`${idLog}: Queueing ${contactsToQueue.length} contact attachment downloads`
2022-03-04 21:14:52 +00:00
);
const contact = await Promise.all(
contactsToQueue.map(async (item, index) => {
if (!item.avatar || !item.avatar.avatar) {
return item;
}
// We've already downloaded this!
if (item.avatar.avatar.path) {
2023-03-27 23:48:57 +00:00
log.info(`${idLog}: Contact attachment already downloaded`);
2022-03-04 21:14:52 +00:00
return item;
}
count += 1;
return {
...item,
avatar: {
...item.avatar,
avatar: await AttachmentDownloads.addJob(item.avatar.avatar, {
messageId,
type: 'contact',
index,
}),
},
};
})
);
let { sticker } = message;
if (sticker && sticker.data && sticker.data.path) {
2023-03-27 23:48:57 +00:00
log.info(`${idLog}: Sticker attachment already downloaded`);
2022-03-04 21:14:52 +00:00
} else if (sticker) {
2023-03-27 23:48:57 +00:00
log.info(`${idLog}: Queueing sticker download`);
2022-03-04 21:14:52 +00:00
count += 1;
const { packId, stickerId, packKey } = sticker;
const status = getStickerPackStatus(packId);
let data: AttachmentType | undefined;
if (status && (status === 'downloaded' || status === 'installed')) {
try {
data = await copyStickerToAttachments(packId, stickerId);
} catch (error) {
log.error(
2023-03-27 23:48:57 +00:00
`${idLog}: Problem copying sticker (${packId}, ${stickerId}) to attachments:`,
Errors.toLogFormat(error)
2022-03-04 21:14:52 +00:00
);
}
}
if (!data && sticker.data) {
data = await AttachmentDownloads.addJob(sticker.data, {
messageId,
type: 'sticker',
index: 0,
});
}
if (!status) {
// Save the packId/packKey for future download/install
void savePackMetadata(packId, packKey, { messageId });
2022-03-04 21:14:52 +00:00
} else {
await dataInterface.addStickerPackReference(messageId, packId);
}
if (!data) {
throw new Error('queueAttachmentDownloads: Failed to fetch sticker data');
}
sticker = {
...sticker,
packId,
data,
};
}
2023-03-27 23:48:57 +00:00
let { editHistory } = message;
if (editHistory) {
log.info(`${idLog}: Looping through ${editHistory.length} edits`);
editHistory = await Promise.all(
editHistory.map(async edit => {
const { attachments: editAttachments, count: editAttachmentsCount } =
await queueNormalAttachments(
idLog,
messageId,
edit.attachments,
attachments
);
count += editAttachmentsCount;
if (editAttachmentsCount !== 0) {
log.info(
`${idLog}: Queueing ${editAttachmentsCount} normal attachment ` +
`downloads (edited:${edit.timestamp})`
);
}
2023-03-27 23:48:57 +00:00
const { preview: editPreview, count: editPreviewCount } =
await queuePreviews(idLog, messageId, edit.preview, preview);
count += editPreviewCount;
if (editPreviewCount !== 0) {
log.info(
`${idLog}: Queueing ${editPreviewCount} preview attachment ` +
`downloads (edited:${edit.timestamp})`
);
}
2023-03-27 23:48:57 +00:00
return {
...edit,
attachments: editAttachments,
preview: editPreview,
};
})
);
}
log.info(`${idLog}: Queued ${count} total attachment downloads`);
2022-03-04 21:14:52 +00:00
if (count <= 0) {
return;
}
return {
attachments,
2023-03-27 23:48:57 +00:00
bodyAttachment,
2022-03-04 21:14:52 +00:00
contact,
2023-03-27 23:48:57 +00:00
editHistory,
preview,
2022-03-04 21:14:52 +00:00
quote,
sticker,
};
}
2023-03-27 23:48:57 +00:00
async function queueNormalAttachments(
idLog: string,
messageId: string,
attachments: MessageAttributesType['attachments'] = [],
otherAttachments: MessageAttributesType['attachments']
): Promise<{
attachments: Array<AttachmentType>;
count: number;
}> {
// Look through "otherAttachments" which can either be attachments in the
// edit history or the message's attachments and see if any of the attachments
// are the same. If they are let's replace it so that we don't download more
// than once.
// We don't also register the signatures for "attachments" because they would
// then not be added to the AttachmentDownloads job.
const attachmentSignatures: Map<string, AttachmentType> = new Map();
otherAttachments?.forEach(attachment => {
const signature = getAttachmentSignature(attachment);
if (signature) {
attachmentSignatures.set(signature, attachment);
}
2023-03-27 23:48:57 +00:00
});
let count = 0;
const nextAttachments = await Promise.all(
attachments.map((attachment, index) => {
if (!attachment) {
return attachment;
}
// We've already downloaded this!
if (isDownloaded(attachment)) {
log.info(`${idLog}: Normal attachment already downloaded`);
return attachment;
}
const signature = getAttachmentSignature(attachment);
const existingAttachment = signature
? attachmentSignatures.get(signature)
: undefined;
// We've already downloaded this elsewhere!
if (
existingAttachment &&
(isDownloading(existingAttachment) || isDownloaded(existingAttachment))
) {
log.info(
`${idLog}: Normal attachment already downloaded in other attachments. Replacing`
);
// Incrementing count so that we update the message's fields downstream
count += 1;
return existingAttachment;
}
count += 1;
return AttachmentDownloads.addJob(attachment, {
messageId,
type: 'attachment',
index,
});
})
);
return {
attachments: nextAttachments,
count,
};
}
function getLinkPreviewSignature(preview: LinkPreviewType): string | undefined {
const { image, url } = preview;
if (!image) {
return;
}
return `<${url}>${getAttachmentSignature(image)}`;
}
async function queuePreviews(
idLog: string,
messageId: string,
previews: MessageAttributesType['preview'] = [],
otherPreviews: MessageAttributesType['preview']
): Promise<{ preview: Array<LinkPreviewType>; count: number }> {
// Similar to queueNormalAttachments' logic for detecting same attachments
// except here we also pick by link preview URL.
const previewSignatures: Map<string, LinkPreviewType> = new Map();
otherPreviews?.forEach(preview => {
const signature = getLinkPreviewSignature(preview);
if (!signature) {
return;
}
previewSignatures.set(signature, preview);
});
let count = 0;
const preview = await Promise.all(
previews.map(async (item, index) => {
if (!item.image) {
return item;
}
// We've already downloaded this!
if (isDownloaded(item.image)) {
log.info(`${idLog}: Preview attachment already downloaded`);
return item;
}
const signature = getLinkPreviewSignature(item);
const existingPreview = signature
? previewSignatures.get(signature)
: undefined;
// We've already downloaded this elsewhere!
if (
existingPreview &&
(isDownloading(existingPreview.image) ||
isDownloaded(existingPreview.image))
) {
log.info(`${idLog}: Preview already downloaded elsewhere. Replacing`);
// Incrementing count so that we update the message's fields downstream
count += 1;
return existingPreview;
}
count += 1;
return {
...item,
image: await AttachmentDownloads.addJob(item.image, {
messageId,
type: 'preview',
index,
}),
};
})
);
return {
preview,
count,
};
}
function getQuoteThumbnailSignature(
quote: QuotedMessageType,
thumbnail?: AttachmentType
): string | undefined {
if (!thumbnail) {
return undefined;
}
return `<${quote.id}>${getAttachmentSignature(thumbnail)}`;
}
async function queueQuoteAttachments(
idLog: string,
messageId: string,
quote: QuotedMessageType | undefined,
otherQuotes: ReadonlyArray<QuotedMessageType>
): Promise<{ quote?: QuotedMessageType; count: number }> {
let count = 0;
if (!quote) {
return { quote, count };
}
const quoteAttachmentsToQueue =
quote && quote.attachments ? quote.attachments : [];
if (quoteAttachmentsToQueue.length === 0) {
return { quote, count };
}
// Similar to queueNormalAttachments' logic for detecting same attachments
// except here we also pick by quote sent timestamp.
const thumbnailSignatures: Map<string, AttachmentType> = new Map();
otherQuotes.forEach(otherQuote => {
for (const attachment of otherQuote.attachments) {
const signature = getQuoteThumbnailSignature(
otherQuote,
attachment.thumbnail
);
if (!signature) {
continue;
}
thumbnailSignatures.set(signature, attachment);
}
});
return {
quote: {
...quote,
attachments: await Promise.all(
quote.attachments.map(async (item, index) => {
if (!item.thumbnail) {
return item;
}
// We've already downloaded this!
if (isDownloaded(item.thumbnail)) {
log.info(`${idLog}: Quote attachment already downloaded`);
return item;
}
const signature = getQuoteThumbnailSignature(quote, item.thumbnail);
const existingThumbnail = signature
? thumbnailSignatures.get(signature)
: undefined;
// We've already downloaded this elsewhere!
if (
existingThumbnail &&
(isDownloading(existingThumbnail) ||
isDownloaded(existingThumbnail))
) {
log.info(
`${idLog}: Preview already downloaded elsewhere. Replacing`
);
// Incrementing count so that we update the message's fields downstream
count += 1;
return {
...item,
thumbnail: existingThumbnail,
};
}
count += 1;
return {
...item,
thumbnail: await AttachmentDownloads.addJob(item.thumbnail, {
messageId,
type: 'quote',
index,
}),
};
})
),
},
count,
};
}