mattermost-mobile-upstream/app/products/calls/hooks.ts
Elias Nahum b6fc85385e
Migrate from RNN to Expo router (#9402)
* Expo-Router partial migration

* Full migration to ExpoRouter

* i18n

* add tests

* Merge branch 'main' into expo-router

* align package-lock.json

* i18n

* feedback review

* feedback review

* android 16kb patch

* Refactored emoji picker keyboard using a state machine

* set android launch_screen in drawables instead of layout

* no conditional hooks

* remove duplicate call in test

* address feedback

* fix tests and address more feedback

* small corrections

* small corrections

* small corrections

* fix draft test

* fix draft test 2

* remove navigateToScreen in draff test

* fix nit in draft test

* remove doc file

* Feedback review

* fix snapshots

* improve test coverage

* fix i18n

* Upgrade t o RN 0.83, other dependencies and new architecture (#9737)

* library hardware-keyboard android new arch support fix

* library rnshare android new arch support fix

* library rnutils android new arch support fix

* library secure-pdf-viewer add new arch support

* Enable new arch on iOS and Android

* update emm and network client with new-arch

* update intune to use new-arch

* performance improvements

* fix tests

* fixes post input on new-arch

* fix android emoji picker

* remove doc

* run tests in parallel

* upgrade to React Native 0.83.9, Expo 55, React 19, and New Architecture

Bumps core dependencies to their latest versions:
- React Native 0.77.3 → 0.83.9 (New Architecture enabled)
- React 18.3.1 → 19.2.5
- Expo SDK 52 → 55
- TypeScript 5.8.3 → 6.0.3
- Node.js 22.16.0 → 24.15.0
- react-native-reanimated 3.17.3 → 4.3.0
- Various other dependency upgrades

Migrates iOS AppDelegate from Objective-C to Swift, updates Android
build tooling and Gradle wrapper, refreshes all patches and font
assets, and adapts app code, tests, and CI workflows throughout for
API changes introduced by these upgrades.

* remove unecessary dismissKeyboard in notifications

* feedback review

* update intune to use new-arch

* update @mattermost deps

* missing i18n string

* additional fixes

* update fastlane
2026-05-13 17:44:55 +08:00

225 lines
7.9 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
// Check if calls is enabled. If it is, then run fn; if it isn't, show an alert and set
// msgPostfix to ' (Not Available)'.
import {useCallback, useEffect, useState} from 'react';
import {useIntl} from 'react-intl';
import {Alert, Platform} from 'react-native';
import Permissions from 'react-native-permissions';
import {initializeVoiceTrack} from '@calls/actions/calls';
import {
getCallsConfig,
getCurrentCall,
setMicPermissionsGranted,
useCallsState,
useChannelsWithCalls,
useCurrentCall,
useGlobalCallsState,
useIncomingCalls,
} from '@calls/state';
import {type CallSession} from '@calls/types/calls';
import {errorAlert, isHostControlsAllowed} from '@calls/utils';
import {Screens} from '@constants';
import {
CALL_ERROR_BAR_HEIGHT,
CALL_NOTIFICATION_BAR_HEIGHT,
CURRENT_CALL_BAR_HEIGHT,
JOIN_CALL_BAR_HEIGHT,
} from '@constants/view';
import {useServerUrl} from '@context/server';
import DatabaseManager from '@database/manager';
import {useAppState} from '@hooks/device';
import NetworkManager from '@managers/network_manager';
import {queryAllActiveServers} from '@queries/app/servers';
import {getCurrentUser} from '@queries/servers/user';
import {navigateToScreen} from '@screens/navigation';
import {getFullErrorMessage} from '@utils/errors';
import {openUserProfile} from '@utils/navigation';
import {isSystemAdmin} from '@utils/user';
import type {Client} from '@client/rest';
export const useTryCallsFunction = (fn: () => void) => {
const intl = useIntl();
const serverUrl = useServerUrl();
const [msgPostfix, setMsgPostfix] = useState('');
const [clientError, setClientError] = useState('');
let client: Client | undefined;
if (!clientError) {
try {
client = NetworkManager.getClient(serverUrl);
} catch (error) {
setClientError(getFullErrorMessage(error));
}
}
const tryFn = useCallback(async () => {
let enabled;
try {
enabled = await client?.getEnabled();
} catch (error) {
errorAlert(getFullErrorMessage(error), intl);
return;
}
if (enabled) {
setMsgPostfix('');
fn();
return;
}
if (clientError) {
errorAlert(clientError, intl);
return;
}
const title = intl.formatMessage({
id: 'mobile.calls_not_available_title',
defaultMessage: 'Calls is not enabled',
});
const message = intl.formatMessage({
id: 'mobile.calls_not_available_msg',
defaultMessage: 'Please contact your System Admin to enable the feature.',
});
const ok = intl.formatMessage({
id: 'mobile.calls_ok',
defaultMessage: 'OK',
});
const notAvailable = intl.formatMessage({
id: 'mobile.calls_not_available_option',
defaultMessage: '(Not available)',
});
Alert.alert(
title,
message,
[
{
text: ok,
style: 'cancel',
},
],
);
setMsgPostfix(` ${notAvailable}`);
}, [client, fn, clientError, intl]);
return [tryFn, msgPostfix] as [() => Promise<void>, string];
};
const micPermission = Platform.select({
ios: Permissions.PERMISSIONS.IOS.MICROPHONE,
default: Permissions.PERMISSIONS.ANDROID.RECORD_AUDIO,
});
export const usePermissionsChecker = (micPermissionsGranted: boolean) => {
const appState = useAppState();
const [hasPermission, setHasPermission] = useState(micPermissionsGranted);
useEffect(() => {
const asyncFn = async () => {
if (appState === 'active') {
const result = (await Permissions.check(micPermission)) === Permissions.RESULTS.GRANTED;
setHasPermission(result);
if (result) {
initializeVoiceTrack();
setMicPermissionsGranted(result);
}
}
};
if (!micPermissionsGranted) {
asyncFn();
}
}, [appState, micPermissionsGranted]);
return hasPermission;
};
export const useCallsAdjustment = (serverUrl: string, channelId: string): number => {
const incomingCalls = useIncomingCalls().incomingCalls;
const channelsWithCalls = useChannelsWithCalls(serverUrl);
const callsState = useCallsState(serverUrl);
const globalCallsState = useGlobalCallsState();
const currentCall = useCurrentCall();
const [numServers, setNumServers] = useState(1);
const micPermissionsGranted = usePermissionsChecker(globalCallsState.micPermissionsGranted);
const dismissed = Boolean(callsState.calls[channelId]?.dismissed[callsState.myUserId]);
const inCurrentCall = currentCall?.id === channelId;
const joinCallBannerVisible = Boolean(channelsWithCalls[channelId]) && !dismissed && !inCurrentCall;
useEffect(() => {
const getNumServers = async () => {
const query = await queryAllActiveServers()?.fetch();
setNumServers(query?.length || 0);
};
getNumServers();
}, []);
// Do we have calls banners?
const currentCallBarVisible = Boolean(currentCall);
const micPermissionsError = !micPermissionsGranted && (currentCall && !currentCall.micPermissionsErrorDismissed);
const callQualityAlert = Boolean(currentCall?.callQualityAlert);
const incomingCallsShowing = incomingCalls.filter((ic) => ic.channelID !== channelId);
const notificationBarHeight = CALL_NOTIFICATION_BAR_HEIGHT + (numServers > 1 ? 8 : 0);
const callsIncomingAdjustment = (incomingCallsShowing.length * notificationBarHeight) + (incomingCallsShowing.length * 8);
return (currentCallBarVisible ? CURRENT_CALL_BAR_HEIGHT + 8 : 0) +
(micPermissionsError ? CALL_ERROR_BAR_HEIGHT + 8 : 0) +
(callQualityAlert ? CALL_ERROR_BAR_HEIGHT + 8 : 0) +
(joinCallBannerVisible ? JOIN_CALL_BAR_HEIGHT + 8 : 0) +
callsIncomingAdjustment;
};
export const useHostControlsAvailable = () => {
const [isAdmin, setIsAdmin] = useState(false);
const currentCall = getCurrentCall();
const serverUrl = currentCall?.serverUrl || '';
const config = getCallsConfig(serverUrl);
const allowed = isHostControlsAllowed(config);
useEffect(() => {
const getUser = async () => {
const database = DatabaseManager.serverDatabases[serverUrl]?.database;
if (!database) {
return;
}
const user = await getCurrentUser(database);
setIsAdmin(isSystemAdmin(user?.roles || ''));
};
getUser();
}, [serverUrl]);
const isHost = currentCall?.hostId === currentCall?.myUserId;
return allowed && (isHost || isAdmin);
};
export const useHostMenus = () => {
const currentCall = useCurrentCall();
const hostControlsAvailable = useHostControlsAvailable();
const isHost = currentCall?.hostId === currentCall?.myUserId;
const openHostControl = useCallback(async (sessionId: string) => {
navigateToScreen(Screens.CALL_HOST_CONTROLS, {sessionId});
}, []);
const openProfile = useCallback(async (session: CallSession) => {
openUserProfile({
userId: session.userId,
});
}, []);
const onPress = useCallback((session: CallSession) => () => {
// Show host controls when allowed and I'm host or admin,
// but don't show if this is me and I'm the host already.
const isYou = session.userId === currentCall?.myUserId;
if (hostControlsAvailable && !(isYou && isHost)) {
openHostControl(session.sessionId);
} else {
openProfile(session);
}
}, [currentCall?.myUserId, hostControlsAvailable, isHost, openHostControl, openProfile]);
return {hostControlsAvailable, onPress, openProfile};
};