signal-desktop/ts/messageModifiers/ViewSyncs.ts

117 lines
3 KiB
TypeScript
Raw Normal View History

// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable max-classes-per-file */
import { Collection, Model } from 'backbone';
import type { MessageModel } from '../models/messages';
import { ReadStatus } from '../messages/MessageReadStatus';
import { markViewed } from '../services/MessageUpdater';
2022-04-21 00:29:37 +00:00
import { isIncoming, isStory } from '../state/selectors/message';
2021-09-23 18:16:09 +00:00
import { notificationService } from '../services/notifications';
import * as log from '../logging/log';
2022-05-11 20:59:58 +00:00
import { GiftBadgeStates } from '../components/conversation/Message';
export type ViewSyncAttributesType = {
senderId: string;
senderE164?: string;
senderUuid: string;
timestamp: number;
viewedAt: number;
};
class ViewSyncModel extends Model<ViewSyncAttributesType> {}
let singleton: ViewSyncs | undefined;
export class ViewSyncs extends Collection {
static getSingleton(): ViewSyncs {
if (!singleton) {
singleton = new ViewSyncs();
}
return singleton;
}
forMessage(message: MessageModel): Array<ViewSyncModel> {
const senderId = window.ConversationController.ensureContactIds({
e164: message.get('source'),
uuid: message.get('sourceUuid'),
});
const syncs = this.filter(item => {
return (
item.get('senderId') === senderId &&
item.get('timestamp') === message.get('sent_at')
);
});
if (syncs.length) {
log.info(
`Found ${syncs.length} early view sync(s) for message ${message.get(
'sent_at'
)}`
);
this.remove(syncs);
}
return syncs;
}
async onSync(sync: ViewSyncModel): Promise<void> {
try {
const messages = await window.Signal.Data.getMessagesBySentAt(
sync.get('timestamp')
);
const found = messages.find(item => {
const senderId = window.ConversationController.ensureContactIds({
e164: item.source,
uuid: item.sourceUuid,
});
2022-04-21 00:29:37 +00:00
return (
(isIncoming(item) || isStory(item)) &&
senderId === sync.get('senderId')
);
});
if (!found) {
log.info(
'Nothing found for view sync',
sync.get('senderId'),
sync.get('senderE164'),
sync.get('senderUuid'),
sync.get('timestamp')
);
return;
}
2021-09-23 18:16:09 +00:00
notificationService.removeBy({ messageId: found.id });
const message = window.MessageController.register(found.id, found);
if (message.get('readStatus') !== ReadStatus.Viewed) {
message.set(markViewed(message.attributes, sync.get('viewedAt')));
}
2022-05-11 20:59:58 +00:00
const giftBadge = message.get('giftBadge');
if (giftBadge) {
message.set({
giftBadge: {
...giftBadge,
2022-05-16 19:54:38 +00:00
state: isIncoming(message.attributes)
? GiftBadgeStates.Redeemed
: GiftBadgeStates.Opened,
2022-05-11 20:59:58 +00:00
},
});
}
this.remove(sync);
} catch (error) {
log.error(
'ViewSyncs.onSync error:',
error && error.stack ? error.stack : error
);
}
}
}