Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
207 lines
7.5 KiB
TypeScript
207 lines
7.5 KiB
TypeScript
import type { IRoom } from '@rocket.chat/core-typings';
|
|
import { Emitter } from '@rocket.chat/emitter';
|
|
import { useLocalStorage } from '@rocket.chat/fuselage-hooks';
|
|
import { createPredicateFromFilter } from '@rocket.chat/mongo-adapter';
|
|
import type { FindOptions, SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
|
import { UserContext, useRouteParameter, useSearchParameter } from '@rocket.chat/ui-contexts';
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import { Meteor } from 'meteor/meteor';
|
|
import type { Filter, ObjectId } from 'mongodb';
|
|
import type { ContextType, ReactNode } from 'react';
|
|
import { useEffect, useMemo, useRef } from 'react';
|
|
import type { StoreApi, UseBoundStore } from 'zustand';
|
|
|
|
import { useClearRemovedRoomsHistory } from './hooks/useClearRemovedRoomsHistory';
|
|
import { useDeleteUser } from './hooks/useDeleteUser';
|
|
import { useEmailVerificationWarning } from './hooks/useEmailVerificationWarning';
|
|
import { useReloadAfterLogin } from './hooks/useReloadAfterLogin';
|
|
import { useUpdateAvatar } from './hooks/useUpdateAvatar';
|
|
import { useIdleConnection } from '../../hooks/useIdleConnection';
|
|
import type { IDocumentMapStore } from '../../lib/cachedStores/DocumentMapStore';
|
|
import { applyQueryOptions } from '../../lib/cachedStores/applyQueryOptions';
|
|
import { getDdpSdk } from '../../lib/sdk/ddpSdk';
|
|
import { settings } from '../../lib/settings';
|
|
import { userIdStore } from '../../lib/user';
|
|
import { Users, Rooms, Subscriptions } from '../../stores';
|
|
import { useSamlInviteToken } from '../../views/invite/hooks/useSamlInviteToken';
|
|
|
|
export type UserProviderProps = {
|
|
children: ReactNode;
|
|
};
|
|
|
|
// Local logout broadcaster — `onLogout(cb)` consumers (e.g. e2ee cleanup) still
|
|
// subscribe to this. The post-logout side effects that used to require a
|
|
// `sdk.call('logoutCleanUp')` round-trip (afterLogoutCleanUpCallback +
|
|
// Apps.IPostUserLoggedOut) now fire server-side via `Accounts.onLogout` and
|
|
// `POST /v1/users.logout`, so this emitter is purely client-side fan-out.
|
|
const ee = new Emitter();
|
|
getDdpSdk().account.onLogout(() => ee.emit('logout'));
|
|
|
|
const queryRoom = (
|
|
query: Filter<Pick<IRoom, '_id'>>,
|
|
): [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => IRoom | undefined] => {
|
|
const predicate = createPredicateFromFilter(query);
|
|
let snapshot = Rooms.state.find(predicate);
|
|
|
|
const subscribe = (onStoreChange: () => void) =>
|
|
Rooms.use.subscribe(() => {
|
|
const newSnapshot = Rooms.state.find(predicate);
|
|
if (newSnapshot === snapshot) return;
|
|
snapshot = newSnapshot;
|
|
onStoreChange();
|
|
});
|
|
|
|
const getSnapshot = () => snapshot;
|
|
|
|
return [subscribe, getSnapshot];
|
|
};
|
|
|
|
const UserProvider = ({ children }: UserProviderProps) => {
|
|
const userId = userIdStore();
|
|
|
|
const user = Users.use((state) => {
|
|
if (!userId) return null;
|
|
return state.get(userId) ?? null;
|
|
});
|
|
|
|
const previousUserId = useRef(userId);
|
|
const [userLanguage, setUserLanguage] = useLocalStorage('userLanguage', '');
|
|
const [preferedLanguage, setPreferedLanguage] = useLocalStorage('preferedLanguage', '');
|
|
const [, setSamlInviteToken] = useSamlInviteToken();
|
|
const samlCredentialToken = useSearchParameter('saml_idp_credentialToken');
|
|
const inviteTokenHash = useRouteParameter('hash');
|
|
|
|
useEmailVerificationWarning(user ?? undefined);
|
|
useClearRemovedRoomsHistory(userId);
|
|
|
|
useDeleteUser();
|
|
useUpdateAvatar();
|
|
useIdleConnection(userId);
|
|
useReloadAfterLogin(user);
|
|
|
|
const querySubscriptions = useMemo(() => {
|
|
const createSubscriptionFactory =
|
|
<T extends SubscriptionWithRoom | IRoom>(store: UseBoundStore<StoreApi<IDocumentMapStore<T>>>) =>
|
|
(
|
|
query: object,
|
|
options: FindOptions = {},
|
|
): [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => SubscriptionWithRoom[]] => {
|
|
const predicate = createPredicateFromFilter<T>(query);
|
|
let snapshot = applyQueryOptions(store.getState().filter(predicate), options);
|
|
|
|
const subscribe = (onStoreChange: () => void) =>
|
|
store.subscribe(() => {
|
|
const newSnapshot = applyQueryOptions(store.getState().filter(predicate), options);
|
|
if (newSnapshot === snapshot) return;
|
|
snapshot = newSnapshot;
|
|
onStoreChange();
|
|
});
|
|
|
|
// TODO: this type assertion is completely wrong; however, the `useUserSubscriptions` hook might be deleted in
|
|
// the future, so we can live with it for now
|
|
const getSnapshot = () => snapshot as SubscriptionWithRoom[];
|
|
|
|
return [subscribe, getSnapshot];
|
|
};
|
|
|
|
return userId ? createSubscriptionFactory(Subscriptions.use) : createSubscriptionFactory(Rooms.use);
|
|
}, [userId]);
|
|
|
|
const querySubscription = useMemo(() => {
|
|
return (query: object): [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => SubscriptionWithRoom] => {
|
|
const predicate = createPredicateFromFilter<SubscriptionWithRoom>(query);
|
|
let snapshot = Subscriptions.use.getState().find(predicate);
|
|
|
|
const subscribe = (onStoreChange: () => void) =>
|
|
Subscriptions.use.subscribe(() => {
|
|
const newSnapshot = Subscriptions.use.getState().find(predicate);
|
|
if (newSnapshot === snapshot) return;
|
|
snapshot = newSnapshot;
|
|
onStoreChange();
|
|
});
|
|
|
|
// TODO: this type assertion is completely wrong; however, the `useUserSubscriptions` hook might be deleted in
|
|
// the future, so we can live with it for now
|
|
const getSnapshot = () => snapshot as SubscriptionWithRoom;
|
|
|
|
return [subscribe, getSnapshot];
|
|
};
|
|
}, []);
|
|
|
|
const contextValue = useMemo(
|
|
(): ContextType<typeof UserContext> => ({
|
|
userId,
|
|
user,
|
|
queryPreference: <T,>(
|
|
key: string | ObjectId,
|
|
defaultValue?: T,
|
|
): [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => T | undefined] => {
|
|
const effectiveKey = String(key);
|
|
|
|
const subscribe = (onStoreChange: () => void): (() => void) => {
|
|
const unsubUsers = Users.use.subscribe(onStoreChange);
|
|
const unsubSettings = settings.observe(`Accounts_Default_User_Preferences_${effectiveKey}`, onStoreChange);
|
|
return () => {
|
|
unsubUsers();
|
|
unsubSettings();
|
|
};
|
|
};
|
|
|
|
const getSnapshot = (): T | undefined => {
|
|
return (
|
|
(user?.settings?.preferences?.[effectiveKey] as T | undefined) ??
|
|
defaultValue ??
|
|
settings.peek(`Accounts_Default_User_Preferences_${effectiveKey}`)
|
|
);
|
|
};
|
|
return [subscribe, getSnapshot];
|
|
},
|
|
querySubscription,
|
|
queryRoom,
|
|
querySubscriptions,
|
|
logout: async () => Meteor.logout(),
|
|
onLogout: (cb) => {
|
|
return ee.on('logout', cb);
|
|
},
|
|
}),
|
|
[userId, user, querySubscription, querySubscriptions],
|
|
);
|
|
|
|
// Mirror local preference changes into the live userLanguage state without hitting the server.
|
|
useEffect(() => {
|
|
if (preferedLanguage === userLanguage) {
|
|
return;
|
|
}
|
|
|
|
setUserLanguage(preferedLanguage);
|
|
}, [preferedLanguage, setUserLanguage, userLanguage]);
|
|
|
|
// When the server reports a new language, overwrite both storage keys so every tab stays aligned.
|
|
useEffect(() => {
|
|
if (user?.language !== undefined && user.language !== userLanguage) {
|
|
setUserLanguage(user.language);
|
|
setPreferedLanguage(user.language);
|
|
}
|
|
}, [setPreferedLanguage, setUserLanguage, user?.language, userLanguage]);
|
|
|
|
useEffect(() => {
|
|
if (!samlCredentialToken && !inviteTokenHash) {
|
|
setSamlInviteToken(null);
|
|
}
|
|
}, [inviteTokenHash, samlCredentialToken, setSamlInviteToken]);
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
useEffect(() => {
|
|
if (previousUserId.current && previousUserId.current !== userId) {
|
|
queryClient.clear();
|
|
}
|
|
|
|
previousUserId.current = userId;
|
|
}, [queryClient, userId]);
|
|
|
|
return <UserContext.Provider value={contextValue}>{children}</UserContext.Provider>;
|
|
};
|
|
|
|
export default UserProvider;
|