signal-desktop/ts/util/waitForOnline.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

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
import { clearTimeoutIfNecessary } from './clearTimeoutIfNecessary';
export type WaitForOnlineOptionsType = Readonly<{
server?: Readonly<{ isOnline: () => boolean | undefined }>;
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> {
return new Promise((resolve, reject) => {
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 = () => {
cleanup();
2021-04-08 16:24:21 +00:00
resolve();
};
const cleanup = () => {
events.off('online', listener);
clearTimeoutIfNecessary(timeoutId);
};
events.on('online', listener);
if (timeout !== undefined) {
2021-11-01 18:38:26 +00:00
timeoutId = setTimeout(() => {
cleanup();
reject(new Error('waitForOnline: did not come online in time'));
}, timeout);
}
2021-04-08 16:24:21 +00:00
});
}