forked from Josephine-Chen/FocusPro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsites.js
87 lines (82 loc) · 2.3 KB
/
sites.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
/**
* Stores the time that is spent on each site.
*
* The primary interface to this class is through setCurrentFocus.
*/
//Note: Can probable use as is with no changes
function Sites(config) {
this._config = config;
if (!localStorage.sites) {
localStorage.sites = JSON.stringify({});
}
this._currentSite = null;
this._siteRegexp = /^(\w+:\/\/[^\/]+).*$/;
this._startTime = null;
}
/**
* Returns the a dictionary of site -> seconds.
*/
Object.defineProperty(Sites.prototype, "sites", {
get: function() {
var s = JSON.parse(localStorage.sites);
var sites = {};
for (var site in s) {
if (s.hasOwnProperty(site) && !this._config.isIgnoredSite(site)) {
sites[site] = s[site];
}
}
return sites;
}
});
/**
* Returns just the site/domain from the url. Includes the protocol.
* chrome://extensions/some/other?blah=ffdf -> chrome://extensions
* @param {string} url The URL of the page, including the protocol.
* @return {string} The site, including protocol, but not paths.
*/
Sites.prototype.getSiteFromUrl = function(url) {
var match = url.match(this._siteRegexp);
if (match) {
return match[1];
}
return null;
};
Sites.prototype._updateTime = function() {
if (!this._currentSite || !this._startTime) {
return;
}
var delta = new Date() - this._startTime;
console.log("Site: " + this._currentSite + " Delta = " + delta/1000);
if (delta/1000/60 > 2*this._config.updateTimePeriodMinutes) {
console.log("Delta of " + delta/1000 + " seconds too long; ignored.");
return;
}
var sites = this.sites;
if (!sites[this._currentSite]) {
sites[this._currentSite] = 0;
}
sites[this._currentSite] += delta/1000;
localStorage.sites = JSON.stringify(sites);
};
/**
* This method should be called whenever there is a potential focus change.
* Provide url=null if Chrome is out of focus.
*/
Sites.prototype.setCurrentFocus = function(url) {
console.log("setCurrentFocus: " + url);
this._updateTime();
if (url === null) {
this._currentSite = null;
this._startTime = null;
} else {
this._currentSite = this.getSiteFromUrl(url);
this._startTime = new Date();
}
};
/**
* Clear all statistics.
*/
Sites.prototype.clear = function() {
localStorage.sites = JSON.stringify({});
this._config.lastClearTime = new Date().getTime();
};