-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzeitgeist.js
312 lines (256 loc) · 9.85 KB
/
zeitgeist.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/* Original Zeitgeist plugin under GNU GPLv3 (c) Zeitgeist project, 2012
* Original native messaging API under Chromium's BSD-style license (c) Chromium authors, 2013
* Additions under GNU GPLv3 (c) Steve Dodier-Lazaro for UCL Computer Science, 2015
*/
var host = null;
var tabInfo = {};
var tabIdTimeouts = {};
/* STORAGE FOR LAST STEP'S ACTIVE WINDOWS */
var _latestActiveTabs = {}; // Array of tabs that were active for long enough at the last event logging call (key: XID, data: active duration in secs)
var _currentActiveTab = null; // Pointer to the window that last sent a 'focus' signal
var _activeTimeStart = 0; // Timestamp of when that window was last active
/* STORAGE FOR LAST STEP'S ACTIVE WORKSPACES */
var _latestActiveWorkspaces; // List of workspaces that were active in the
var _currentActiveWorkspace = null; // Pointer to the window that last sent a 'focus' signal
var _activeWsTimeStart = 0; // Timestamp of when that window was last active
var intervalWorker;
/* UTILITIES */
function startsWith(str, prefix) {
return str && str.indexOf(prefix, 0) === 0;
}
function getCurrentTabId () {
// if (typeof _currentActiveTab !== 'undefined')
if (_currentActiveTab !== null)
return _currentActiveTab.id;
else
return -1;
}
function hasFocus(callback) {
chrome.windows.getLastFocused ({}, function (current) {
if (typeof current !== 'undefined')
callback(current.focused);
else
callback(false);
});
}
function pollForFocusLoss() {
hasFocus(function (focused) {
if (!focused) {
onCurrentTabChanged(null);
// console.error ("LOST FOCUS! LOST FOCUS! PANIC!");
//} else {
// console.log ("We currently have the focus");
}
});
window.setTimeout(pollForFocusLoss, 500);
}
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
function onCurrentTabChanged (tab) {
if (typeof tab !== 'undefined') {
var currentTime = Date.now();
var duration = (currentTime - _activeTimeStart) / 1000;
if (_currentActiveTab !== null) {
// The previously active tab has stayed long enough to be registered as active
if (_currentActiveTab.id in _latestActiveTabs)
_latestActiveTabs[_currentActiveTab.url] += duration;
else
_latestActiveTabs[_currentActiveTab.url] = duration;
}
if (_currentActiveTab || tab)
//console.log("Activated %d in %d, previous tab %d stayed %f seconds",
// tab? tab.id : -1,
// tab? tab.windowId : -1,
// getCurrentTabId(),
// _currentActiveTab ? duration : 0.0);
_currentActiveTab = tab;
_activeTimeStart = currentTime;
}
}
function onTabActivated (tabId) {
chrome.windows.getLastFocused ({}, function (current) {
if (typeof current !== 'undefined') {
chrome.tabs.get (tabId, function (tab) {
if (typeof tab !== 'undefined') {
if (current.id === tab.windowId) {
onCurrentTabChanged (tab);
}
} else
onCurrentTabChanged (null);
});
} else
onCurrentTabChanged (null);
});
}
function onTabActivatedListener (activeInfo) {
onTabActivated (activeInfo.tabId);
}
function onWindowsFocusChanged (windowId) {
chrome.windows.get (windowId, {populate: true}, function (current) {
var foundActive = false;
if (typeof chrome.runtime.lastError == 'undefined' && typeof current !== 'undefined') {
current.tabs.forEach (function (tab) {
if (tab.active) {
onCurrentTabChanged (tab);
foundActive = true;
}
});
}
if (!foundActive)
onCurrentTabChanged (null);
});
}
function initActiveTab () {
chrome.windows.getLastFocused ({populate: true}, function (current) {
if (typeof chrome.runtime.lastError !== 'undefined') return;
if (typeof current !== 'undefined') {
current.tabs.forEach (function (tab) {
if (tab.active) {
_currentActiveTab = tab;
_activeTimeStart = Date.now();
}
});
}
});
}
function getLatestActiveTabs() {
// Hack: register current window if it's been here for long enough
onCurrentTabChanged(_currentActiveTab);
var latest = _latestActiveTabs;
_latestActiveTabs = {};
return latest;
}
function intervalRun() {
var currentActive = getLatestActiveTabs();
if (!isEmpty(currentActive))
sendActiveEvent(currentActive);
// To stop, call: worker.postMessage ({type: "Stop"});
}
/* ZEITGEIST EVENT HANDLING */
function sendAccessEvent (documentInfo, tab) {
chrome.processes.getProcessIdForTab(tab.id, function (pid) {
documentInfo.sentAccess = true;
documentInfo.pid = pid;
documentInfo.windowId = tab.windowId;
documentInfo.index = tab.index;
documentInfo.id = tab.id;
tabInfo[tab.id] = documentInfo;
console.log ("Sending an access event for tab %d, %s, %O", tab.id, tab.url, tab);
sendNativeMessage({type: "Access", documentInfo: documentInfo});
});
}
function sendLeaveEvent (tabid) {
var documentInfo = tabInfo[tabid];
if (documentInfo == null || documentInfo.sentAccess != true) return;
console.log ("Sending a leave event for tab %d", tabid);
sendNativeMessage({type: "Leave", tabid: tabid, documentInfo: documentInfo});
tabInfo[tabid] = null;
}
function sendActiveEvent (activeEventInfo) {
console.log ("Sending an active tabs event, %O", activeEventInfo);
sendNativeMessage({type: "ActiveTabs", info: activeEventInfo});
}
function sendDownloadEvent (downloadItem) {
console.log ("Sending a download event, %O", downloadItem);
sendNativeMessage({type: "Download", item: downloadItem});
}
/* LISTENERS */
function onTabCreated (tab) {
if (startsWith (tab.url, "chrome://")) return;
//console.log ("Tab created: %d, %O", tab.id, tab);
chrome.tabs.executeScript(tab.id, {file: "content_script.js"}, function(result) {
if (chrome.runtime.lastError)
console.error ("Could not inject content in tab, %O", chrome.runtime.lastError);
});
}
function onTabRemoved (tabid) {
//console.log ("Tab removed: %d", tabid);
sendLeaveEvent(tabid);
}
function onTabUpdated (tabid, changeInfo, tab) {
if (startsWith (changeInfo.url, "chrome://")) return;
//console.log ("Tab updated: %d, %O, %O", tabid, changeInfo, tab);
if (!changeInfo.url) return;
onCurrentTabChanged(tab);
window.clearTimeout(tabIdTimeouts[tabid])
tabIdTimeouts[tabid] = window.setTimeout(function(){
chrome.tabs.executeScript(tabid, {file: "content_script.js"}, function(result) {
if (chrome.runtime.lastError)
console.error ("Could not inject content in tab, %O", chrome.runtime.lastError);
});
},
5000);
}
function onDownloadChanged (downloadDelta) {
//console.log ("File downloaded: %s", downloadItem.url);
if (downloadDelta.state && downloadDelta.state.current == "complete") {
chrome.downloads.search({id: downloadDelta.id}, function (results) {
if (results.length > 0) {
sendDownloadEvent(results[0]);
}
});
}
}
/* NATIVE MESSAGE API */
var port = null;
function sendNativeMessage(message) {
port.postMessage(message);
console.log("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
console.log("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
console.log("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
}
function nativeConnect() {
var hostName = "uk.ac.ucl.cs.study.multitasking.chrome";
console.log("Connecting to native messaging host <b>" + hostName + "</b>");
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
}
/* EXTENSION SETUP */
function onExtensionRequest (request, sender, sendResponse) {
var id = sender.tab.id;
sendLeaveEvent(id);
sendAccessEvent(request, sender.tab);
}
/* We trust ourselves that we're running chrome, and will set the actor on the host-side
var is_chromium = /chromium/.test( navigator.userAgent.toLowerCase() );
if (!is_chromium) plugin.setActor("application://google-chrome.desktop");
else plugin.setActor("application://chromium-browser.desktop");
*/
chrome.extension.onRequest.addListener (onExtensionRequest);
chrome.tabs.onUpdated.addListener (onTabUpdated);
chrome.tabs.onCreated.addListener (onTabCreated);
chrome.tabs.onRemoved.addListener (onTabRemoved);
chrome.downloads.onChanged.addListener(onDownloadChanged);
chrome.tabs.onActivated.addListener(onTabActivatedListener);
chrome.windows.onFocusChanged.addListener (onWindowsFocusChanged);
chrome.windows.getAll({"populate" : true}, function (windows) {
for (var i = 0; i < windows.length; i++) {
var tabs = windows[i].tabs;
for (var j = 0; j < tabs.length; j++) {
chrome.tabs.executeScript(tabs[j].id, {file: "content_script.js"}, function(result) {
if (chrome.runtime.lastError)
console.error ("Could not inject content in tab, %O", chrome.runtime.lastError);
});
}
}
});
initActiveTab();
pollForFocusLoss();
intervalWorker = new Worker ("intervalWorker.js");
intervalWorker.onmessage = function (evt) {
if (evt.data.type == "Timeout") {
intervalRun();
}
};
intervalWorker.onerror = function (evt) {
console.error ("The worker that periodically processes active tabs has thrown an error (%s)", evt.data);
};
intervalWorker.postMessage ({type: "Start"});
nativeConnect();