Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
3.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {IS_DEV} from '@app/features/platform/types/Env';
import {isElectron} from '@app/features/ui/utils/ElectronRuntime';
import {makeAutoObservable} from 'mobx';

const IDLE_DURATION_MS = 1000 * (IS_DEV ? 10 : 60 * 10);
const IDLE_CHECK_INTERVAL_MS = Math.min(Math.floor(IDLE_DURATION_MS * 0.25), 30_000);
const SYSTEM_IDLE_RETRY_DELAY_MS = 60_000;

interface DesktopIdleApi {
	getSystemIdleTimeMs?: () => Promise<number>;
}

function getDesktopIdleApi(): Required<DesktopIdleApi> | null {
	if (!isElectron()) return null;
	const electronApi = (
		window as {
			electron?: DesktopIdleApi | null;
		}
	).electron;
	return typeof electronApi?.getSystemIdleTimeMs === 'function'
		? {getSystemIdleTimeMs: electronApi.getSystemIdleTimeMs.bind(electronApi)}
		: null;
}

function normalizeIdleTimeMs(value: number): number | null {
	if (!Number.isFinite(value) || value < 0) return null;
	return Math.floor(value);
}

class Idle {
	idle = false;
	afk = false;
	private afkThresholdMs = IDLE_DURATION_MS;
	private lastLocalActivityTime = Date.now();
	private lastSystemActivityTime = 0;
	private lastNonZeroSystemIdleTime = Date.now();
	private checkInterval: NodeJS.Timeout | null = null;
	private systemIdleCheckInFlight = false;
	private lastSystemIdleFailureAt = 0;

	constructor() {
		makeAutoObservable(this, {}, {autoBind: true});
		this.startIdleCheck();
	}

	private startIdleCheck(): void {
		if (typeof setInterval !== 'function') return;
		this.checkInterval = setInterval(() => {
			this.updateIdleState();
		}, IDLE_CHECK_INTERVAL_MS);
	}

	destroy(): void {
		if (this.checkInterval !== null) {
			clearInterval(this.checkInterval);
			this.checkInterval = null;
		}
	}

	recordActivity(): void {
		this.lastLocalActivityTime = Date.now();
		this.applyInactiveDuration(0);
	}

	isIdle(): boolean {
		return this.idle;
	}

	isAfk(): boolean {
		return this.afk;
	}

	setAfkTimeoutMs(afkThresholdMs: number): void {
		if (afkThresholdMs === this.afkThresholdMs) return;
		this.afkThresholdMs = afkThresholdMs;
		this.updateIdleStateFromLocalActivity();
	}

	getIdleSince(): number {
		return this.idle ? this.getLastActivityTime() : 0;
	}

	getInactiveDurationMs(now = Date.now()): number {
		return Math.max(0, now - this.getLastActivityTime());
	}

	private getLastActivityTime(): number {
		return Math.max(this.lastLocalActivityTime, this.lastSystemActivityTime);
	}

	private updateIdleState(): void {
		const desktopIdleApi = getDesktopIdleApi();
		if (
			desktopIdleApi &&
			!this.systemIdleCheckInFlight &&
			Date.now() - this.lastSystemIdleFailureAt >= SYSTEM_IDLE_RETRY_DELAY_MS
		) {
			void this.updateIdleStateFromSystem(desktopIdleApi);
			return;
		}
		this.updateIdleStateFromLocalActivity();
	}

	private updateIdleStateFromLocalActivity(): void {
		this.applyInactiveDuration(this.getInactiveDurationMs());
	}

	private async updateIdleStateFromSystem(desktopIdleApi: Required<DesktopIdleApi>): Promise<void> {
		this.systemIdleCheckInFlight = true;
		try {
			const idleTimeMs = normalizeIdleTimeMs(await desktopIdleApi.getSystemIdleTimeMs());
			const now = Date.now();
			if (idleTimeMs === null) {
				this.lastSystemIdleFailureAt = now;
			} else if (idleTimeMs > 0) {
				this.lastNonZeroSystemIdleTime = now;
				this.lastSystemActivityTime = Math.max(this.lastSystemActivityTime, now - idleTimeMs);
			} else if (now - this.lastNonZeroSystemIdleTime < Math.min(IDLE_DURATION_MS, this.afkThresholdMs)) {
				this.lastSystemActivityTime = now;
			}
		} catch {
			this.lastSystemIdleFailureAt = Date.now();
		} finally {
			this.systemIdleCheckInFlight = false;
		}
		this.updateIdleStateFromLocalActivity();
	}

	private applyInactiveDuration(inactiveDurationMs: number): void {
		this.idle = inactiveDurationMs >= IDLE_DURATION_MS;
		this.afk = inactiveDurationMs >= this.afkThresholdMs;
	}
}

export default new Idle();