2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
2021-04-08 16:24:21 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2022-02-25 18:37:15 +00:00
|
|
|
import { clearTimeoutIfNecessary } from './clearTimeoutIfNecessary';
|
|
|
|
|
2024-03-18 21:48:00 +00:00
|
|
|
export type WaitForOnlineOptionsType = Readonly<{
|
2024-04-02 20:43:20 +00:00
|
|
|
server?: Readonly<{ isOnline: () => boolean | undefined }>;
|
2024-03-18 21:48:00 +00:00
|
|
|
events?: {
|
|
|
|
on: (event: 'online', fn: () => void) => void;
|
|
|
|
off: (event: 'online', fn: () => void) => void;
|
|
|
|
};
|
|
|
|
timeout?: number;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
export function waitForOnline({
|
|
|
|
server: maybeServer,
|
|
|
|
events = window.Whisper.events,
|
|
|
|
timeout,
|
|
|
|
}: WaitForOnlineOptionsType = {}): Promise<void> {
|
2021-07-23 22:02:36 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2024-03-18 21:48:00 +00:00
|
|
|
let server = maybeServer;
|
|
|
|
if (server === undefined) {
|
|
|
|
({ server } = window.textsecure);
|
|
|
|
if (!server) {
|
|
|
|
reject(new Error('waitForOnline: no textsecure server'));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (server.isOnline()) {
|
2021-04-08 16:24:21 +00:00
|
|
|
resolve();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-11-01 18:38:26 +00:00
|
|
|
let timeoutId: undefined | ReturnType<typeof setTimeout>;
|
|
|
|
|
2021-04-08 16:24:21 +00:00
|
|
|
const listener = () => {
|
2021-07-23 22:02:36 +00:00
|
|
|
cleanup();
|
2021-04-08 16:24:21 +00:00
|
|
|
resolve();
|
|
|
|
};
|
|
|
|
|
2021-07-23 22:02:36 +00:00
|
|
|
const cleanup = () => {
|
2024-03-18 21:48:00 +00:00
|
|
|
events.off('online', listener);
|
2022-02-25 18:37:15 +00:00
|
|
|
clearTimeoutIfNecessary(timeoutId);
|
2021-07-23 22:02:36 +00:00
|
|
|
};
|
|
|
|
|
2024-03-18 21:48:00 +00:00
|
|
|
events.on('online', listener);
|
2021-07-23 22:02:36 +00:00
|
|
|
|
|
|
|
if (timeout !== undefined) {
|
2021-11-01 18:38:26 +00:00
|
|
|
timeoutId = setTimeout(() => {
|
2021-07-23 22:02:36 +00:00
|
|
|
cleanup();
|
|
|
|
reject(new Error('waitForOnline: did not come online in time'));
|
|
|
|
}, timeout);
|
|
|
|
}
|
2021-04-08 16:24:21 +00:00
|
|
|
});
|
|
|
|
}
|