Files
element-call/src/ClientContext.tsx
T

395 lines
10 KiB
TypeScript
Raw Normal View History

2022-01-05 17:19:03 -08:00
/*
Copyright 2021-2024 New Vector Ltd.
2022-01-05 17:19:03 -08:00
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
2022-01-05 17:19:03 -08:00
*/
import {
type FC,
2022-01-05 17:19:03 -08:00
useCallback,
useEffect,
useState,
createContext,
2025-06-24 04:48:35 -04:00
use,
useRef,
useMemo,
type JSX,
2022-01-05 17:19:03 -08:00
} from "react";
2025-01-06 18:00:20 +01:00
import { useNavigate } from "react-router-dom";
2025-03-13 13:58:43 +01:00
import { logger } from "matrix-js-sdk/lib/logger";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
2022-05-27 16:08:03 -04:00
2025-03-13 18:15:58 +01:00
import type { WidgetApi } from "matrix-widget-api";
import { ErrorPage } from "./FullScreenView";
import { widget } from "./widget";
import {
PosthogAnalytics,
RegistrationType,
} from "./analytics/PosthogAnalytics";
import { useEventTarget } from "./useEvents";
import { OpenElsewhereError } from "./RichError";
2022-01-05 17:19:03 -08:00
2022-05-27 16:08:03 -04:00
declare global {
interface Window {
matrixclient: MatrixClient;
2023-06-30 16:43:28 +01:00
passwordlessUser: boolean;
2022-05-27 16:08:03 -04:00
}
}
2023-06-30 16:43:28 +01:00
export type ClientState = ValidClientState | ErrorState;
2023-06-30 16:43:28 +01:00
export type ValidClientState = {
state: "valid";
authenticated?: AuthenticatedClient;
// 'Disconnected' rather than 'connected' because it tracks specifically
// whether the client is supposed to be connected but is not
disconnected: boolean;
2024-11-04 08:54:13 -01:00
supportedFeatures: {
reactions: boolean;
};
2025-03-05 08:52:31 -05:00
setClient: (client: MatrixClient, session: Session) => void;
2022-05-27 16:08:03 -04:00
};
2023-06-30 16:43:28 +01:00
export type AuthenticatedClient = {
2022-05-27 16:08:03 -04:00
client: MatrixClient;
2023-06-30 16:43:28 +01:00
isPasswordlessUser: boolean;
2022-05-27 16:08:03 -04:00
changePassword: (password: string) => Promise<void>;
logout: () => void;
2023-06-30 16:43:28 +01:00
};
export type ErrorState = {
state: "error";
error: Error;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
export const ClientContextProvider = ClientContext.Provider;
2025-06-24 04:48:35 -04:00
export const useClientState = (): ClientState | undefined => use(ClientContext);
2023-06-30 16:43:28 +01:00
export function useClient(): {
client?: MatrixClient;
2025-03-05 08:52:31 -05:00
setClient?: (client: MatrixClient, session: Session) => void;
2023-06-30 16:43:28 +01:00
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
2022-05-27 16:08:03 -04:00
}
2023-06-30 16:43:28 +01:00
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
2025-03-05 08:52:31 -05:00
setClient?: (client: MatrixClient, session: Session) => void;
2023-06-30 16:43:28 +01:00
passwordlessUser: boolean;
loading: boolean;
authenticated: boolean;
logout?: () => void;
error?: Error;
} {
const clientState = useClientState();
let client;
let setClient;
let passwordlessUser = false;
let loading = true;
let error;
let authenticated = false;
let logout;
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false;
loading = false;
authenticated = client !== undefined;
logout = clientState.authenticated?.logout;
} else if (clientState?.state === "error") {
error = clientState.error;
loading = false;
}
return {
client,
setClient,
passwordlessUser,
loading,
authenticated,
logout,
error,
};
}
2022-05-27 16:08:03 -04:00
2023-06-30 16:43:28 +01:00
const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
2022-01-05 17:19:03 -08:00
2022-07-08 14:56:00 +01:00
interface Props {
children: JSX.Element;
}
export const ClientProvider: FC<Props> = ({ children }) => {
2025-01-06 18:00:20 +01:00
const navigate = useNavigate();
2022-01-05 17:19:03 -08:00
2023-07-21 15:08:53 -04:00
// null = signed out, undefined = loading
2023-06-30 16:43:28 +01:00
const [initClientState, setInitClientState] = useState<
2023-07-21 15:08:53 -04:00
InitResult | null | undefined
2023-06-30 16:43:28 +01:00
>(undefined);
const initializing = useRef(false);
2022-01-05 17:19:03 -08:00
useEffect(() => {
// In case the component is mounted, unmounted, and remounted quickly (as
// React does in strict mode), we need to make sure not to doubly initialize
2023-06-30 16:43:28 +01:00
// the client.
if (initializing.current) return;
initializing.current = true;
2023-06-30 16:43:28 +01:00
loadClient()
2025-03-05 08:52:31 -05:00
.then((initResult) => {
setInitClientState(initResult);
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
})
2023-06-30 16:43:28 +01:00
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
2022-01-05 17:19:03 -08:00
}, []);
const changePassword = useCallback(
2022-05-27 16:08:03 -04:00
async (password: string) => {
2023-06-30 16:43:28 +01:00
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
2022-01-05 17:19:03 -08:00
2023-06-30 16:43:28 +01:00
await initClientState.client.setPassword(
2022-01-05 17:19:03 -08:00
{
type: "m.login.password",
identifier: {
type: "m.id.user",
2022-05-27 16:08:03 -04:00
user: session.user_id,
2022-01-05 17:19:03 -08:00
},
2022-05-27 16:08:03 -04:00
user: session.user_id,
2023-06-30 16:43:28 +01:00
password: session.tempPassword,
2022-01-05 17:19:03 -08:00
},
2023-10-11 10:42:04 -04:00
password,
2022-01-05 17:19:03 -08:00
);
2022-05-27 16:08:03 -04:00
saveSession({ ...session, passwordlessUser: false });
2022-01-05 17:19:03 -08:00
2023-06-30 16:43:28 +01:00
setInitClientState({
2024-11-04 08:54:13 -01:00
...initClientState,
2023-06-30 16:43:28 +01:00
passwordlessUser: false,
2022-01-05 17:19:03 -08:00
});
},
2024-11-04 08:54:13 -01:00
[initClientState],
2022-01-05 17:19:03 -08:00
);
2022-02-15 12:46:58 -08:00
const setClient = useCallback(
2025-03-05 08:52:31 -05:00
(client: MatrixClient, session: Session) => {
2023-06-30 16:43:28 +01:00
const oldClient = initClientState?.client;
2025-03-05 08:52:31 -05:00
if (oldClient && oldClient !== client) {
2023-06-30 16:43:28 +01:00
oldClient.stopClient();
2022-02-15 12:46:58 -08:00
}
2022-01-05 17:19:03 -08:00
2025-03-05 08:52:31 -05:00
saveSession(session);
setInitClientState({
widgetApi: null,
client,
passwordlessUser: session.passwordlessUser,
});
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
2022-02-15 12:46:58 -08:00
},
2023-10-11 10:42:04 -04:00
[initClientState?.client],
2022-02-15 12:46:58 -08:00
);
2022-01-05 17:19:03 -08:00
2022-09-13 16:48:04 +02:00
const logout = useCallback(async () => {
2023-06-30 16:43:28 +01:00
const client = initClientState?.client;
if (!client) {
return;
}
2022-10-13 21:25:15 -04:00
await client.logout(true);
2022-09-26 13:01:43 +01:00
await client.clearStores();
2022-05-27 16:08:03 -04:00
clearSession();
setInitClientState(null);
await navigate("/");
2025-03-05 08:52:31 -05:00
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
2025-01-06 18:00:20 +01:00
}, [navigate, initClientState?.client]);
2022-01-05 17:19:03 -08:00
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. This isn't necessary if the app is running in
// a widget though, since then it'll be mostly stateless.
useEffect(() => {
2022-11-28 16:15:47 -05:00
if (!widget) loadChannel?.postMessage({});
}, []);
2023-06-30 16:43:28 +01:00
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
2023-10-11 10:42:04 -04:00
undefined,
2023-06-30 16:43:28 +01:00
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
2023-06-30 16:43:28 +01:00
initClientState?.client.stopClient();
setAlreadyOpenedErr(new OpenElsewhereError());
}, [initClientState?.client, setAlreadyOpenedErr]),
);
const [isDisconnected, setIsDisconnected] = useState(false);
2024-11-04 08:54:13 -01:00
const [supportsReactions, setSupportsReactions] = useState(false);
2023-07-21 15:08:53 -04:00
const state: ClientState | undefined = useMemo(() => {
2023-06-30 16:43:28 +01:00
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
2023-06-30 16:43:28 +01:00
}
2023-07-21 15:08:53 -04:00
if (initClientState === undefined) return undefined;
const authenticated =
initClientState === null
? undefined
: {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
2023-06-30 16:43:28 +01:00
return {
state: "valid",
authenticated,
2022-01-05 17:19:03 -08:00
setClient,
disconnected: isDisconnected,
2024-11-04 08:54:13 -01:00
supportedFeatures: {
reactions: supportsReactions,
},
};
}, [
alreadyOpenedErr,
changePassword,
initClientState,
logout,
setClient,
isDisconnected,
2024-11-04 08:54:13 -01:00
supportsReactions,
]);
const onSync = useCallback(
(state: SyncState, _old: SyncState | null, data?: ISyncStateData) => {
setIsDisconnected(clientIsDisconnected(state, data));
},
2023-10-11 10:42:04 -04:00
[],
2022-01-05 17:19:03 -08:00
);
2022-02-15 12:46:58 -08:00
useEffect(() => {
2023-06-30 16:43:28 +01:00
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
2023-04-05 13:06:55 +01:00
2023-04-05 15:00:14 +01:00
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
2022-02-15 12:46:58 -08:00
if (initClientState.client) {
initClientState.client.on(ClientEvent.Sync, onSync);
}
2024-11-04 08:54:13 -01:00
if (initClientState.widgetApi) {
const reactSend = initClientState.widgetApi.hasCapability(
"org.matrix.msc2762.send.event:m.reaction",
);
const redactSend = initClientState.widgetApi.hasCapability(
"org.matrix.msc2762.send.event:m.room.redaction",
);
const reactRcv = initClientState.widgetApi.hasCapability(
"org.matrix.msc2762.receive.event:m.reaction",
);
const redactRcv = initClientState.widgetApi.hasCapability(
"org.matrix.msc2762.receive.event:m.room.redaction",
);
if (!reactSend || !reactRcv || !redactSend || !redactRcv) {
logger.warn("Widget does not support reactions");
setSupportsReactions(false);
} else {
setSupportsReactions(true);
}
} else {
setSupportsReactions(true);
}
2024-06-04 11:20:25 -04:00
return (): void => {
if (initClientState.client) {
initClientState.client.removeListener(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync]);
2022-02-15 12:46:58 -08:00
2023-06-30 16:43:28 +01:00
if (alreadyOpenedErr) {
return <ErrorPage widget={widget} error={alreadyOpenedErr} />;
}
2025-06-24 04:48:35 -04:00
return <ClientContext value={state}>{children}</ClientContext>;
2022-05-27 16:08:03 -04:00
};
2022-01-05 17:19:03 -08:00
export type InitResult = {
2024-11-04 08:54:13 -01:00
widgetApi: WidgetApi | null;
2023-06-30 16:43:28 +01:00
client: MatrixClient;
passwordlessUser: boolean;
};
2023-07-21 15:08:53 -04:00
async function loadClient(): Promise<InitResult | null> {
2023-06-30 16:43:28 +01:00
if (widget) {
// We're inside a widget, so let's engage *matryoshka mode*
logger.log("Using a matryoshka client");
const client = await widget.client;
return {
2024-11-04 08:54:13 -01:00
widgetApi: widget.api,
2023-06-30 16:43:28 +01:00
client,
passwordlessUser: false,
};
} else {
const { initSPA } = await import("./utils/spa");
return initSPA(loadSession, clearSession);
2023-06-30 16:43:28 +01:00
}
}
export interface Session {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
tempPassword?: string;
}
2023-09-22 18:05:13 -04:00
const clearSession = (): void => localStorage.removeItem("matrix-auth-store");
const saveSession = (s: Session): void =>
2023-06-30 16:43:28 +01:00
localStorage.setItem("matrix-auth-store", JSON.stringify(s));
const loadSession = (): Session | undefined => {
const data = localStorage.getItem("matrix-auth-store");
if (!data) {
return undefined;
}
return JSON.parse(data);
};
const clientIsDisconnected = (
syncState: SyncState,
2023-10-11 10:42:04 -04:00
syncData?: ISyncStateData,
2023-09-22 18:05:13 -04:00
): boolean =>
syncState === "ERROR" && syncData?.error?.name === "ConnectionError";