diff --git a/lib/shared/dm-ops/dm-op-utils.js b/lib/shared/dm-ops/dm-op-utils.js new file mode 100644 --- /dev/null +++ b/lib/shared/dm-ops/dm-op-utils.js @@ -0,0 +1,61 @@ +// @flow + +import type { AuxUserStore } from '../../types/aux-user-types.js'; +import type { DMOperation } from '../../types/dm-ops.js'; +import type { OutboundP2PMessage } from '../../types/sqlite-types.js'; +import { outboundP2PMessageStatuses } from '../../types/sqlite-types.js'; +import type { CurrentUserInfo } from '../../types/user-types.js'; +import { values } from '../../utils/objects.js'; +import { getUUID } from '../../utils/uuid.js'; + +function generateMessagesToPeers( + message: DMOperation, + peers: $ReadOnlyArray, + userID: string, + supportsAutoRetry: boolean, +): $ReadOnlyArray { + const outboundP2PMessages = []; + for (const peerID of peers) { + const messageToPeer: OutboundP2PMessage = { + messageID: getUUID(), + deviceID: peerID, + userID, + timestamp: new Date().getTime().toString(), + plaintext: JSON.stringify(message), + ciphertext: '', + status: outboundP2PMessageStatuses.persisted, + supportsAutoRetry, + }; + outboundP2PMessages.push(messageToPeer); + } + return outboundP2PMessages; +} + +export type DMOperationSpecification = { + +op: DMOperation, + +supportsAutoRetry: boolean, + +recipients: 'all_peer_devices' | 'self_devices', +}; + +function createMessagesToPeersFromDMOp( + operation: DMOperationSpecification, + auxUserStore: AuxUserStore, + currentUserInfo: ?CurrentUserInfo, +): $ReadOnlyArray { + if (!currentUserInfo?.id) { + return []; + } + const selfDevices = + auxUserStore.auxUserInfos[currentUserInfo.id].deviceList?.devices ?? []; + const allPeerDevices = values(auxUserStore.auxUserInfos) + .map(info => info.deviceList?.devices ?? []) + .flat(); + return generateMessagesToPeers( + operation.op, + operation.recipients === 'all_peer_devices' ? allPeerDevices : selfDevices, + currentUserInfo.id, + operation.supportsAutoRetry, + ); +} + +export { createMessagesToPeersFromDMOp };