fix: show dialog before deleting group

also deal with leave/delete group silent retries on 401
pull/3281/head
Audric Ackermann 4 months ago
parent 8c41db515e
commit a8372f1b8c
No known key found for this signature in database

@ -1,7 +1,7 @@
import { compact, flatten, isEqual } from 'lodash';
import { SessionDataTestId, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import useInterval from 'react-use/lib/useInterval';
import styled from 'styled-components';
import { Data } from '../../../../data/data';
@ -11,13 +11,14 @@ import {
useConversationUsername,
useDisappearingMessageSettingText,
useIsClosedGroup,
useIsGroupDestroyed,
useIsKickedFromGroup,
useIsPublic,
useLastMessageIsLeaveError,
} from '../../../../hooks/useParamSelector';
import { useIsRightPanelShowing } from '../../../../hooks/useUI';
import {
showAddModeratorsByConvoId,
showDeleteGroupByConvoId,
showInviteContactByConvoId,
showLeaveGroupByConvoId,
showRemoveModeratorsByConvoId,
@ -57,7 +58,7 @@ import {
showDeleteGroupItem,
showLeaveGroupItem,
} from '../../../menu/items/LeaveAndDeleteGroup/guard';
import { getIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { useIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { showLeaveCommunityItem } from '../../../menu/items/LeaveCommunity/guard';
async function getMediaGalleryProps(conversationId: string): Promise<{
@ -229,16 +230,18 @@ const LeaveCommunityPanelButton = () => {
const DeleteGroupPanelButton = () => {
const convoId = useSelectedConversationKey();
const isGroup = useIsClosedGroup(convoId);
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
const isKickedFromGroup = useIsKickedFromGroup(convoId) || false;
const lastMessageIsLeaveError = useLastMessageIsLeaveError(convoId);
const selectedUsername = useConversationUsername(convoId) || convoId;
const isPublic = useIsPublic(convoId);
const isGroupDestroyed = useIsGroupDestroyed(convoId);
const showItem = showDeleteGroupItem({
isGroup,
isKickedFromGroup,
isMessageRequestShown,
lastMessageIsLeaveError,
isPublic,
isGroupDestroyed,
});
if (!showItem || !convoId) {
@ -251,7 +254,7 @@ const DeleteGroupPanelButton = () => {
<PanelIconButton
text={window.i18n(token)}
dataTestId="leave-group-button"
onClick={() => void showLeaveGroupByConvoId(convoId, selectedUsername)}
onClick={() => void showDeleteGroupByConvoId(convoId, selectedUsername)}
color={'var(--danger-color)'}
iconType={'delete'}
/>
@ -262,15 +265,17 @@ const LeaveGroupPanelButton = () => {
const selectedConvoKey = useSelectedConversationKey();
const isGroup = useIsClosedGroup(selectedConvoKey);
const username = useConversationUsername(selectedConvoKey) || selectedConvoKey;
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
const isKickedFromGroup = useIsKickedFromGroup(selectedConvoKey) || false;
const lastMessageIsLeaveError = useLastMessageIsLeaveError(selectedConvoKey);
const isPublic = useIsPublic(selectedConvoKey);
const isGroupDestroyed = useIsGroupDestroyed(selectedConvoKey);
const showItem = showLeaveGroupItem({
isGroup,
isKickedFromGroup,
isMessageRequestShown,
lastMessageIsLeaveError,
isPublic,
isGroupDestroyed,
});
if (!selectedConvoKey || !showItem) {

@ -1,7 +1,6 @@
import classNames from 'classnames';
import { isEmpty } from 'lodash';
import { useSelector } from 'react-redux';
import { useConvoIdFromContext } from '../../../contexts/ConvoIdContext';
import {
useHasUnread,
@ -12,7 +11,7 @@ import {
} from '../../../hooks/useParamSelector';
import { LastMessageStatusType } from '../../../state/ducks/types';
import { useIsSearching } from '../../../state/selectors/search';
import { getIsMessageRequestOverlayShown } from '../../../state/selectors/section';
import { useIsMessageRequestOverlayShown } from '../../../state/selectors/section';
import { assertUnreachable } from '../../../types/sqlSharedTypes';
import { TypingAnimation } from '../../conversation/TypingAnimation';
import { MessageBody } from '../../conversation/message/message-content/MessageBody';
@ -26,7 +25,7 @@ export const MessageItem = () => {
const hasUnread = useHasUnread(conversationId);
const isConvoTyping = useIsTyping(conversationId);
const isMessageRequest = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequest = useIsMessageRequestOverlayShown();
const isOutgoingRequest = useIsOutgoingRequest(conversationId);
const isSearching = useIsSearching();

@ -5,8 +5,8 @@ import { useConvoIdFromContext } from '../../contexts/ConvoIdContext';
import { useIsPinned, useIsPrivate, useIsPrivateAndFriend } from '../../hooks/useParamSelector';
import { ConvoHub } from '../../session/conversations';
import {
getIsMessageRequestOverlayShown,
getIsMessageSection,
useIsMessageRequestOverlayShown,
} from '../../state/selectors/section';
import { useIsSearching } from '../../state/selectors/search';
import { SessionContextMenuContainer } from '../SessionContextMenuContainer';
@ -91,7 +91,7 @@ export const PinConversationMenuItem = (): JSX.Element | null => {
const isPrivateAndFriend = useIsPrivateAndFriend(conversationId);
const isPrivate = useIsPrivate(conversationId);
const isPinned = useIsPinned(conversationId);
const isMessageRequest = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequest = useIsMessageRequestOverlayShown();
if (isMessagesSection && !isMessageRequest && (!isPrivate || (isPrivate && isPrivateAndFriend))) {
const conversation = ConvoHub.use().get(conversationId);

@ -49,8 +49,8 @@ import {
} from '../../state/ducks/modalDialog';
import { useConversationIdOrigin } from '../../state/selectors/conversations';
import {
getIsMessageRequestOverlayShown,
getIsMessageSection,
useIsMessageRequestOverlayShown,
} from '../../state/selectors/section';
import { useSelectedConversationKey } from '../../state/selectors/selectedConversation';
import type { LocalizerToken } from '../../types/localizer';
@ -84,7 +84,7 @@ export const MarkConversationUnreadMenuItem = (): JSX.Element | null => {
const isMessagesSection = useSelector(getIsMessageSection);
const isPrivate = useIsPrivate(conversationId);
const isPrivateAndFriend = useIsPrivateAndFriend(conversationId);
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
if (
isMessagesSection &&
@ -358,7 +358,7 @@ export const ChangeNicknameMenuItem = () => {
*/
export const DeleteMessagesMenuItem = () => {
const convoId = useConvoIdFromContext();
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
if (!convoId || isMessageRequestShown) {
return null;
@ -495,7 +495,7 @@ export const NotificationForConvoMenuItem = (): JSX.Element | null => {
const isFriend = useIsPrivateAndFriend(convoId);
const isPrivate = useIsPrivate(convoId);
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
if (
!convoId ||

@ -1,14 +1,14 @@
import { useSelector } from 'react-redux';
import { useConvoIdFromContext } from '../../../../contexts/ConvoIdContext';
import {
useConversationUsername,
useIsKickedFromGroup,
useIsClosedGroup,
useLastMessageIsLeaveError,
useIsPublic,
useIsGroupDestroyed,
} from '../../../../hooks/useParamSelector';
import { showLeaveGroupByConvoId } from '../../../../interactions/conversationInteractions';
import { showDeleteGroupByConvoId } from '../../../../interactions/conversationInteractions';
import { PubKey } from '../../../../session/types';
import { getIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { useIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { ItemWithDataTestId } from '../MenuItemWithDataTestId';
import { showDeleteGroupItem } from './guard';
import { Localizer } from '../../../basic/Localizer';
@ -17,15 +17,17 @@ export const DeleteGroupMenuItem = () => {
const convoId = useConvoIdFromContext();
const username = useConversationUsername(convoId) || convoId;
const isGroup = useIsClosedGroup(convoId);
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
const isKickedFromGroup = useIsKickedFromGroup(convoId) || false;
const lastMessageIsLeaveError = useLastMessageIsLeaveError(convoId);
const isPublic = useIsPublic(convoId);
const isGroupDestroyed = useIsGroupDestroyed(convoId);
const showLeave = showDeleteGroupItem({
isGroup,
isKickedFromGroup,
isMessageRequestShown,
lastMessageIsLeaveError,
isPublic,
isGroupDestroyed,
});
if (!showLeave) {
@ -37,7 +39,7 @@ export const DeleteGroupMenuItem = () => {
return (
<ItemWithDataTestId
onClick={() => {
void showLeaveGroupByConvoId(convoId, username);
void showDeleteGroupByConvoId(convoId, username);
}}
>
<Localizer token={token} />

@ -1,13 +1,13 @@
import { useSelector } from 'react-redux';
import { useConvoIdFromContext } from '../../../../contexts/ConvoIdContext';
import {
useConversationUsername,
useIsKickedFromGroup,
useIsClosedGroup,
useLastMessageIsLeaveError,
useIsPublic,
useIsGroupDestroyed,
} from '../../../../hooks/useParamSelector';
import { showLeaveGroupByConvoId } from '../../../../interactions/conversationInteractions';
import { getIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { useIsMessageRequestOverlayShown } from '../../../../state/selectors/section';
import { ItemWithDataTestId } from '../MenuItemWithDataTestId';
import { showLeaveGroupItem } from './guard';
import { Localizer } from '../../../basic/Localizer';
@ -15,16 +15,18 @@ import { Localizer } from '../../../basic/Localizer';
export const LeaveGroupMenuItem = () => {
const convoId = useConvoIdFromContext();
const isGroup = useIsClosedGroup(convoId);
const isPublic = useIsPublic(convoId);
const username = useConversationUsername(convoId) || convoId;
const isMessageRequestShown = useSelector(getIsMessageRequestOverlayShown);
const isMessageRequestShown = useIsMessageRequestOverlayShown();
const isKickedFromGroup = useIsKickedFromGroup(convoId) || false;
const lastMessageIsLeaveError = useLastMessageIsLeaveError(convoId);
const isGroupDestroyed = useIsGroupDestroyed(convoId);
const showLeave = showLeaveGroupItem({
isGroup,
isMessageRequestShown,
isKickedFromGroup,
lastMessageIsLeaveError,
isPublic,
isGroupDestroyed,
});
if (!showLeave) {

@ -1,42 +1,53 @@
function sharedEnabled({
isGroup,
isPublic,
isMessageRequestShown,
}: Pick<Parameters<typeof showLeaveGroupItem>[0], 'isGroup' | 'isMessageRequestShown'>) {
return isGroup && !isMessageRequestShown;
}: Pick<
Parameters<typeof showLeaveGroupItem>[0],
'isGroup' | 'isMessageRequestShown' | 'isPublic'
>) {
return isGroup && !isMessageRequestShown && !isPublic;
}
/**
* We can try leave a group if
* - we are an admin of the group (that group would be marked as destroyed on delete)
* and
* - we are a **not kicked** member (if we are kicked without knowing about it and try to leave, we will silently remove the group)
*
* Note: Those actions are hidden if the group is a group request (as we have other buttons to accept/decline a group request).
*
* Note: If we fail to leave the group but that error is retryable, we will keep the group displaying the "leave" option.
*/
export function showLeaveGroupItem({
isGroup,
isPublic,
isKickedFromGroup,
isMessageRequestShown,
lastMessageIsLeaveError,
isGroupDestroyed,
}: {
isGroup: boolean;
isPublic: boolean;
isMessageRequestShown: boolean;
lastMessageIsLeaveError: boolean;
isKickedFromGroup: boolean;
isGroupDestroyed: boolean;
}) {
// we can't try to leave the group if we were kicked from it, or if we've already tried to (lastMessageIsLeaveError is true)
return (
sharedEnabled({ isGroup, isMessageRequestShown }) &&
sharedEnabled({ isGroup, isMessageRequestShown, isPublic }) &&
!isKickedFromGroup &&
!lastMessageIsLeaveError
!isGroupDestroyed
);
}
export function showDeleteGroupItem({
isGroup,
isKickedFromGroup,
isMessageRequestShown,
lastMessageIsLeaveError,
}: {
/**
* We can try to delete a group only if the `showLeaveGroupItem` returns false.
* Note: those actions are hidden if the group is a group request (as we have other buttons to accept/decline a group request)
*/
export function showDeleteGroupItem(args: {
isGroup: boolean;
isPublic: boolean;
isMessageRequestShown: boolean;
lastMessageIsLeaveError: boolean;
isKickedFromGroup: boolean;
isGroupDestroyed: boolean;
}) {
return (
sharedEnabled({ isGroup, isMessageRequestShown }) &&
(isKickedFromGroup || lastMessageIsLeaveError)
);
return sharedEnabled(args) && !showLeaveGroupItem(args);
}

@ -212,7 +212,7 @@ export function useIsKickedFromGroup(convoId?: string) {
export function useIsGroupDestroyed(convoId?: string) {
const libIsDestroyed = useLibGroupDestroyed(convoId);
if (convoId && PubKey.is03Pubkey(convoId)) {
return libIsDestroyed;
return libIsDestroyed || false;
}
return false;
}

@ -431,21 +431,6 @@ async function leaveGroupOrCommunityByConvoId({
}
}
/**
* Returns true if we the convo is a 03 group and if we can try to send a leave message.
*/
async function hasLeavingDetails(convoId: string) {
if (!PubKey.is03Pubkey(convoId)) {
return true;
}
const group = await UserGroupsWrapperActions.getGroup(convoId);
// we need the authData or the secretKey to be able to attempt to leave,
// otherwise we won't be able to even try
return group && (!isEmpty(group.authData) || !isEmpty(group.secretKey));
}
export async function showLeaveGroupByConvoId(conversationId: string, name: string | undefined) {
const conversation = ConvoHub.use().get(conversationId);
@ -462,20 +447,6 @@ export async function showLeaveGroupByConvoId(conversationId: string, name: stri
(PubKey.is05Pubkey(conversationId) || PubKey.is03Pubkey(conversationId)) &&
isAdmin &&
admins.length === 1;
const lastMessageInteractionType = conversation.get('lastMessageInteractionType');
const lastMessageInteractionStatus = conversation.get('lastMessageInteractionStatus');
const canTryToLeave = await hasLeavingDetails(conversationId);
if (
!isPublic &&
((lastMessageInteractionType === ConversationInteractionType.Leave &&
lastMessageInteractionStatus === ConversationInteractionStatus.Error) ||
!canTryToLeave) // if we don't have any key to send our leave message, no need to try
) {
await leaveGroupOrCommunityByConvoId({ conversationId, isPublic, sendLeaveMessage: false });
return;
}
// if this is a community, or we legacy group are not admin, we can just show a confirmation dialog
@ -525,6 +496,46 @@ export async function showLeaveGroupByConvoId(conversationId: string, name: stri
}
}
/**
* Can be used to show a dialog asking confirmation about deleting a group.
* Communities are explicitly forbidden.
* This function won't attempt to send a leave message. Use `showLeaveGroupByConvoId` for that purpose
*/
export async function showDeleteGroupByConvoId(conversationId: string, name: string | undefined) {
const conversation = ConvoHub.use().get(conversationId);
const isPublic = conversation.isPublic();
if (!conversation.isGroup() || isPublic) {
throw new Error('showDeleteGroupByConvoId() called with a non group convo.');
}
const onClickClose = () => {
window?.inboxStore?.dispatch(updateConfirmModal(null));
};
const onClickOk = async () => {
await leaveGroupOrCommunityByConvoId({
conversationId,
isPublic, // we check for isPublic above, and throw if it's true
sendLeaveMessage: false,
onClickClose,
});
};
window?.inboxStore?.dispatch(
updateConfirmModal({
title: window.i18n('groupDelete'),
i18nMessage: { token: 'groupDeleteDescriptionMember', args: { group_name: name ?? '' } },
onClickOk,
okText: window.i18n('delete'),
okTheme: SessionButtonColor.Danger,
onClickClose,
conversationId,
})
);
}
export function showInviteContactByConvoId(conversationId: string) {
window.inboxStore?.dispatch(updateInviteContactModal({ conversationId }));
}
@ -1027,6 +1038,7 @@ export async function promoteUsersInGroup({
method: 'batch',
sortedSubRequests: storeRequests,
abortSignal: controller.signal,
allow401s: false,
}),
2 * DURATION.MINUTES,
controller

@ -1148,6 +1148,7 @@ export class ConversationModel extends Backbone.Model<ConversationAttributes> {
await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk: this.id,
extraStoreRequests,
allow401s: false,
});
await GroupSync.queueNewJobIfNeeded(this.id);

@ -15,6 +15,7 @@ import {
} from './SnodeRequestTypes';
import { NotEmptyArrayOfBatchResults } from './BatchResultEntry';
import { MergedAbortSignal, WithTimeoutMs } from './requestWith';
import { WithAllow401s } from '../../types/with';
function logSubRequests(requests: Array<BuiltSnodeSubRequests>) {
return `[${requests.map(builtRequestToLoggingId).join(', ')}]`;
@ -22,7 +23,6 @@ function logSubRequests(requests: Array<BuiltSnodeSubRequests>) {
type WithTargetNode = { targetNode: Snode };
type WithAssociatedWith = { associatedWith: string | null };
type WithAllow401s = { allow401s: boolean };
/**
* This is the equivalent to the batch send on sogs. The target node runs each sub request and returns a list of all the sub status and bodies.

@ -21,6 +21,7 @@ import { fileServerHost } from '../file_server_api/FileServerApi';
import { hrefPnServerProd } from '../push_notification_api/PnServer';
import { ERROR_CODE_NO_CONNECT } from './SNodeAPI';
import { MergedAbortSignal, WithAbortSignal, WithTimeoutMs } from './requestWith';
import { WithAllow401s } from '../../types/with';
// hold the ed25519 key of a snode against the time it fails. Used to remove a snode only after a few failures (snodeFailureThreshold failures)
let snodeFailureCount: Record<string, number> = {};
@ -310,12 +311,11 @@ export async function processOnionRequestErrorAtDestination({
destinationSnodeEd25519,
associatedWith,
allow401s,
}: {
}: WithAllow401s & {
statusCode: number;
body: string;
destinationSnodeEd25519?: string;
associatedWith?: string;
allow401s: boolean;
}) {
if (statusCode === 200) {
return;
@ -526,14 +526,14 @@ async function processOnionResponse({
associatedWith,
destinationSnodeEd25519,
allow401s,
}: Partial<WithAbortSignal> & {
response?: { text: () => Promise<string>; status: number };
symmetricKey?: ArrayBuffer;
guardNode: Snode;
destinationSnodeEd25519?: string;
associatedWith?: string;
allow401s: boolean;
}): Promise<SnodeResponse> {
}: Partial<WithAbortSignal> &
WithAllow401s & {
response?: { text: () => Promise<string>; status: number };
symmetricKey?: ArrayBuffer;
guardNode: Snode;
destinationSnodeEd25519?: string;
associatedWith?: string;
}): Promise<SnodeResponse> {
let ciphertext = '';
processAbortedRequest(abortSignal);
@ -828,7 +828,8 @@ async function sendOnionRequestHandlingSnodeEjectNoRetries({
allow401s,
timeoutMs,
}: WithAbortSignal &
WithTimeoutMs & {
WithTimeoutMs &
WithAllow401s & {
nodePath: Array<Snode>;
destSnodeX25519: string;
finalDestOptions: FinalDestOptions;
@ -836,7 +837,6 @@ async function sendOnionRequestHandlingSnodeEjectNoRetries({
associatedWith?: string;
useV4: boolean;
throwErrors: boolean;
allow401s: boolean;
}): Promise<SnodeResponse | SnodeResponseV4 | undefined> {
// this sendOnionRequestNoRetries() call has to be the only one like this.
// If you need to call it, call it through sendOnionRequestHandlingSnodeEjectNoRetries because this is the one handling path rebuilding and known errors
@ -1118,12 +1118,12 @@ async function sendOnionRequestSnodeDestNoRetries({
timeoutMs,
associatedWith,
}: WithTimeoutMs &
WithAbortSignal & {
WithAbortSignal &
WithAllow401s & {
onionPath: Array<Snode>;
targetNode: Snode;
headers: Record<string, any>;
plaintext: string | null;
allow401s: boolean;
associatedWith?: string;
}) {
return Onions.sendOnionRequestHandlingSnodeEjectNoRetries({
@ -1155,12 +1155,12 @@ async function lokiOnionFetchNoRetries({
abortSignal,
timeoutMs,
}: WithTimeoutMs &
WithAbortSignal & {
WithAbortSignal &
WithAllow401s & {
targetNode: Snode;
headers: Record<string, any>;
body: string | null;
associatedWith?: string;
allow401s: boolean;
}): Promise<SnodeResponse | undefined> {
try {
// Get a path excluding `targetNode`:

@ -10,6 +10,7 @@ import { HTTPError, NotFoundError } from '../../utils/errors';
import { APPLICATION_JSON } from '../../../types/MIME';
import { ERROR_421_HANDLED_RETRY_REQUEST, Onions, snodeHttpsAgent, SnodeResponse } from './onions';
import { WithAbortSignal, WithTimeoutMs } from './requestWith';
import { WithAllow401s } from '../../types/with';
export interface LokiFetchOptions {
method: 'GET' | 'POST';
@ -32,12 +33,12 @@ async function doRequestNoRetries({
allow401s,
abortSignal,
}: WithTimeoutMs &
WithAbortSignal & {
WithAbortSignal &
WithAllow401s & {
url: string;
options: LokiFetchOptions;
targetNode?: Snode;
associatedWith: string | null;
allow401s: boolean;
}): Promise<undefined | SnodeResponse> {
const method = options.method || 'GET';
@ -126,12 +127,12 @@ async function snodeRpcNoRetries(
timeoutMs,
abortSignal,
}: WithTimeoutMs &
WithAllow401s &
WithAbortSignal & {
method: string;
params: Record<string, any> | Array<Record<string, any>>;
targetNode: Snode;
associatedWith: string | null;
allow401s: boolean;
} // the user pubkey this call is for. if the onion request fails, this is used to handle the error for this user swarm for instance
): Promise<undefined | SnodeResponse> {
const url = `https://${targetNode.ip}:${targetNode.port}/storage_rpc/v1`;

@ -286,8 +286,8 @@ class ConvoController {
const groupInUserGroup = await UserGroupsWrapperActions.getGroup(groupPk);
// send the leave message before we delete everything for this group (including the key!)
// Note: if we were kicked, we already lost the authData/secretKey for it, so no need to try to send our message.
if (sendLeaveMessage && !groupInUserGroup?.kicked) {
if (sendLeaveMessage) {
const failedToSendLeaveMessage = await leaveClosedGroup(groupPk, fromSyncMessage);
if (PubKey.is03Pubkey(groupPk) && failedToSendLeaveMessage) {
// this is caught and is adding an interaction notification message
@ -369,6 +369,7 @@ class ConvoController {
groupPk,
deleteAllMessagesSubRequest,
extraStoreRequests: [],
allow401s: false,
});
await LibSessionUtil.saveDumpsToDb(groupPk);
@ -573,7 +574,7 @@ class ConvoController {
throw new Error(`ConvoHub.${deleteType} needs complete initial fetch`);
}
window.log.info(`${deleteType} with ${ed25519Str(convoId)}`);
window.log.info(`deleteConvoInitialChecks: type ${deleteType} with ${ed25519Str(convoId)}`);
const conversation = this.conversations.get(convoId);
if (!conversation) {
@ -693,7 +694,7 @@ async function leaveClosedGroup(groupPk: PubkeyType | GroupPubkeyType, fromSyncM
window?.log?.info(
`We are leaving the group ${ed25519Str(groupPk)}. Sending our leaving messages.`
);
let failedToSent03LeaveMessage = false;
let failedToSent03LeaveMessage = true;
// We might not be able to send our leaving messages (no encryption key pair, we were already removed, no network, etc).
// If that happens, we should just remove everything from our current user.
try {
@ -711,23 +712,28 @@ async function leaveClosedGroup(groupPk: PubkeyType | GroupPubkeyType, fromSyncM
sortedSubRequests: storeRequests,
method: 'sequence',
abortSignal: controller.signal,
allow401s: true, // we want "allow" 401s so we don't throw
}),
30 * DURATION.SECONDS,
controller
);
if (results?.[0].code !== 200) {
if (results?.[0].code === 401) {
window.log.info(
`leaveClosedGroup for ${ed25519Str(groupPk)} failed with 401. Assuming we've been revoked.`
);
} else if (results?.[0].code !== 200) {
throw new Error(
`Even with the retries, leaving message for group ${ed25519Str(
groupPk
)} failed to be sent...`
);
}
failedToSent03LeaveMessage = false;
} catch (e) {
window?.log?.warn(
`failed to send our leaving messages for ${ed25519Str(groupPk)}:${e.message}`
);
failedToSent03LeaveMessage = true;
}
// the rest of the cleaning of that conversation is done in the `deleteClosedGroup()`

@ -57,6 +57,7 @@ import { SaveSeenMessageHash, stringify } from '../../types/sqlSharedTypes';
import { OpenGroupRequestCommonType } from '../../data/types';
import { NetworkTime } from '../../util/NetworkTime';
import { MergedAbortSignal } from '../apis/snode_api/requestWith';
import { WithAllow401s } from '../types/with';
// ================ SNODE STORE ================
@ -420,7 +421,8 @@ async function sendMessagesDataToSnode<T extends PubkeyType | GroupPubkeyType>({
sortedSubRequests,
method,
abortSignal,
}: {
allow401s,
}: WithAllow401s & {
sortedSubRequests: SortedSubRequestsType<T>;
associatedWith: T;
method: MethodBatchType;
@ -448,7 +450,7 @@ async function sendMessagesDataToSnode<T extends PubkeyType | GroupPubkeyType>({
targetNode,
timeoutMs: 6 * DURATION.SECONDS,
associatedWith,
allow401s: false,
allow401s,
method,
abortSignal,
});
@ -473,7 +475,9 @@ async function sendMessagesDataToSnode<T extends PubkeyType | GroupPubkeyType>({
'first result status is not 200 for sendMessagesDataToSnode but: ',
firstResult.code
);
throw new Error('sendMessagesDataToSnode: Invalid status code');
if (!allow401s || firstResult.code !== 401) {
throw new Error('sendMessagesDataToSnode: Invalid status code');
}
}
GetNetworkTime.handleTimestampOffsetFromNetwork('store', firstResult.body.t);
@ -509,7 +513,8 @@ async function sendEncryptedDataToSnode<T extends GroupPubkeyType | PubkeyType>(
sortedSubRequests,
method,
abortSignal,
}: {
allow401s,
}: WithAllow401s & {
sortedSubRequests: SortedSubRequestsType<T>; // keeping those as an array because the order needs to be enforced for some (group keys for instance)
destination: T;
method: MethodBatchType;
@ -523,6 +528,7 @@ async function sendEncryptedDataToSnode<T extends GroupPubkeyType | PubkeyType>(
associatedWith: destination,
method,
abortSignal,
allow401s,
});
},
{

@ -25,3 +25,4 @@ export type WithLocalMessageDeletionType = { deletionType: 'complete' | 'markDel
export type ShortenOrExtend = 'extend' | 'shorten' | '';
export type WithShortenOrExtend = { shortenOrExtend: ShortenOrExtend };
export type WithMessagesHashes = { messagesHashes: Array<string> };
export type WithAllow401s = { allow401s: boolean };

@ -200,6 +200,7 @@ class GroupInviteJob extends PersistedJob<GroupInvitePersistedData> {
groupPk,
unrevokeSubRequest,
extraStoreRequests: [],
allow401s: false,
});
if (sequenceResult !== RunJobResult.Success) {
await LibSessionUtil.saveDumpsToDb(groupPk);

@ -68,13 +68,10 @@ async function getPendingRevokeParams({
const revokeChanges: RevokeChanges = [];
const unrevokeChanges: RevokeChanges = [];
for (let index = 0; index < withoutHistory.length; index++) {
const m = withoutHistory[index];
const token = await MetaGroupWrapperActions.swarmSubAccountToken(groupPk, m);
unrevokeChanges.push({ action: 'unrevoke_subaccount', tokenToRevokeHex: token });
}
for (let index = 0; index < withHistory.length; index++) {
const m = withHistory[index];
const toUnrevoke = withoutHistory.concat(withHistory);
for (let index = 0; index < toUnrevoke.length; index++) {
const m = toUnrevoke[index];
const token = await MetaGroupWrapperActions.swarmSubAccountToken(groupPk, m);
unrevokeChanges.push({ action: 'unrevoke_subaccount', tokenToRevokeHex: token });
}
@ -198,6 +195,7 @@ class GroupPendingRemovalsJob extends PersistedJob<GroupPendingRemovalsPersisted
destination: groupPk,
method: 'sequence',
abortSignal: controller.signal,
allow401s: false,
}),
30 * DURATION.SECONDS,
controller

@ -36,6 +36,7 @@ import {
RunJobResult,
} from '../PersistedJob';
import { DURATION } from '../../../constants';
import { WithAllow401s } from '../../../types/with';
const defaultMsBetweenRetries = 15000; // a long time between retries, to avoid running multiple jobs at the same time, when one was postponed at the same time as one already planned (5s)
const defaultMaxAttempts = 2;
@ -89,7 +90,9 @@ async function pushChangesToGroupSwarmIfNeeded({
supplementalKeysSubRequest,
deleteAllMessagesSubRequest,
extraStoreRequests,
allow401s,
}: WithGroupPubkey &
WithAllow401s &
WithRevokeSubRequest & {
supplementalKeysSubRequest?: StoreGroupKeysSubRequest;
deleteAllMessagesSubRequest?: DeleteAllFromGroupMsgNodeSubRequest;
@ -170,6 +173,7 @@ async function pushChangesToGroupSwarmIfNeeded({
destination: groupPk,
method: 'sequence',
abortSignal: controller.signal,
allow401s,
}),
30 * DURATION.SECONDS,
controller
@ -250,6 +254,7 @@ class GroupSyncJob extends PersistedJob<GroupSyncPersistedData> {
return await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk: thisJobDestination,
extraStoreRequests: [],
allow401s: false,
});
} catch (e) {
window.log.warn('GroupSyncJob failed with', e.message);

@ -126,6 +126,7 @@ async function pushChangesToUserSwarmIfNeeded() {
destination: us,
method: 'sequence',
abortSignal: controller.signal,
allow401s: false, // user swarm push, we shouldn't need to allow 401s
}),
30 * DURATION.SECONDS,
controller

@ -225,6 +225,7 @@ const initNewGroupInWrapper = createAsyncThunk(
const result = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests,
allow401s: false,
});
if (result !== RunJobResult.Success) {
window.log.warn('GroupSync.pushChangesToGroupSwarmIfNeeded during create failed');
@ -670,6 +671,7 @@ async function handleMemberAddedFromUI({
revokeSubRequest,
unrevokeSubRequest,
extraStoreRequests,
allow401s: false,
});
if (sequenceResult !== RunJobResult.Success) {
await LibSessionUtil.saveDumpsToDb(groupPk);
@ -795,6 +797,7 @@ async function handleMemberRemovedFromUI({
const sequenceResult = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests,
allow401s: false,
});
if (sequenceResult !== RunJobResult.Success) {
throw new Error(
@ -880,6 +883,7 @@ async function handleNameChangeFromUI({
const batchResult = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests,
allow401s: false,
});
if (batchResult !== RunJobResult.Success) {
@ -1005,6 +1009,7 @@ const triggerFakeAvatarUpdate = createAsyncThunk(
const batchResult = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests,
allow401s: false,
});
if (!batchResult) {
window.log.warn(`failed to send avatarChange message for group ${ed25519Str(groupPk)}`);
@ -1060,6 +1065,7 @@ const triggerFakeDeleteMsgBeforeNow = createAsyncThunk(
const batchResult = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests,
allow401s: false,
});
if (!batchResult) {
window.log.warn(

@ -1,5 +1,6 @@
import { createSelector } from '@reduxjs/toolkit';
import { useSelector } from 'react-redux';
import { LeftOverlayMode, SectionStateType, SectionType } from '../ducks/section';
import { StateType } from '../reducer';
import type { SessionSettingCategory } from '../../types/ReduxTypes';
@ -34,9 +35,13 @@ export const getRightOverlayMode = (state: StateType) => {
return state.section.rightOverlayMode;
};
export const getIsMessageRequestOverlayShown = (state: StateType) => {
const getIsMessageRequestOverlayShown = (state: StateType) => {
const focusedSection = getFocusedSection(state);
const leftOverlayMode = getLeftOverlayMode(state);
return focusedSection === SectionType.Message && leftOverlayMode === 'message-requests';
};
export function useIsMessageRequestOverlayShown() {
return useSelector(getIsMessageRequestOverlayShown);
}

@ -297,6 +297,7 @@ describe('GroupSyncJob pushChangesToGroupSwarmIfNeeded', () => {
const result = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests: [],
allow401s: false,
});
expect(result).to.be.eq(RunJobResult.Success);
expect(sendStub.callCount).to.be.eq(0);
@ -322,6 +323,7 @@ describe('GroupSyncJob pushChangesToGroupSwarmIfNeeded', () => {
const result = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests: [],
allow401s: false,
});
sendStub.resolves(undefined);
@ -369,6 +371,7 @@ describe('GroupSyncJob pushChangesToGroupSwarmIfNeeded', () => {
const result = await GroupSync.pushChangesToGroupSwarmIfNeeded({
groupPk,
extraStoreRequests: [],
allow401s: false,
});
expect(sendStub.callCount).to.be.eq(1);

Loading…
Cancel
Save