2018-08-23 03:10:23 +02:00
|
|
|
import { ConstantsService } from 'jslib/services/constants.service';
|
2018-01-10 04:22:49 +01:00
|
|
|
|
2018-01-10 05:18:55 +01:00
|
|
|
import {
|
|
|
|
LockService,
|
|
|
|
StorageService,
|
|
|
|
} from 'jslib/abstractions';
|
2018-08-23 03:10:23 +02:00
|
|
|
import { NotificationsService } from 'jslib/abstractions/notifications.service';
|
|
|
|
|
|
|
|
const IdleInterval = 60 * 5; // 5 minutes
|
2018-01-04 23:04:26 +01:00
|
|
|
|
|
|
|
export default class IdleBackground {
|
|
|
|
private idle: any;
|
2018-08-23 03:10:23 +02:00
|
|
|
private idleTimer: number = null;
|
|
|
|
private idleState = 'active';
|
2018-01-04 23:04:26 +01:00
|
|
|
|
2018-08-23 03:10:23 +02:00
|
|
|
constructor(private lockService: LockService, private storageService: StorageService,
|
|
|
|
private notificationsService: NotificationsService) {
|
2019-06-29 05:33:53 +02:00
|
|
|
this.idle = chrome.idle || (browser != null ? browser.idle : null);
|
2018-01-04 23:04:26 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async init() {
|
|
|
|
if (!this.idle) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-08-23 03:10:23 +02: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);
|
|
|
|
}
|
|
|
|
|
2018-01-04 23:04:26 +01:00
|
|
|
if (this.idle.onStateChanged) {
|
|
|
|
this.idle.onStateChanged.addListener(async (newState: string) => {
|
|
|
|
if (newState === 'locked') {
|
|
|
|
const lockOption = await this.storageService.get<number>(ConstantsService.lockOptionKey);
|
|
|
|
if (lockOption === -2) {
|
2019-02-14 06:46:28 +01:00
|
|
|
this.lockService.lock(true);
|
2018-01-04 23:04:26 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2018-08-23 03:10:23 +02:00
|
|
|
|
|
|
|
private pollIdle(handler: (newState: string) => void) {
|
|
|
|
if (this.idleTimer != null) {
|
|
|
|
window.clearTimeout(this.idleTimer);
|
|
|
|
this.idleTimer = null;
|
|
|
|
}
|
|
|
|
this.idle.queryState(IdleInterval, (state: string) => {
|
|
|
|
if (state !== this.idleState) {
|
|
|
|
this.idleState = state;
|
|
|
|
handler(state);
|
|
|
|
}
|
|
|
|
this.idleTimer = window.setTimeout(() => this.pollIdle(handler), 5000);
|
|
|
|
});
|
|
|
|
}
|
2018-01-04 23:04:26 +01:00
|
|
|
}
|