-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.js
435 lines (375 loc) · 9.84 KB
/
web.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
function Config() {
this.getUniqueId = function () {
return typeof APP_ID == "undefined"
? JSON.stringify(window.location.hostname)
: APP_ID;
};
this.getRootUrl = function () {
return typeof WEBSITE_URL == "undefined"
? window.location.protocol +
"//" +
window.location.hostname +
(window.location.port ? ":" + location.port : "")
: WEBSITE_URL;
};
this.getApiUrl = function () {
return typeof API_URL == "undefined"
? window.location.protocol +
"//" +
window.location.hostname +
(location.port ? ":" + window.location.port : "") +
"/api"
: API_URL;
};
}
function Registry(namespace) {
var namespace =
typeof namespace === "undefined"
? jsonEncode(window.location.hostname)
: "@" + namespace;
const defaultPassword =
"8pVbaKePV3beCUZYbKSfujzucbcD3eqyJvCAUgQL8PbYe3VmAMSKC9esx8jV8M7KegPsxkDTpUKvu2UenQyPPjsDf92XnjtZh5GJRz8bQHZngNGKenKZHDD8";
const password = namespace == "" ? namespace : defaultPassword;
function jsonDecode(json) {
return JSON.parse(json);
}
function jsonEncode(string) {
return JSON.stringify(string);
}
/**
* Gets a key from the key-vaue store, if it does not exist returns NULL
* @param {string} key
* @returns {Object}
*/
this.get = function (key) {
const keyNamespaced = key + namespace;
if (localStorage.getItem(keyNamespaced) === null) {
return null;
}
var expiresDate = localStorage.getItem(keyNamespaced + "&&expires");
if (expiresDate === null) {
return null;
}
const expires = new Date(expiresDate);
const now = new Date();
const isExpired = now.getTime() > expires.getTime() ? true : false;
if (isExpired) {
this.remove(keyNamespaced);
return null;
}
const value = window.localStorage.getItem(keyNamespaced);
if (value === null) {
return null;
}
if (value === "undefined") {
return null;
}
if (typeof value === "undefined") {
return null;
}
const valueDecoded = jsonDecode(value);
return this.decrypt(valueDecoded);
};
/**
* Sets a value to a key
* @param {string} key
* @param {Object} value
* @param {number} expires
* @returns {void}
*/
this.set = function (key, value, expires) {
if (typeof value === "undefined") {
value = null;
}
const expiresMilliseconds = typeof expires === "undefined" ? 60000000000 : expires * 1000;
const keyNamespaced = key + namespace;
if (value === null) {
localStorage.removeItem(keyNamespaced);
return;
}
const encValue = this.encrypt(value);
localStorage.setItem(keyNamespaced, jsonEncode(encValue));
const expiresTime = new Date().getTime() + expiresMilliseconds;
const expiresDate = new Date();
expiresDate.setTime(expiresTime);
localStorage.setItem(keyNamespaced + "&&expires", expiresDate);
};
this.remove = function (key) {
const keyNamespaced = key + namespace;
localStorage.removeItem(keyNamespaced);
localStorage.removeItem(keyNamespaced + "&&expires");
};
this.empty = function () {
var keys = Object.keys(localStorage);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key.indexOf(namespace) > -1) {
localStorage.removeItem(key);
}
}
};
/**
* Encrypts an object to a string
* @return string
*/
this.encrypt = function (obj) {
const jsonString = JSON.stringify(obj);
const passLen = password.length;
const result = [];
for (var i = 0; i < jsonString.length; i++) {
const passOffset = i % passLen;
const calAscii = jsonString.charCodeAt(i) + password.charCodeAt(passOffset);
result.push(calAscii);
}
return JSON.stringify(result);
};
/**
* Decrypts an string to the original object
* @return object
*/
this.decrypt = function (encStr) {
const codesArr = JSON.parse(encStr);
const passLen = password.length;
const result = [];
for (let i = 0; i < codesArr.length; i++) {
const passOffset = i % passLen;
const calAscii = codesArr[i] - password.charCodeAt(passOffset);
result.push(calAscii);
}
let str = "";
for (let i = 0; i < result.length; i++) {
var ch = String.fromCharCode(result[i]);
str += ch;
}
return JSON.parse(str);
};
}
/**
* Initialize
* @type $$
*/
function Initialize() {
/* START: Public Scope */
this.debug = true;
/**
* Stores a key-value pair to the registry
*
* @param {String} key
* @param {Object} value
* @returns {Object}
*/
this.get = function (key) {
return Registry.get(key);
};
/**
* Retrieves a key value from the registry
*
* @param {String} key
* @returns {Object}
*/
this.set = function (key, value) {
return Registry.set(key, value);
};
/**
* Returns the API URL
* If an API_URL variable is set, will return as it is. Otherwise will
* generate one, assuming the API is hosted on the same domain {domain}/api
* @returns {String}
*/
this.getApiUrl = function () {
return Config.getApiUrl();
};
/**
* Returns the current page URL
*
* @returns {String}
*/
this.getUrl = function () {
return window.location.href;
};
/**
* Returns the URL parameters
*
* @returns {Array}
*/
this.getUrlParams = function () {
var s = window.location.search.substring(1).split("&");
var p = {};
if (!s.length) {
return p;
}
for (var i = 0; i < s.length; i++) {
var parts = s[i].split("=");
p[unescape(parts[0])] = unescape(parts[1]);
}
return p;
};
/**
* Returns a single URL parameter
*
* @returns {String}
*/
this.getUrlParam = function (parameter) {
var parameters = this.getUrlParams();
return typeof parameters[parameter] === "undefined"
? null
: parameters[parameter];
};
/**
* Returns the authenticated user
* Key "AuthUser"
* @returns {Array}
*/
this.getAuthUser = function () {
if (Registry.get("AuthUser") === null) {
return null;
}
return Registry.get("AuthUser");
};
/**
* Sets the authenticated user.
* Key "AuthUser"
*
* @returns {Array}
*/
this.setAuthUser = function (user) {
return Registry.set("AuthUser", user);
};
/**
* Returns the authentication token
* Key "AuthToken"
*
* @returns {String}
*/
this.getAuthToken = function () {
return Registry.get("AuthToken");
};
/**
* Sets the authentication token.
* Key "AuthToken"
*
* @returns {Array}
*/
this.setAuthToken = function (token) {
return Registry.set("AuthToken", token);
};
/**
* Returns the current language, if set.
* Key "CurrentLanguage"
* @returns {Array}
*/
this.getLanguage = function () {
var language = Registry.get("CurrentLanguage");
if (language === null) {
language = "en";
}
return language;
};
/**
* Sets the current language.
* Key "CurrentLanguage"
* @returns {Array}
*/
this.setLanguage = function (language) {
return Registry.set("CurrentLanguage", language);
};
/**
* Redirects the user to the specified URL
*
* Options:
* - target = _blank - will open a new window
*
* @param {*} url
* @param {*} data
* @param {*} options
* @returns
*/
this.to = function (url, data, options) {
if (url.match("^http://") || url.match("^https://")) {
// External url
} else {
var url = rtrim(Config.getRootUrl(), ["/"]) + "/" + ltrim(url, ["/"]);
}
var queryString =
typeof data === "undefined"
? ""
: Object.keys(data)
.map((key) => {
return (
encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
);
})
.join("&");
if (queryString.length > 0) {
url = url + (url.indexOf("?") < 0 ? "?" : "&") + queryString;
}
var options = typeof options === "undefined" ? {} : options;
if (options.target === "_blank") {
var link = document.createElement("a");
link.href = url;
link.target = "_blank";
link.style.display = "none";
document.body.appendChild(link);
document.body.lastElementChild.click();
} else {
window.location.href = url;
}
return false; // otherwise links will be triggered
};
var topics = {},
subUid = -1;
this.publish = function (topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function () {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
this.subscribe = function (topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func,
});
return token;
};
this.unsubscribe = function (token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
function rtrim(str, charlist) {
charlist = !charlist
? " \\s\u00A0"
: (charlist + "").replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, "\\$1");
var re = new RegExp("[" + charlist + "]+$", "g");
return (str + "").replace(re, "");
}
function ltrim(str, charlist) {
charlist = !charlist
? " \\s\u00A0"
: (charlist + "").replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, "$1");
var re = new RegExp("^[" + charlist + "]+", "g");
return (str + "").replace(re, "");
}
}
Config = new Config();
Registry = new Registry(Config.getUniqueId());
$$ = new Initialize();