bitwarden-estensione-browser/src/background/idle.background.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

72 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-12-21 20:48:22 +01:00
import { NotificationsService } from "jslib-common/abstractions/notifications.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { StateService } from "../services/abstractions/state.service";
2021-09-17 15:44:27 +02:00
2018-08-23 03:10:23 +02:00
const IdleInterval = 60 * 5; // 5 minutes
export default class IdleBackground {
2021-12-21 20:48:22 +01:00
private idle: any;
private idleTimer: number = null;
private idleState = "active";
2021-12-21 20:48:22 +01:00
constructor(
private vaultTimeoutService: VaultTimeoutService,
private stateService: StateService,
private notificationsService: NotificationsService
) {
this.idle = chrome.idle || (browser != null ? browser.idle : null);
}
async init() {
if (!this.idle) {
return;
}
2021-12-21 20:48:22 +01:00
const idleHandler = (newState: string) => {
if (newState === "active") {
this.notificationsService.reconnectFromActivity();
} else {
this.notificationsService.disconnectFromInactivity();
}
};
if (this.idle.onStateChanged && this.idle.setDetectionInterval) {
this.idle.setDetectionInterval(IdleInterval);
this.idle.onStateChanged.addListener(idleHandler);
} else {
this.pollIdle(idleHandler);
}
2021-12-21 20:48:22 +01:00
if (this.idle.onStateChanged) {
this.idle.onStateChanged.addListener(async (newState: string) => {
if (newState === "locked") {
// If the screen is locked or the screensaver activates
const timeout = await this.stateService.getVaultTimeout();
if (timeout === -2) {
// On System Lock vault timeout option
const action = await this.stateService.getVaultTimeoutAction();
if (action === "logOut") {
await this.vaultTimeoutService.logOut();
2018-08-23 03:10:23 +02:00
} else {
2021-12-21 20:48:22 +01:00
await this.vaultTimeoutService.lock(true);
2018-08-23 03:10:23 +02:00
}
2021-12-21 20:48:22 +01:00
}
}
2021-12-21 20:48:22 +01:00
});
}
2021-12-21 20:48:22 +01:00
}
2018-08-23 03:10:23 +02:00
2021-12-21 20:48:22 +01:00
private pollIdle(handler: (newState: string) => void) {
if (this.idleTimer != null) {
window.clearTimeout(this.idleTimer);
this.idleTimer = null;
2018-08-23 03:10:23 +02:00
}
2021-12-21 20:48:22 +01:00
this.idle.queryState(IdleInterval, (state: string) => {
if (state !== this.idleState) {
this.idleState = state;
handler(state);
}
this.idleTimer = window.setTimeout(() => this.pollIdle(handler), 5000);
});
}
}