SymphonyElectron/js/activityDetection/activityDetection.js
Kiran Niranjan 4087eb3acc Electron 32 (Activity Detection) (#71)
* Implemented user activity detection

* ELECTRON-32: Implemented throttle function

* ELECTRON-32: Fixed some bugs in throttle function

* ELECTRON-32: Updated comments

* ELECTRON-32: Fixed clear interval bug

* ELECTRON-32: Updated as per the review

* ELECTRON-32: Updated return statement

* ELECTRON-32: Added a boolean to the callback function

* ELECTRON-32: Resolved conflicts

* ELECTRON-32 - Added period attribute
2017-05-08 11:30:45 -07:00

94 lines
2.3 KiB
JavaScript

'use strict';
const systemIdleTime = require('@paulcbetts/system-idle-time');
const throttle = require('../utils/throttle');
let maxIdleTime;
let activityWindow;
let intervalId;
let throttleActivity;
/**
* Check if the user is idle
*/
function activityDetection() {
// Get system idle status and idle time from PaulCBetts package
if (systemIdleTime.getIdleTime() < maxIdleTime) {
return {isUserIdle: false, systemIdleTime: systemIdleTime.getIdleTime()};
}
// If idle for more than 4 mins, monitor system idle status every second
if (!intervalId) {
monitorUserActivity();
}
return null;
}
/**
* Start monitoring user activity status.
* Run every 4 mins to check user idle status
*/
function initiateActivityDetection() {
if (!throttleActivity) {
throttleActivity = throttle(maxIdleTime, sendActivity);
setInterval(throttleActivity, maxIdleTime);
}
sendActivity();
}
/**
* Monitor system idle status every second
*/
function monitorUserActivity() {
intervalId = setInterval(monitor, 1000);
function monitor() {
if (systemIdleTime.getIdleTime() < maxIdleTime) {
// If system is active, send an update to the app bridge and clear the timer
sendActivity();
clearInterval(intervalId);
intervalId = undefined;
}
}
}
/**
* Send user activity status to the app bridge
* to be updated across all clients
*/
function sendActivity() {
let systemActivity = activityDetection();
if (systemActivity && !systemActivity.isUserIdle && systemActivity.systemIdleTime) {
send({systemIdleTime: systemActivity.systemIdleTime});
}
}
/**
* Sends user activity status from main process to activity detection hosted by
* renderer process. Allows main process to use activity detection
* provided by JS.
* @param {object} data - data as object
*/
function send(data) {
if (activityWindow && data) {
activityWindow.send('activity', {
systemIdleTime: data.systemIdleTime
});
}
}
function setActivityWindow(period, win) {
maxIdleTime = period;
activityWindow = win;
}
module.exports = {
send: send,
setActivityWindow: setActivityWindow,
initiateActivityDetection: initiateActivityDetection
};