forked from rjrodriguez/RCH-Bootstrap-4-Snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trackingClient.js
64 lines (53 loc) · 2.3 KB
/
trackingClient.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
// This is example of a client for extenstion online tracking service
// Part of Brackets Extension Rating extension by Alex Bardanov
// https://github.com/dnbard/brackets-extension-rating
// use require('./onlineTrackingClient').init() to activate tracking
define(function(require, exports){
var trackingServiceUrl = 'http://online-dnbard.rhcloud.com/',
// http://brackets-online.herokuapp.com/ is an address of default tracking service
// Change it if you use self-hosting instance of online tracking service
appToken = '5620f410e59615263f000006',
// read https://github.com/dnbard/brackets-extension-rating/wiki/Online-and-max-users-counters-in-this-extension
// to learn on how to obtain an application token for your extension
mins60 = 60 * 60 * 1000,
mins5 = 5 * 60 * 1000,
keyId = 'ext-online-id';
function tick(){
var userId = getUserId(appToken, keyId),
url;
if (userId){
url = trackingServiceUrl + 'tick/' + appToken + '/' + userId;
} else {
url = trackingServiceUrl + 'tick/' + appToken;
}
$.ajax({ url: url })
.success(function(data){
//TODO: create complex model of data in local storage to support any number of extensions
if (data && data !== 'OK' && data !== 'ERROR'){
saveUserId(data, appToken, keyId);
}
}).error(function(){
console.log('Can\'t track online status, retry in 5 mins');
setTimeout(tick, mins5);
});
}
function init(){
tick();
setInterval(tick, mins60);
}
function getUserId(appToken, keyId){
if (typeof appToken !== 'string' || typeof keyId !== 'string'){
throw new Error('Invalid argument');
}
return JSON.parse(localStorage.getItem(keyId) || '{ }')[appToken];
}
function saveUserId(id, appToken, keyId){
if (typeof id !== 'string' || typeof appToken !== 'string' || typeof keyId !== 'string'){
throw new Error('Invalid argument');
}
var obj = JSON.parse(localStorage.getItem(keyId) || '{ }');
obj[appToken] = id;
localStorage.setItem(keyId, JSON.stringify(obj));
}
exports.init = init;
});