element-call-Github/src/ClientContext.tsx

414 lines
11 KiB
TypeScript
Raw Normal View History

2022-01-06 09:19:03 +08:00
/*
Copyright 2021-2024 New Vector Ltd.
2022-01-06 09:19:03 +08:00
SPDX-License-Identifier: AGPL-3.0-only
Please see LICENSE in the repository root for full details.
2022-01-06 09:19:03 +08:00
*/
import {
FC,
2022-01-06 09:19:03 +08:00
useCallback,
useEffect,
useState,
createContext,
useContext,
useRef,
useMemo,
2022-01-06 09:19:03 +08:00
} from "react";
import { useHistory } from "react-router-dom";
import {
ClientEvent,
ICreateClientOpts,
MatrixClient,
} from "matrix-js-sdk/src/client";
2022-06-28 05:41:07 +08:00
import { logger } from "matrix-js-sdk/src/logger";
2022-10-10 21:19:10 +08:00
import { useTranslation } from "react-i18next";
import { ISyncStateData, SyncState } from "matrix-js-sdk/src/sync";
import { MatrixError } from "matrix-js-sdk/src/matrix";
import { ErrorView } from "./FullScreenView";
import { fallbackICEServerAllowed, initClient } from "./utils/matrix";
import { widget } from "./widget";
import {
PosthogAnalytics,
RegistrationType,
} from "./analytics/PosthogAnalytics";
2022-10-10 21:19:10 +08:00
import { translatedError } from "./TranslatedError";
import { useEventTarget } from "./useEvents";
2022-12-21 01:26:45 +08:00
import { Config } from "./config/Config";
2022-01-06 09:19:03 +08:00
declare global {
interface Window {
matrixclient: MatrixClient;
passwordlessUser: boolean;
}
}
export type ClientState = ValidClientState | ErrorState;
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;
setClient: (params?: SetClientParams) => void;
};
export type AuthenticatedClient = {
client: MatrixClient;
isPasswordlessUser: boolean;
changePassword: (password: string) => Promise<void>;
logout: () => void;
};
export type ErrorState = {
state: "error";
error: Error;
};
export type SetClientParams = {
client: MatrixClient;
session: Session;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
export const useClientState = (): ClientState | undefined =>
useContext(ClientContext);
export function useClient(): {
client?: MatrixClient;
setClient?: (params?: SetClientParams) => void;
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
}
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
setClient?: (params?: SetClientParams) => void;
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,
};
}
const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
2022-01-06 09:19:03 +08:00
2022-07-08 21:56:00 +08:00
interface Props {
children: JSX.Element;
}
export const ClientProvider: FC<Props> = ({ children }) => {
2022-01-06 09:19:03 +08:00
const history = useHistory();
// null = signed out, undefined = loading
const [initClientState, setInitClientState] = useState<
InitResult | null | undefined
>(undefined);
const initializing = useRef(false);
2022-01-06 09: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
// the client.
if (initializing.current) return;
initializing.current = true;
loadClient()
.then(setInitClientState)
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
2022-01-06 09:19:03 +08:00
}, []);
const changePassword = useCallback(
async (password: string) => {
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
2022-01-06 09:19:03 +08:00
await initClientState.client.setPassword(
2022-01-06 09:19:03 +08:00
{
type: "m.login.password",
identifier: {
type: "m.id.user",
user: session.user_id,
2022-01-06 09:19:03 +08:00
},
user: session.user_id,
password: session.tempPassword,
2022-01-06 09:19:03 +08:00
},
2023-10-11 22:42:04 +08:00
password,
2022-01-06 09:19:03 +08:00
);
saveSession({ ...session, passwordlessUser: false });
2022-01-06 09:19:03 +08:00
setInitClientState({
client: initClientState.client,
passwordlessUser: false,
2022-01-06 09:19:03 +08:00
});
},
2023-10-11 22:42:04 +08:00
[initClientState?.client],
2022-01-06 09:19:03 +08:00
);
2022-02-16 04:46:58 +08:00
const setClient = useCallback(
(clientParams?: SetClientParams) => {
const oldClient = initClientState?.client;
const newClient = clientParams?.client;
if (oldClient && oldClient !== newClient) {
oldClient.stopClient();
2022-02-16 04:46:58 +08:00
}
2022-01-06 09:19:03 +08:00
if (clientParams) {
saveSession(clientParams.session);
setInitClientState({
client: clientParams.client,
passwordlessUser: clientParams.session.passwordlessUser,
2022-02-16 04:46:58 +08:00
});
} else {
clearSession();
setInitClientState(null);
2022-02-16 04:46:58 +08:00
}
},
2023-10-11 22:42:04 +08:00
[initClientState?.client],
2022-02-16 04:46:58 +08:00
);
2022-01-06 09:19:03 +08:00
const logout = useCallback(async () => {
const client = initClientState?.client;
if (!client) {
return;
}
2022-10-14 09:25:15 +08:00
await client.logout(true);
2022-09-26 20:01:43 +08:00
await client.clearStores();
clearSession();
setInitClientState(null);
history.push("/");
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [history, initClientState?.client]);
2022-01-06 09:19:03 +08:00
2022-10-10 21:19:10 +08:00
const { t } = useTranslation();
// 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-29 05:15:47 +08:00
if (!widget) loadChannel?.postMessage({});
}, []);
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
2023-10-11 22:42:04 +08:00
undefined,
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
initClientState?.client.stopClient();
``` move "{{count, number}}_one" "participant_count_one" move "{{count, number}}_other" "participant_count_other" move "{{count}} stars_one" "star_rating_input_label_one" move "{{count}} stars_other" "star_rating_input_label_other" move "{{displayName}} is presenting" "video_tile.presenter_label" move "{{displayName}}, your call has ended." "call_ended_view.headline" move "<0></0><1></1>You may withdraw consent by unchecking this box. If you are currently in a call, this setting will take effect at the end of the call." "settings.opt_in_description" move "<0>Already have an account?</0><1><0>Log in</0> Or <2>Access as a guest</2></1>" "register_auth_links" move "<0>Create an account</0> Or <2>Access as a guest</2>" "login_auth_links" move "<0>Oops, something's gone wrong.</0>" "full_screen_view_h1" move "<0>Submitting debug logs will help us track down the problem.</0>" "full_screen_view_description" move "<0>Thanks for your feedback!</0>" "call_ended_view.feedback_done" move "<0>We'd love to hear your feedback so we can improve your experience.</0>" "call_ended_view.feedback_prompt" move "<0>Why not finish by setting up a password to keep your account?</0><1>You'll be able to keep your name and set an avatar for use on future calls</1>" "call_ended_view.create_account_prompt" move "Another user on this call is having an issue. In order to better diagnose these issues we'd like to collect a debug log." "rageshake_request_modal.body" move "Back to recents" "lobby.leave_button" move "By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our <2>Privacy Policy</2> and our <5>Cookie Policy</5>." "analytics_notice" move "Call not found" "group_call_loader_failed_heading" move "Calls are now end-to-end encrypted and need to be created from the home page. This helps make sure everyone's using the same encryption key." "group_call_loader_failed_text" move "Confirm password" "register_confirm_password_label" move "Connectivity to the server has been lost." "disconnected_banner" move "Continue in browser" "app_selection_modal.continue_in_browser" move "Create account" "call_ended_view.create_account_button" move "Debug log request" "rageshake_request_modal.title" move "Developer" "settings.developer_tab_title" move "Developer Settings" "settings.developer_settings_label" move "Element Call Home" "header_label" move "End call" "hangup_button_label" move "Full screen" "fullscreen_button_label" move "Exit full screen" "exit_fullscreen_button_label" move "Expose developer settings in the settings window." "settings.developer_settings_label_description" move "Feedback" "settings.feedback_tab_title" move "Grid" "layout_grid_label" move "Spotlight" "layout_spotlight_label" move "How did it go?" "call_ended_view.survey_prompt" move "If you are experiencing issues or simply would like to provide some feedback, please send us a short description below." "settings.feedback_tab_body" move "Include debug logs" "settings.feedback_tab_send_logs_label" move "Invite to this call" "invite_modal.title" move "Join call" "lobby.join_button" move "Join call now" "room_auth_view_join_button" move "Join existing call?" "join_existing_call_modal.title" move "Link copied to clipboard" "invite_modal.link_copied_toast" move "Local volume" "local_volume_label" move "Logging in…" "logging_in" move "Login" "login_title" move "Login to your account" "unauthenticated_view_login_button" move "Microphone off" "microphone_off" move "Microphone on" "microphone_on" move "More" "settings.more_tab_title" move "Mute microphone" "mute_microphone_button_label" move "Name of call" "call_name" move "Not now, return to home screen" "call_ended_view.not_now_button" move "Open in the app" "app_selection_modal.open_in_app" move "Not registered yet? <2>Create an account</2>" "unauthenticated_view_body" move "Participants" "header_participants_label" move "Passwords must match" "register.passwords_must_match" move "Ready to join?" "app_selection_modal.text" move "Recaptcha dismissed" "recaptcha_dismissed" move "Recaptcha not loaded" "recaptcha_not_loaded" move "Reconnect" "call_ended_view.reconnect_button" move "Registering…" "register.registering" move "Retry sending logs" "rageshake_button_error_caption" move "Return to home screen" "return_home_button" move "Select an option" "select_input_unset_button" move "Select app" "app_selection_modal.title" move "Send debug logs" "rageshake_send_logs" move "Sending debug logs…" "rageshake_sending_logs" move "Sending…" "rageshake_sending" move "Share screen" "screenshare_button_label" move "Sharing screen" "stop_screenshare_button_label" move "Show connection stats" "settings.show_connection_stats_label" move "Speaker" "settings.speaker_device_selection_label" move "Start new call" "start_new_call" move "Start video" "start_video_button_label" move "Stop video" "stop_video_button_label" move "Submit feedback" "settings.feedback_tab_h4" move "Submitting…" "submitting" move "Thanks, we received your feedback!" "settings.feedback_tab_thank_you" move "Thanks!" "rageshake_sent" move "This application has been opened in another tab." "application_opened_another_tab" move "This call already exists, would you like to join?" "join_existing_call_modal.text" move "Unmute microphone" "unmute_microphone_button_label" move "Version: {{version}}" "version" move "Waiting for other participants…" "waiting_for_participants" move "Yes, join call" "join_existing_call_modal.join_button" move "You" "video_tile.sfu_participant_local" move "You were disconnected from the call" "call_ended_view.body" move "Your feedback" "settings.feedback_tab_description_label" move "Your web browser does not support media end-to-end encryption. Supported Browsers are Chrome, Safari, Firefox >=117" "browser_media_e2ee_unsupported" move "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>" "unauthenticated_view_eula_caption" move "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>" "room_auth_view_eula_caption" move "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>" "register.recaptcha_caption" ```
2023-11-20 21:00:43 +08:00
setAlreadyOpenedErr(translatedError("application_opened_another_tab", t));
2023-10-11 22:42:04 +08:00
}, [initClientState?.client, setAlreadyOpenedErr, t]),
);
const [isDisconnected, setIsDisconnected] = useState(false);
const state: ClientState | undefined = useMemo(() => {
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
}
if (initClientState === undefined) return undefined;
const authenticated =
initClientState === null
? undefined
: {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
return {
state: "valid",
authenticated,
2022-01-06 09:19:03 +08:00
setClient,
disconnected: isDisconnected,
};
}, [
alreadyOpenedErr,
changePassword,
initClientState,
logout,
setClient,
isDisconnected,
]);
const onSync = useCallback(
(state: SyncState, _old: SyncState | null, data?: ISyncStateData) => {
setIsDisconnected(clientIsDisconnected(state, data));
},
2023-10-11 22:42:04 +08:00
[],
2022-01-06 09:19:03 +08:00
);
2022-02-16 04:46:58 +08:00
useEffect(() => {
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
2022-02-16 04:46:58 +08:00
if (initClientState.client) {
initClientState.client.on(ClientEvent.Sync, onSync);
}
2024-06-04 23:20:25 +08:00
return (): void => {
if (initClientState.client) {
initClientState.client.removeListener(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync]);
2022-02-16 04:46:58 +08:00
if (alreadyOpenedErr) {
return <ErrorView error={alreadyOpenedErr} />;
}
2022-01-06 09:19:03 +08:00
return (
<ClientContext.Provider value={state}>{children}</ClientContext.Provider>
2022-01-06 09:19:03 +08:00
);
};
2022-01-06 09:19:03 +08:00
type InitResult = {
client: MatrixClient;
passwordlessUser: boolean;
};
async function loadClient(): Promise<InitResult | null> {
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 {
client,
passwordlessUser: false,
};
} else {
// We're running as a standalone application
try {
const session = loadSession();
if (!session) {
logger.log("No session stored; continuing without a client");
return null;
}
logger.log("Using a standalone client");
/* eslint-disable camelcase */
const { user_id, device_id, access_token, passwordlessUser } = session;
const initClientParams: ICreateClientOpts = {
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
fallbackICEServerAllowed: fallbackICEServerAllowed,
livekitServiceURL: Config.get().livekit?.livekit_service_url,
};
try {
const client = await initClient(initClientParams, true);
return {
client,
passwordlessUser,
};
} catch (err) {
if (err instanceof MatrixError && err.errcode === "M_UNKNOWN_TOKEN") {
// We can't use this session anymore, so let's log it out
logger.log(
"The session from local store is invalid; continuing without a client",
);
clearSession();
// returning null = "no client` pls register" (undefined = "loading" which is the current value when reaching this line)
return null;
}
throw err;
}
} catch (err) {
clearSession();
throw err;
}
}
}
export interface Session {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
tempPassword?: string;
}
const clearSession = (): void => localStorage.removeItem("matrix-auth-store");
const saveSession = (s: Session): void =>
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 22:42:04 +08:00
syncData?: ISyncStateData,
): boolean =>
syncState === "ERROR" && syncData?.error?.name === "ConnectionError";