forked from Teamwork/node-afk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (93 loc) · 2.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
var exec = require('child_process').exec;
var execFile = require('child_process').execFile;
var os = require('os');
var path = require('path');
var listeners = [],
idle = {},
whenToCheck;
idle.tick = function (callback) {
callback = callback || function (){};
if (/^win/.test(process.platform)) {
var cmd = path.join( __dirname, 'bin', 'idle.exe');
execFile(cmd, function (error, stdout, stderr) {
if(error) {
callback(0, error);
return;
}
callback(Math.floor(parseInt(stdout, 10) / 1000), null)
});
}
else if (/darwin/.test(process.platform)) {
var cmd = '/usr/sbin/ioreg -c IOHIDSystem | /usr/bin/awk \'/HIDIdleTime/ {print int($NF/1000000000); exit}\'';
exec(cmd, function (error, stdout, stderr) {
if(error) {
callback(0, error);
return;
}
callback(parseInt(stdout, 10), null);
});
}
else if (/linux/.test(process.platform)) {
var cmd = 'xprintidle';
exec(cmd, function (error, stdout, stderr) {
if(error) {
callback(0, error);
return;
}
callback(Math.round(parseInt(stdout, 10) / 1000), null);
});
}
else {
callback(0);
}
}
idle.addListener = function (shouldSeconds, callback) {
var isAfk = false;
var listenerId = listeners.push(true) - 1;
var timeoutRef = null;
var checkIsAway = function () {
if(!listeners[listenerId]) {
clearTimeout(timeoutRef);
return;
}
idle.tick(function(isSeconds){
var whenSeconds = whenToCheck(isSeconds, shouldSeconds),
s = 1000;
if(whenSeconds === 0 && !isAfk) {
callback({
status: 'away',
seconds: isSeconds,
id: listenerId
});
isAfk = true;
timeoutRef = setTimeout(checkIsAway, s);
}
else if(isAfk && whenSeconds > 0) {
callback({
status: 'back',
seconds: isSeconds,
id: listenerId
});
isAfk = false;
timeoutRef = setTimeout(checkIsAway, whenSeconds * s);
}
else if (whenSeconds > 0 && !isAfk){
timeoutRef = setTimeout(checkIsAway, whenSeconds * s);
}
else {
timeoutRef = setTimeout(checkIsAway, s);
}
});
};
checkIsAway();
return listenerId;
};
idle.removeListener = function (listenerId) {
listeners[listenerId] = false;
return true;
};
whenToCheck = function (isSeconds, shouldSeconds) {
var whenSeconds = shouldSeconds - isSeconds;
return whenSeconds > 0 ? whenSeconds : 0;
}
module.exports = idle;