mattermost-mobile/app/managers/session_manager.ts
Rahim Rahman 597e03d7d8
feat(MM-65145): Network connectivity/performance observer (#9173)
* feat: implement floating banner system

- Add FloatingBanner component with gesture support and keyboard awareness
- Implement BannerManager singleton for banner lifecycle management
- Create floating banner screen with SafeAreaProvider integration
- Add comprehensive banner configuration types and positioning
- Update Banner component to use modern gesture handling
- Enhance BannerItem with improved typography and spacing (40px height)
- Add ConnectionBanner improvements with better sizing
- Remove ConnectionBanner from channel list (moved to floating system)
- Update screens constants (remove FLOATING_BANNER - handled as overlay)
- Add i18n support for limited network connection message

The system provides:
- Auto-hide functionality with customizable duration
- Position-aware rendering (top/bottom with keyboard adjustment)
- Tablet-specific offset handling
- Swipe-to-dismiss with configurable thresholds
- Custom component support alongside default banner items
- Comprehensive test coverage with device-specific scenarios

* docs: add floating banner system documentation and cleanup

- Add comprehensive floating-banner.md with architecture diagrams
- Remove incompatible connection_banner/index.ts file
- Update device.ts hooks for better keyboard handling
- Simplify screens/index.tsx floating banner registration
- Update test/setup.ts to remove deprecated keyboard mocks
- Clean up keyboard height logic and ESLint issues

The documentation covers:
- System architecture and component relationships
- API reference and usage patterns
- Performance considerations and best practices
- Integration points and troubleshooting guide
- Comprehensive testing strategy

All tests now pass with the updated setup.

* fix issue with translation file

* some self cleanup.

* renamed index.tsx => Banner.tsx

* creaete meaningful tests for Banner component and all the hooks.

* fix tests

* cleanup based on initial review by AI

* dismissible was set to true, changing to what was configured.

* making title and message optional

* feat(MM-65145): Network connectivity/performance observer

* add MONITOR_NETWORK_PERFORMANCE

* i18n stuff

* remove unused props

* Undo some AI changes that caught by another AI

* network connectivity observation md

* addressed some comments in PR

* more fixes based on PR review.

* added future enhancement

* dismissOverlay will be awaited
* delay dismissing overlay so we don't have to show a new one all the time

* make the banner stackable

* Fix issue with last banner dismissal delayed by 2s

* update floating-banner test

* put back an extra space

* add a todo to use namespace
* add comment on priority order for connectivity performance
* use static const vs magic number

* add a guard against adding performanceSubject when server has been removed
* fix failing tests

* clean-up based on review by @enahum

* fix failing test

* fix failiing tests

* rename confusing var

* update changes to types

* fixed issue with swipe not working on android

* performance and connectivity use the same id so that 2 banners won't appear

* fix issue w/ android not registering touch events behind the overlay

* fix failing test

* hideBanner now needs id.

* Connection status unknown added in en.json

* update the doc

* animate the banner moving up when bottom banner first appear.

* removed unused functions and update tests

* add useMemo and useCallback

* update jsdoc to say dismissable is default true

* fix failing test
2025-10-12 10:10:05 -06:00

219 lines
8.4 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import CookieManager, {type Cookie} from '@react-native-cookies/cookies';
import {Image} from 'expo-image';
import {AppState, type AppStateStatus, DeviceEventEmitter, Platform} from 'react-native';
import {removePushDisabledInServerAcknowledged, storeOnboardingViewedValue} from '@actions/app/global';
import {cancelSessionNotification, logout, scheduleSessionNotification} from '@actions/remote/session';
import {Events, Launch} from '@constants';
import DatabaseManager from '@database/manager';
import {resetMomentLocale} from '@i18n';
import {getAllServerCredentials, removeServerCredentials} from '@init/credentials';
import {relaunchApp} from '@init/launch';
import PushNotifications from '@init/push_notifications';
import NetworkConnectivityManager from '@managers/network_connectivity_manager';
import NetworkConnectivitySubscriptionManager from '@managers/network_connectivity_subscription_manager';
import NetworkManager from '@managers/network_manager';
import NetworkPerformanceManager from '@managers/network_performance_manager';
import SecurityManager from '@managers/security_manager';
import WebsocketManager from '@managers/websocket_manager';
import {getAllServers, getServerDisplayName} from '@queries/app/servers';
import {getCurrentUser} from '@queries/servers/user';
import {getThemeFromState} from '@screens/navigation';
import EphemeralStore from '@store/ephemeral_store';
import {deleteFileCache, deleteFileCacheByDir} from '@utils/file';
import {isMainActivity} from '@utils/helpers';
import {urlSafeBase64Encode} from '@utils/security';
import {addNewServer} from '@utils/server';
import type {LaunchType} from '@typings/launch';
type LogoutCallbackArg = {
serverUrl: string;
removeServer: boolean;
}
export class SessionManagerSingleton {
private previousAppState: AppStateStatus;
private scheduling = false;
private terminatingSessionUrl = new Set<string>();
constructor() {
if (Platform.OS === 'android') {
AppState.addEventListener('blur', () => {
this.onAppStateChange('inactive');
});
AppState.addEventListener('focus', () => {
this.onAppStateChange('active');
});
} else {
AppState.addEventListener('change', this.onAppStateChange);
}
DeviceEventEmitter.addListener(Events.SERVER_LOGOUT, this.onLogout);
DeviceEventEmitter.addListener(Events.SESSION_EXPIRED, this.onSessionExpired);
this.previousAppState = AppState.currentState;
}
init() {
this.cancelAllSessionNotifications();
}
private cancelAllSessionNotifications = async () => {
const serverCredentials = await getAllServerCredentials();
for (const {serverUrl} of serverCredentials) {
cancelSessionNotification(serverUrl);
}
};
private clearCookies = async (serverUrl: string, webKit: boolean) => {
try {
const cookies = await CookieManager.get(serverUrl, webKit);
const values = Object.values(cookies);
values.forEach((cookie: Cookie) => {
CookieManager.clearByName(serverUrl, cookie.name, webKit);
});
} catch (error) {
// Nothing to clear
}
};
private clearCookiesForServer = async (serverUrl: string) => {
if (Platform.OS === 'ios') {
this.clearCookies(serverUrl, false);
this.clearCookies(serverUrl, true);
} else if (Platform.OS === 'android') {
CookieManager.flush();
}
};
private scheduleAllSessionNotifications = async () => {
if (!this.scheduling) {
this.scheduling = true;
const serverCredentials = await getAllServerCredentials();
const promises: Array<Promise<{error: unknown} | {error?: undefined}>> = [];
for (const {serverUrl} of serverCredentials) {
promises.push(scheduleSessionNotification(serverUrl));
}
await Promise.all(promises);
this.scheduling = false;
}
};
private resetLocale = async () => {
if (Object.keys(DatabaseManager.serverDatabases).length) {
const serverDatabase = await DatabaseManager.getActiveServerDatabase();
const user = await getCurrentUser(serverDatabase!);
resetMomentLocale(user?.locale);
} else {
resetMomentLocale();
}
};
private terminateSession = async (serverUrl: string, removeServer: boolean) => {
cancelSessionNotification(serverUrl);
await removeServerCredentials(serverUrl);
PushNotifications.removeServerNotifications(serverUrl);
SecurityManager.removeServer(serverUrl);
NetworkConnectivityManager.setServerConnectionStatus(false, serverUrl);
NetworkManager.invalidateClient(serverUrl);
NetworkConnectivitySubscriptionManager.stop();
NetworkPerformanceManager.removeServer(serverUrl);
WebsocketManager.invalidateClient(serverUrl);
if (removeServer) {
await removePushDisabledInServerAcknowledged(urlSafeBase64Encode(serverUrl));
await DatabaseManager.destroyServerDatabase(serverUrl);
} else {
await DatabaseManager.deleteServerDatabase(serverUrl);
}
this.resetLocale();
this.clearCookiesForServer(serverUrl);
Image.clearDiskCache();
deleteFileCache(serverUrl);
deleteFileCacheByDir('mmPasteInput');
deleteFileCacheByDir('thumbnails');
if (Platform.OS === 'android') {
deleteFileCacheByDir('image_cache');
}
};
private onAppStateChange = async (appState: AppStateStatus) => {
if (appState === this.previousAppState || !isMainActivity()) {
return;
}
this.previousAppState = appState;
switch (appState) {
case 'active':
setTimeout(this.cancelAllSessionNotifications, 750);
break;
case 'inactive':
this.scheduleAllSessionNotifications();
break;
}
};
private onLogout = async ({serverUrl, removeServer}: LogoutCallbackArg) => {
if (this.terminatingSessionUrl.has(serverUrl)) {
return;
}
this.terminatingSessionUrl.add(serverUrl);
const activeServerUrl = await DatabaseManager.getActiveServerUrl();
const activeServerDisplayName = await DatabaseManager.getActiveServerDisplayName();
await this.terminateSession(serverUrl, removeServer);
if (activeServerUrl === serverUrl) {
let displayName = '';
let launchType: LaunchType = Launch.AddServer;
if (!Object.keys(DatabaseManager.serverDatabases).length) {
EphemeralStore.theme = undefined;
launchType = Launch.Normal;
if (activeServerDisplayName) {
displayName = activeServerDisplayName;
}
}
// set the onboardingViewed value to false so the launch will show the onboarding screen after all servers were removed
const servers = await getAllServers();
if (!servers.length) {
await storeOnboardingViewedValue(false);
}
relaunchApp({launchType, serverUrl, displayName});
}
this.terminatingSessionUrl.delete(serverUrl);
};
private onSessionExpired = async (serverUrl: string) => {
this.terminatingSessionUrl.add(serverUrl);
// logout is not doing anything in this scenario, but we keep it
// to keep the same flow as other logout scenarios.
await logout(serverUrl, undefined, {skipServerLogout: true, skipEvents: true});
await this.terminateSession(serverUrl, false);
const activeServerUrl = await DatabaseManager.getActiveServerUrl();
const serverDisplayName = await getServerDisplayName(serverUrl);
await relaunchApp({launchType: Launch.Normal, serverUrl, displayName: serverDisplayName});
if (activeServerUrl) {
addNewServer(getThemeFromState(), serverUrl, serverDisplayName);
} else {
EphemeralStore.theme = undefined;
}
this.terminatingSessionUrl.delete(serverUrl);
};
}
const SessionManager = new SessionManagerSingleton();
export default SessionManager;