Skip to content

Commit

Permalink
feat: cleaned up accept/block/decline logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Bilb committed Jun 11, 2024
1 parent 9d9844a commit e42be00
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 29 deletions.
4 changes: 2 additions & 2 deletions _locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@
"messageRequestAcceptedOursNoName": "You have accepted the message request",
"declineRequestMessage": "Are you sure you want to decline this message request?",
"deleteGroupRequest": "Are you sure you want to delete this group invite?",
"deleteGroupRequestAndBlock": "Are you sure you want to block <b>$name$</b>? Blocked users cannot send you message requests, group invites or call you.",
"deleteGroupRequestAndBlock": "Are you sure you want to block <b>$name$</b>?<br/>Blocked users cannot send you message requests, group invites or call you.",
"respondingToRequestWarning": "Sending a message to this user will automatically accept their message request and reveal your Session ID.",
"respondingToGroupRequestWarning": "Sending a message to this group will automatically accept the group invite.",
"userInvitedYouToGroup": "<b>$name$</b> invited you to join <b>$groupName$</b>.",
Expand All @@ -584,7 +584,7 @@
"mustBeApproved": "This conversation must be accepted to use this feature",
"youHaveANewFriendRequest": "You have a new friend request",
"clearAllConfirmationTitle": "Clear All Message Requests",
"clearAllConfirmationBody": "Are you sure you want to clear all message and group requests?",
"clearAllConfirmationBody": "Are you sure you want to clear all message requests and group invites?",
"thereAreNoMessagesIn": "There are no messages in <b>$name$</b>.",
"noMessagesInBlindedDisabledMsgRequests": "<b>$name$</b> has message requests from Community conversations turned off, so you cannot send them a message.",
"noMessagesInNoteToSelf": "You have no messages in <b>$name$</b>.",
Expand Down
5 changes: 4 additions & 1 deletion ts/components/leftpane/overlay/OverlayMessageRequest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const OverlayMessageRequest = () => {
*/
function handleClearAllRequestsClick() {
const { i18n } = window;
const title = i18n('clearAllConfirmationTitle');
const title = i18n('clearAll');
const message = i18n('clearAllConfirmationBody');
const onClose = dispatch(updateConfirmModal(null));

Expand All @@ -68,6 +68,9 @@ export const OverlayMessageRequest = () => {
title,
message,
onClose,
okTheme: SessionButtonColor.Danger,
closeTheme: SessionButtonColor.Primary,
okText: window.i18n('clear'),
onClickOk: async () => {
window?.log?.info('Blocking all message requests');
if (!hasRequests) {
Expand Down
6 changes: 6 additions & 0 deletions ts/interactions/conversationInteractions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,9 @@ export async function declineConversationWithoutConfirm({
window?.log?.info('No conversation to decline.');
return;
}
window.log.debug(
`declineConversationWithoutConfirm of ${ed25519Str(conversationId)}, alsoBlock:${alsoBlock}, conversationIdOrigin:${conversationIdOrigin ? ed25519Str(conversationIdOrigin) : '<none>'}`
);

// Note: do not set the active_at undefined as this would make that conversation not synced with the libsession wrapper
await conversationToDecline.setIsApproved(false, false);
Expand Down Expand Up @@ -288,7 +291,10 @@ export const declineConversationWithConfirm = ({
updateConfirmModal({
okText: window.i18n(okKey),
cancelText: window.i18n('cancel'),
title: window.i18n(okKey),
message,
okTheme: SessionButtonColor.Danger,
closeTheme: SessionButtonColor.Primary,
onClickOk: async () => {
await declineConversationWithoutConfirm({
conversationId,
Expand Down
11 changes: 11 additions & 0 deletions ts/session/apis/snode_api/SnodeRequestTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -973,24 +973,35 @@ export class StoreUserMessageSubRequest extends SnodeAPISubRequest {
public readonly dbMessageIdentifier: string | null;
public readonly createdAtNetworkTimestamp: number;

public readonly plainTextBuffer: Uint8Array | null;

constructor(
args: WithCreatedAtNetworkTimestamp & {
ttlMs: number;
encryptedData: Uint8Array;
destination: PubkeyType;
dbMessageIdentifier: string | null;
/**
* When we send a message to a 1o1 recipient, we then need to send the same message to our own swarm as a synced message.
* To forward that message, we need the original message data, which is the plainTextBuffer field here.
*/
plainTextBuffer: Uint8Array | null;
}
) {
super();
this.ttlMs = args.ttlMs;
this.destination = args.destination;
this.encryptedData = args.encryptedData;
this.plainTextBuffer = args.plainTextBuffer;
this.dbMessageIdentifier = args.dbMessageIdentifier;
this.createdAtNetworkTimestamp = args.createdAtNetworkTimestamp;

if (isEmpty(this.encryptedData)) {
throw new Error('this.encryptedData cannot be empty');
}
if (this.plainTextBuffer && !this.plainTextBuffer.length) {
throw new Error('this.plainTextBuffer can be either null or non-empty');
}
}

public async buildAndSignParameters(): Promise<{
Expand Down
54 changes: 31 additions & 23 deletions ts/session/sending/MessageSender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,29 @@ type PubkeyToRequestType<T extends GroupPubkeyType | PubkeyType> = T extends Pub

type StoreRequestsPerPubkey<T extends PubkeyType | GroupPubkeyType> = Array<PubkeyToRequestType<T>>;

type EncryptedMessageDetails = Pick<
EncryptAndWrapMessageResults,
| 'namespace'
| 'encryptedAndWrappedData'
| 'identifier'
| 'ttl'
| 'networkTimestamp'
| 'plainTextBuffer'
>;

async function messageToRequest05({
destination,
encryptedAndWrapped: { namespace, encryptedAndWrappedData, identifier, ttl, networkTimestamp },
encryptedAndWrapped: {
namespace,
encryptedAndWrappedData,
identifier,
ttl,
networkTimestamp,
plainTextBuffer,
},
}: {
destination: PubkeyType;
encryptedAndWrapped: Pick<
EncryptAndWrapMessageResults,
'namespace' | 'encryptedAndWrappedData' | 'identifier' | 'ttl' | 'networkTimestamp'
>;
encryptedAndWrapped: EncryptedMessageDetails;
}): Promise<StoreRequest05> {
const shared05Arguments = {
encryptedData: encryptedAndWrappedData,
Expand All @@ -114,6 +128,7 @@ async function messageToRequest05({
destination,
namespace,
createdAtNetworkTimestamp: networkTimestamp,
plainTextBuffer,
};
if (namespace === SnodeNamespaces.Default || namespace === SnodeNamespaces.LegacyClosedGroup) {
return new StoreUserMessageSubRequest(shared05Arguments);
Expand Down Expand Up @@ -175,10 +190,7 @@ async function messageToRequest<T extends GroupPubkeyType | PubkeyType>({
encryptedAndWrapped,
}: {
destination: T;
encryptedAndWrapped: Pick<
EncryptAndWrapMessageResults,
'namespace' | 'encryptedAndWrappedData' | 'identifier' | 'ttl' | 'networkTimestamp'
>;
encryptedAndWrapped: EncryptedMessageDetails;
}): Promise<PubkeyToRequestType<T>> {
if (PubKey.is03Pubkey(destination)) {
const req = await messageToRequest03({ destination, encryptedAndWrapped });
Expand All @@ -200,12 +212,7 @@ async function messagesToRequests<T extends GroupPubkeyType | PubkeyType>({
encryptedAndWrappedArr,
}: {
destination: T;
encryptedAndWrappedArr: Array<
Pick<
EncryptAndWrapMessageResults,
'namespace' | 'encryptedAndWrappedData' | 'identifier' | 'ttl' | 'networkTimestamp'
>
>;
encryptedAndWrappedArr: Array<EncryptedMessageDetails>;
}): Promise<Array<PubkeyToRequestType<T>>> {
const subRequests: Array<PubkeyToRequestType<T>> = [];
for (let index = 0; index < encryptedAndWrappedArr.length; index++) {
Expand Down Expand Up @@ -260,6 +267,7 @@ async function sendSingleMessage({
// before we return from the await below.
// and the isDuplicate messages relies on sent_at timestamp to be valid.
const found = await Data.getMessageById(encryptedAndWrapped.identifier);

// make sure to not update the sent timestamp if this a currently syncing message
if (found && !found.get('sentSync')) {
found.set({ sent_at: encryptedAndWrapped.networkTimestamp });
Expand Down Expand Up @@ -497,10 +505,10 @@ type SharedEncryptAndWrap = {
ttl: number;
identifier: string;
isSyncMessage: boolean;
plainTextBuffer: Uint8Array;
};

type EncryptAndWrapMessage = {
plainTextBuffer: Uint8Array;
destination: string;
namespace: number;
networkTimestamp: number;
Expand Down Expand Up @@ -549,6 +557,7 @@ async function encryptForGroupV2(
ttl,
identifier,
isSyncMessage: syncMessage,
plainTextBuffer,
};
}

Expand Down Expand Up @@ -594,6 +603,7 @@ async function encryptMessageAndWrap(
ttl,
identifier,
isSyncMessage: syncMessage,
plainTextBuffer,
};
}

Expand Down Expand Up @@ -847,7 +857,6 @@ async function handleBatchResultWithSubRequests({
window.log.error('handleBatchResultWithSubRequests: invalid batch result ');
return;
}
const us = UserUtils.getOurPubKeyStrFromCache();

const seenHashes: Array<SeenMessageHashes> = [];
for (let index = 0; index < subRequests.length; index++) {
Expand Down Expand Up @@ -878,11 +887,7 @@ async function handleBatchResultWithSubRequests({

// We need to store the hash of our synced message when for a 1o1. (as this is the one stored on our swarm)
// For groups, we can just store that hash directly as the group's swarm is hosting all of the group messages

if (
subRequest.dbMessageIdentifier &&
(subRequest.destination === us || isDestinationClosedGroup)
) {
if (subRequest.dbMessageIdentifier) {
// eslint-disable-next-line no-await-in-loop
await MessageSentHandler.handleSwarmMessageSentSuccess(
{
Expand All @@ -891,7 +896,10 @@ async function handleBatchResultWithSubRequests({
? SignalService.Envelope.Type.CLOSED_GROUP_MESSAGE
: SignalService.Envelope.Type.SESSION_MESSAGE,
identifier: subRequest.dbMessageIdentifier,
plainTextBuffer: null,
plainTextBuffer:
subRequest instanceof StoreUserMessageSubRequest
? subRequest.plainTextBuffer
: null,
},
subRequest.createdAtNetworkTimestamp,
storedHash
Expand Down
3 changes: 2 additions & 1 deletion ts/session/sending/MessageSentHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ async function handleSwarmMessageSentSuccess(

// A message is synced if we triggered a sync message (sentSync)
// and the current message was sent to our device (so a sync message)
const shouldMarkMessageAsSynced = isOurDevice && fetchedMessage.get('sentSync');
const shouldMarkMessageAsSynced =
isOurDevice && fetchedMessage.get('sentSync') && isClosedGroupMessage;

// Handle the sync logic here
if (shouldTriggerSyncMessage && sentMessage && sentMessage.plainTextBuffer) {
Expand Down
3 changes: 2 additions & 1 deletion ts/session/utils/String.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,5 @@ export const sanitizeSessionUsername = (inputName: string) => {
return validChars;
};

export const ed25519Str = (ed25519Key: string) => `(...${ed25519Key.substr(58)})`;
export const ed25519Str = (ed25519Key: string) =>
`(...${ed25519Key.length > 58 ? ed25519Key.substr(58) : ed25519Key})`;
1 change: 0 additions & 1 deletion ts/types/LocalizerKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ export type LocalizerKeys =
| 'clear'
| 'clearAll'
| 'clearAllConfirmationBody'
| 'clearAllConfirmationTitle'
| 'clearAllData'
| 'clearAllReactions'
| 'clearDataSettingsTitle'
Expand Down

0 comments on commit e42be00

Please sign in to comment.