diff --git a/lib/hooks/invite-links.js b/lib/hooks/invite-links.js index 5a93db110..a39578a05 100644 --- a/lib/hooks/invite-links.js +++ b/lib/hooks/invite-links.js @@ -1,357 +1,379 @@ // @flow import * as React from 'react'; import { addKeyserverActionType } from '../actions/keyserver-actions.js'; import { useCreateOrUpdatePublicLink, createOrUpdatePublicLinkActionTypes, useDisableInviteLink, disableInviteLinkLinkActionTypes, } from '../actions/link-actions.js'; import { joinThreadActionTypes, useJoinThread, } from '../actions/thread-actions.js'; import { extractKeyserverIDFromID } from '../keyserver-conn/keyserver-call-utils.js'; import { createLoadingStatusSelector } from '../selectors/loading-selectors.js'; import { threadInfoSelector } from '../selectors/thread-selectors.js'; import { isLoggedInToKeyserver } from '../selectors/user-selectors.js'; import type { KeyserverOverride } from '../shared/invite-links.js'; import { useIsKeyserverURLValid } from '../shared/keyserver-utils.js'; import { permissionsAndAuthRelatedRequestTimeout } from '../shared/timeouts.js'; import type { CalendarQuery } from '../types/entry-types.js'; import type { SetState } from '../types/hook-types.js'; import { defaultKeyserverInfo } from '../types/keyserver-types.js'; import type { InviteLink, InviteLinkVerificationResponse, } from '../types/link-types.js'; import type { LoadingStatus } from '../types/loading-types.js'; import type { ThreadInfo } from '../types/minimally-encoded-thread-permissions-types.js'; import { useDispatchActionPromise } from '../utils/redux-promise-utils.js'; import { useDispatch, useSelector } from '../utils/redux-utils.js'; const createOrUpdatePublicLinkStatusSelector = createLoadingStatusSelector( createOrUpdatePublicLinkActionTypes, ); const disableInviteLinkStatusSelector = createLoadingStatusSelector( disableInviteLinkLinkActionTypes, ); function useInviteLinksActions( communityID: string, inviteLink: ?InviteLink, ): { +error: ?string, +isLoading: boolean, +isChanged: boolean, +name: string, +setName: SetState, +createOrUpdateInviteLink: () => mixed, +disableInviteLink: () => mixed, } { const [name, setName] = React.useState( inviteLink?.name ?? Math.random().toString(36).slice(-9), ); const [error, setError] = React.useState(null); const dispatchActionPromise = useDispatchActionPromise(); const callCreateOrUpdatePublicLink = useCreateOrUpdatePublicLink(); const createCreateOrUpdateActionPromise = React.useCallback(async () => { setError(null); try { return await callCreateOrUpdatePublicLink({ name, communityID, }); } catch (e) { setError(e.message); throw e; } }, [callCreateOrUpdatePublicLink, communityID, name]); const createOrUpdateInviteLink = React.useCallback(() => { void dispatchActionPromise( createOrUpdatePublicLinkActionTypes, createCreateOrUpdateActionPromise(), ); }, [createCreateOrUpdateActionPromise, dispatchActionPromise]); const disableInviteLinkServerCall = useDisableInviteLink(); const createDisableLinkActionPromise = React.useCallback(async () => { setError(null); try { return await disableInviteLinkServerCall({ name, communityID, }); } catch (e) { setError(e.message); throw e; } }, [disableInviteLinkServerCall, communityID, name]); const disableInviteLink = React.useCallback(() => { void dispatchActionPromise( disableInviteLinkLinkActionTypes, createDisableLinkActionPromise(), ); }, [createDisableLinkActionPromise, dispatchActionPromise]); const disableInviteLinkStatus = useSelector(disableInviteLinkStatusSelector); const createOrUpdatePublicLinkStatus = useSelector( createOrUpdatePublicLinkStatusSelector, ); const isLoading = createOrUpdatePublicLinkStatus === 'loading' || disableInviteLinkStatus === 'loading'; return React.useMemo( () => ({ error, isLoading, isChanged: name !== inviteLink?.name, name, setName, createOrUpdateInviteLink, disableInviteLink, }), [ createOrUpdateInviteLink, disableInviteLink, error, inviteLink?.name, isLoading, name, ], ); } -const joinThreadLoadingStatusSelector = createLoadingStatusSelector( - joinThreadActionTypes, -); - export type LinkStatus = 'invalid' | 'valid' | 'timed_out' | 'already_joined'; const inviteLinkTexts: { +[LinkStatus]: { +header: string, +message: (isThreadLink: boolean) => string, }, } = { invalid: { header: 'Invite invalid', message: () => 'This invite link may be expired. Please try again with another invite' + ' link.', }, ['timed_out']: { header: 'Timeout', message: () => 'The request has timed out.', }, ['already_joined']: { header: 'Already a member', message: isThreadLink => `You are already a member of this ${ isThreadLink ? 'thread' : 'community' }.`, }, }; type AcceptInviteLinkParams = { +verificationResponse: InviteLinkVerificationResponse, +inviteSecret: string, +keyserverOverride: ?KeyserverOverride, +calendarQuery: () => CalendarQuery, +closeModal: () => mixed, + +linkStatus: LinkStatus, +setLinkStatus: SetState, +navigateToThread: ThreadInfo => mixed, }; function useAcceptInviteLink(params: AcceptInviteLinkParams): { +join: () => mixed, +joinLoadingStatus: LoadingStatus, } { const { verificationResponse, inviteSecret, keyserverOverride, calendarQuery, closeModal, + linkStatus, setLinkStatus, navigateToThread, } = params; const dispatch = useDispatch(); const callJoinThread = useJoinThread(); const communityID = verificationResponse.community?.id; let keyserverID = keyserverOverride?.keyserverID; if (!keyserverID && communityID) { keyserverID = extractKeyserverIDFromID(communityID); } const isKeyserverKnown = useSelector(state => keyserverID ? !!state.keyserverStore.keyserverInfos[keyserverID] : false, ); const isAuthenticated = useSelector(isLoggedInToKeyserver(keyserverID)); const keyserverURL = keyserverOverride?.keyserverURL; const isKeyserverURLValid = useIsKeyserverURLValid(keyserverURL); const [ongoingJoinData, setOngoingJoinData] = React.useState mixed, +reject: () => mixed, +communityID: string, }>(null); const timeoutRef = React.useRef(); React.useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, []); + const [step, setStep] = React.useState< + | 'inactive' + | 'add_keyserver' + | 'auth_to_keyserver' + | 'join_community' + | 'finished', + >('inactive'); const createJoinPromise = React.useCallback(() => { return new Promise((resolve, reject) => { if ( !keyserverID || !communityID || keyserverID !== extractKeyserverIDFromID(communityID) ) { reject(); setLinkStatus('invalid'); setOngoingJoinData(null); return; } const timeoutID = setTimeout(() => { reject(); setOngoingJoinData(oldData => { if (oldData) { setLinkStatus('timed_out'); } return null; }); }, permissionsAndAuthRelatedRequestTimeout); timeoutRef.current = timeoutID; const resolveAndClearTimeout = () => { clearTimeout(timeoutID); resolve(); }; const rejectAndClearTimeout = () => { clearTimeout(timeoutID); reject(); }; setOngoingJoinData({ resolve: resolveAndClearTimeout, reject: rejectAndClearTimeout, communityID, }); + setStep('add_keyserver'); }); }, [communityID, keyserverID, setLinkStatus]); React.useEffect(() => { void (async () => { - if (!ongoingJoinData || isKeyserverKnown) { + if (!ongoingJoinData || step !== 'add_keyserver') { return; } + if (isKeyserverKnown) { + setStep('auth_to_keyserver'); + return; + } + const isValid = await isKeyserverURLValid(); if (!isValid || !keyserverURL) { setLinkStatus('invalid'); ongoingJoinData.reject(); setOngoingJoinData(null); return; } dispatch({ type: addKeyserverActionType, payload: { keyserverAdminUserID: keyserverID, newKeyserverInfo: defaultKeyserverInfo(keyserverURL), }, }); })(); }, [ dispatch, isKeyserverKnown, isKeyserverURLValid, - ongoingJoinData, keyserverID, keyserverURL, + ongoingJoinData, setLinkStatus, + step, ]); + React.useEffect(() => { + if (step === 'auth_to_keyserver' && ongoingJoinData && isAuthenticated) { + setStep('join_community'); + } + }, [isAuthenticated, ongoingJoinData, step]); + const dispatchActionPromise = useDispatchActionPromise(); - const [joined, setJoined] = React.useState(false); React.useEffect(() => { void (async () => { - if (!ongoingJoinData || !isAuthenticated) { + if (!ongoingJoinData || step !== 'join_community') { return; } const threadID = ongoingJoinData.communityID; const query = calendarQuery(); const joinThreadPromise = callJoinThread({ threadID, calendarQuery: { startDate: query.startDate, endDate: query.endDate, filters: [ ...query.filters, { type: 'threads', threadIDs: [threadID] }, ], }, inviteLinkSecret: inviteSecret, }); void dispatchActionPromise(joinThreadActionTypes, joinThreadPromise); try { await joinThreadPromise; - setJoined(true); + setStep('finished'); ongoingJoinData.resolve(); } catch (e) { setLinkStatus(status => (status === 'valid' ? 'invalid' : status)); ongoingJoinData.reject(); } finally { setOngoingJoinData(null); } })(); }, [ calendarQuery, callJoinThread, dispatchActionPromise, inviteSecret, - isAuthenticated, ongoingJoinData, setLinkStatus, + step, ]); const threadInfos = useSelector(threadInfoSelector); React.useEffect(() => { - if (!joined) { + if (step !== 'finished') { return; } const threadID = verificationResponse.community?.id; if (!threadID || !threadInfos[threadID]) { closeModal(); return; } navigateToThread(threadInfos[threadID]); }, [ - joined, - navigateToThread, closeModal, + navigateToThread, + step, threadInfos, verificationResponse.community?.id, ]); - const joinLoadingStatus = useSelector(joinThreadLoadingStatusSelector); + let joinLoadingStatus: LoadingStatus = 'inactive'; + if (linkStatus === 'invalid' || linkStatus === 'timed_out') { + joinLoadingStatus = 'error'; + } else if (step !== 'inactive' && step !== 'finished') { + joinLoadingStatus = 'loading'; + } return React.useMemo( () => ({ join: createJoinPromise, joinLoadingStatus, }), [createJoinPromise, joinLoadingStatus], ); } export { useInviteLinksActions, useAcceptInviteLink, inviteLinkTexts }; diff --git a/native/navigation/invite-link-modal.react.js b/native/navigation/invite-link-modal.react.js index 6102d5cf3..69d843e0b 100644 --- a/native/navigation/invite-link-modal.react.js +++ b/native/navigation/invite-link-modal.react.js @@ -1,272 +1,273 @@ // @flow import * as React from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; import { inviteLinkTexts, useAcceptInviteLink, } from 'lib/hooks/invite-links.js'; import type { LinkStatus } from 'lib/hooks/invite-links.js'; import { threadInfoSelector } from 'lib/selectors/thread-selectors.js'; import type { KeyserverOverride } from 'lib/shared/invite-links'; import type { InviteLinkVerificationResponse } from 'lib/types/link-types.js'; import type { ThreadInfo } from 'lib/types/minimally-encoded-thread-permissions-types'; import { nonThreadCalendarQuery } from './nav-selectors.js'; import { NavContext } from './navigation-context.js'; import type { RootNavigationProp } from './root-navigator.react.js'; import type { NavigationRoute } from './route-names.js'; import { useNavigateToThread } from '../chat/message-list-types.js'; import Button from '../components/button.react.js'; import Modal from '../components/modal.react.js'; import { useSelector } from '../redux/redux-utils.js'; import { useStyles } from '../themes/colors.js'; export type InviteLinkModalParams = { +invitationDetails: InviteLinkVerificationResponse, +secret: string, +keyserverOverride?: ?KeyserverOverride, }; type Props = { +navigation: RootNavigationProp<'InviteLinkModal'>, +route: NavigationRoute<'InviteLinkModal'>, }; function InviteLinkModal(props: Props): React.Node { const styles = useStyles(unboundStyles); const { invitationDetails, secret, keyserverOverride } = props.route.params; const [linkStatus, setLinkStatus] = React.useState( invitationDetails.status === 'expired' ? 'invalid' : invitationDetails.status, ); const navContext = React.useContext(NavContext); const calendarQuery = useSelector(state => nonThreadCalendarQuery({ redux: state, navContext, }), ); const navigateToThreadWithParams = useNavigateToThread(); const navigateToThread = React.useCallback( (threadInfo: ThreadInfo) => { navigateToThreadWithParams({ threadInfo }); }, [navigateToThreadWithParams], ); const { join, joinLoadingStatus } = useAcceptInviteLink({ verificationResponse: invitationDetails, inviteSecret: secret, keyserverOverride, calendarQuery, closeModal: props.navigation.goBack, + linkStatus, setLinkStatus, navigateToThread, }); const header = React.useMemo(() => { if (invitationDetails.status === 'valid' && linkStatus === 'valid') { let additionalCommunityDescription = null; if (invitationDetails.thread) { additionalCommunityDescription = ( <> within {invitationDetails.community.name} ); } const targetName = invitationDetails.thread?.name ?? invitationDetails.community.name; return ( <> You have been invited to join {targetName} {additionalCommunityDescription} ); } return ( <> {inviteLinkTexts[linkStatus].header} {inviteLinkTexts[linkStatus].message(!!invitationDetails.thread)} ); }, [ invitationDetails, styles.threadName, styles.communityIntro, styles.invalidInviteExplanation, styles.invalidInviteTitle, styles.invitation, linkStatus, ]); const threadInfos = useSelector(threadInfoSelector); const closeModal = React.useCallback(() => { const threadID = invitationDetails.thread?.id ?? invitationDetails.community?.id; if (linkStatus === 'already_joined' && threadID && threadInfos[threadID]) { navigateToThread(threadInfos[threadID]); } else { props.navigation.goBack(); } }, [ invitationDetails.community?.id, invitationDetails.thread?.id, linkStatus, navigateToThread, props.navigation, threadInfos, ]); const buttons = React.useMemo(() => { if (linkStatus === 'valid') { const joinButtonContent = joinLoadingStatus === 'loading' ? ( ) : ( Accept invite ); return ( <> ); } return ( ); }, [ closeModal, join, joinLoadingStatus, linkStatus, props.navigation.goBack, styles.activityIndicatorStyle, styles.button, styles.buttonPrimary, styles.buttonSecondary, styles.buttonText, styles.gap, ]); return ( {header} {buttons} ); } const unboundStyles = { modal: { backgroundColor: 'modalForeground', paddingVertical: 24, paddingHorizontal: 16, flex: 0, }, invitation: { color: 'whiteText', textAlign: 'center', fontSize: 14, fontWeight: '400', lineHeight: 22, marginBottom: 24, }, communityIntro: { color: 'whiteText', textAlign: 'center', fontSize: 14, fontWeight: '400', lineHeight: 22, marginBottom: 24, marginTop: 16, }, threadName: { color: 'whiteText', textAlign: 'center', fontSize: 18, fontWeight: '500', lineHeight: 24, }, invalidInviteTitle: { color: 'whiteText', textAlign: 'center', fontSize: 22, fontWeight: '500', lineHeight: 28, marginBottom: 24, }, invalidInviteExplanation: { color: 'whiteText', textAlign: 'center', fontSize: 14, fontWeight: '400', lineHeight: 22, }, separator: { height: 1, backgroundColor: 'modalSeparator', marginVertical: 24, }, gap: { marginBottom: 16, }, button: { borderRadius: 8, paddingVertical: 12, paddingHorizontal: 24, }, buttonPrimary: { backgroundColor: 'purpleButton', }, buttonSecondary: { borderColor: 'secondaryButtonBorder', borderWidth: 1, }, buttonText: { color: 'whiteText', textAlign: 'center', fontSize: 16, fontWeight: '500', lineHeight: 24, }, activityIndicatorStyle: { paddingVertical: 2, }, }; export default InviteLinkModal; diff --git a/web/invite-links/accept-invite-modal.react.js b/web/invite-links/accept-invite-modal.react.js index 42435104f..7bebaf14b 100644 --- a/web/invite-links/accept-invite-modal.react.js +++ b/web/invite-links/accept-invite-modal.react.js @@ -1,132 +1,133 @@ // @flow import * as React from 'react'; import ModalOverlay from 'lib/components/modal-overlay.react.js'; import { useModalContext } from 'lib/components/modal-provider.react.js'; import { inviteLinkTexts, useAcceptInviteLink, } from 'lib/hooks/invite-links.js'; import type { LinkStatus } from 'lib/hooks/invite-links.js'; import type { KeyserverOverride } from 'lib/shared/invite-links.js'; import { type InviteLinkVerificationResponse } from 'lib/types/link-types.js'; import type { ThreadInfo } from 'lib/types/minimally-encoded-thread-permissions-types.js'; import { useDispatch } from 'lib/utils/redux-utils.js'; import css from './accept-invite-modal.css'; import Button, { buttonThemes } from '../components/button.react.js'; import { updateNavInfoActionType } from '../redux/action-types.js'; import { useSelector } from '../redux/redux-utils.js'; import { nonThreadCalendarQuery } from '../selectors/nav-selectors.js'; type Props = { +verificationResponse: InviteLinkVerificationResponse, +inviteSecret: string, +keyserverOverride?: ?KeyserverOverride, }; function AcceptInviteModal(props: Props): React.Node { const { verificationResponse, inviteSecret, keyserverOverride } = props; const [linkStatus, setLinkStatus] = React.useState( verificationResponse.status === 'expired' ? 'invalid' : verificationResponse.status, ); const { popModal } = useModalContext(); const calendarQuery = useSelector(nonThreadCalendarQuery); const dispatch = useDispatch(); const navigateToThread = React.useCallback( (threadInfo: ThreadInfo) => { dispatch({ type: updateNavInfoActionType, payload: { chatMode: 'view', activeChatThreadID: threadInfo.id, tab: 'chat', }, }); popModal(); }, [dispatch, popModal], ); const { join, joinLoadingStatus } = useAcceptInviteLink({ verificationResponse, inviteSecret, keyserverOverride, calendarQuery, closeModal: popModal, + linkStatus, setLinkStatus, navigateToThread, }); let content; if (verificationResponse.status === 'valid' && linkStatus === 'valid') { const { community } = verificationResponse; let additionalCommunityDescription = null; if (verificationResponse.thread) { additionalCommunityDescription = (
within
{community.name}
); } const targetName = verificationResponse.thread?.name ?? verificationResponse.community.name; content = ( <>
You have been invited to join
{targetName}
{additionalCommunityDescription}
); } else { content = ( <>
{inviteLinkTexts[linkStatus].header}
{inviteLinkTexts[linkStatus].message(!!verificationResponse.thread)}

); } return (
{content}
); } export default AcceptInviteModal;