diff --git a/src/preload/userPresence.js b/src/preload/userPresence.js index 447a207293..5ca1b85aad 100644 --- a/src/preload/userPresence.js +++ b/src/preload/userPresence.js @@ -2,64 +2,74 @@ import { ipcRenderer } from 'electron'; import { getMeteor, getTracker, getGetUserPreference, getUserPresence } from './rocketChat'; -let maximumIdleTime = 10 * 1000; -const idleDetectionInterval = 1 * 1000; +const pollUserPresence = (UserPresence, maximumIdleTime) => { + let wasUserPresent = false; + + return () => { + let isUserPresent = true; + + try { + const idleTime = ipcRenderer.sendSync('request-system-idle-time'); + isUserPresent = idleTime < maximumIdleTime; + + if (isUserPresent === wasUserPresent) { + return; + } + + if (isUserPresent) { + UserPresence.setOnline(); + } else { + UserPresence.setAway(); + } + } catch (error) { + console.error(error); + } finally { + wasUserPresent = isUserPresent; + } + }; +}; -function onChangeUserPresence(isUserPresent) { +const handleUserPresence = () => { + const Meteor = getMeteor(); + const Tracker = getTracker(); + const getUserPreference = getGetUserPreference(); const UserPresence = getUserPresence(); - if (!UserPresence) { + if (!Meteor || !Tracker || !getUserPreference || !UserPresence) { return; } - if (isUserPresent) { - UserPresence.setOnline(); - return; - } + let intervalID; - UserPresence.setAway(); -} - -let wasUserPresent = false; - -function pollUserPresence() { - let isUserPresent = false; + Tracker.autorun(() => { + if (intervalID) { + clearInterval(intervalID); + intervalID = null; + } - try { - const idleTime = ipcRenderer.sendSync('request-system-idle-time'); - isUserPresent = idleTime < maximumIdleTime; - } catch (error) { - console.error(error); - } + const uid = Meteor.userId(); - if (isUserPresent !== wasUserPresent) { - onChangeUserPresence(isUserPresent); - wasUserPresent = isUserPresent; - } -} + if (!uid) { + return; + } -function handleUserPresence() { - const Meteor = getMeteor(); - const Tracker = getTracker(); - const getUserPreference = getGetUserPreference(); + delete UserPresence.awayTime; + UserPresence.start(); - if (!Meteor || !Tracker || !getUserPreference) { - return; - } + const isAutoAwayEnabled = getUserPreference(uid, 'enableAutoAway'); - Tracker.autorun(() => { - if (!Meteor.userId()) { + if (!isAutoAwayEnabled) { + UserPresence.setOnline(); return; } - const userId = Meteor.userId(); - if (getUserPreference(userId, 'enableAutoAway')) { - maximumIdleTime = (getUserPreference(userId, 'idleTimeLimit') || 300) * 1000; - } - }); + const maximumIdleTime = (getUserPreference(uid, 'idleTimeLimit') || 300) * 1000; + const idleTimeDetectionInterval = maximumIdleTime / 2; + const callback = pollUserPresence(UserPresence, maximumIdleTime); - setInterval(pollUserPresence, idleDetectionInterval); -} + intervalID = setInterval(callback, idleTimeDetectionInterval); + }); +}; export default () => {