-
Notifications
You must be signed in to change notification settings - Fork 2
/
backend.js
398 lines (369 loc) · 12.1 KB
/
backend.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
/*
* This file is part of Chronos. The LICENSE file at the top level of
* this repository contains the full copyright notices and license terms.
*/
const cache_lifetime = 10 * 24 * 60 * 60 * 1000;
const cache_timeout = 60 * 60 * 1000;
const sync_delay_timeout = 5 * 60 * 1000;
const lock = '_lock';
function sanitizeURL(url) {
return url.replace(/([^:]\/)\/+/g, "$1");
}
function uuid4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function dispatch(message, callback) {
if (message == 'employees') {
updateEmployees().always(callback);
return true;
} else if (message == 'works') {
updateWorks().always(callback);
return true;
} else if (message[0] == 'lines') {
getLines(message[1]).always(callback);
return true;
} else if (message[0] == 'update line') {
runWithLock(lock, function() {
callback(updateLine(message[1], message[2], message[3]));
return syncLines();
});
return;
} else if (message[0] == 'delete line') {
runWithLock(lock, function() {
callback(deleteLine(message[1], message[2]));
return syncLines();
});
return;
}
}
function runWithLock(key, fn, timeout, checkTime) {
var timer = function() {
window.setTimeout(runWithLock.bind(null, key, fn, timeout, checkTime), checkTime);
};
if (!timeout) {
timeout = 30000;
}
if (!checkTime) {
checkTime = 100;
}
var result = localStorage.getItem(key);
if (result) {
var data = JSON.parse(result);
if (data.time >= Date.now() - timeout) {
timer();
return;
} else {
console.error('lock timeout');
localStorage.removeItem(key);
}
}
var id = Math.random();
localStorage.setItem(key, JSON.stringify({id: id, time: Date.now()}));
window.setTimeout(function() {
var result = localStorage.getItem(key);
if (!result) {
timer();
return;
}
var data = JSON.parse(result);
if (data.id !== id) {
timer();
return;
}
var response;
try {
response = fn();
} finally {
if (response) {
response.always(function() {
localStorage.removeItem(key);
});
} else {
localStorage.removeItem(key);
}
}
}, 10);
}
function updateEmployees() {
var url = localStorage.getItem('url');
var db = localStorage.getItem('db');
var key = localStorage.getItem('key');
var employees = JSON.parse(localStorage.getItem('employees')) || [];
var date = new Date(JSON.parse(localStorage.getItem('employees_date')));
if (!(url && db && key)) {
return jQuery.when([]);
}
if ((navigator.offline) ||
((new Date() - date) < cache_timeout)) {
return jQuery.when(employees);
}
var employees_url = sanitizeURL(url + '/' + db + '/timesheet/employees');
return jQuery.ajax({
'url': employees_url,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'type': 'GET'})
.then(function(employees) {
localStorage.setItem('employees', JSON.stringify(employees));
localStorage.setItem('employees_date', JSON.stringify(new Date()));
return employees;
}, function() {
return employees;
});
}
function updateWorks() {
var url = localStorage.getItem('url');
var db = localStorage.getItem('db');
var key = localStorage.getItem('key');
var employee = localStorage.getItem('employee');
var works = JSON.parse(localStorage.getItem('works')) || [];
var date = new Date(JSON.parse(localStorage.getItem('works_date')));
if (!(url && db && key && employee)) {
return jQuery.when([]);
}
if ((navigator.offline) ||
((new Date() - date) < cache_timeout)) {
return jQuery.when(works);
}
var works_url = sanitizeURL(
url + '/' + db + '/timesheet' + '/employee/' + employee +
'/works');
return jQuery.ajax({
'url': works_url,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'type': 'GET'})
.then(function(works) {
localStorage.setItem('works', JSON.stringify(works));
localStorage.setItem('works_date', JSON.stringify(new Date()));
return works;
}, function() {
return works;
});
}
function getLines(date) {
var url = localStorage.getItem('url');
var db = localStorage.getItem('db');
var key = localStorage.getItem('key');
var employee = localStorage.getItem('employee');
var lines = JSON.parse(localStorage.getItem('lines')) || {};
var lines_date = JSON.parse(localStorage.getItem('lines_date')) || {};
var cache_date = new Date(lines_date[date]);
var unsaved = (lines[date] || []).filter(function(line) {
return line.dirty || (line.id < 0);
});
if (!(url && db && key && employee)) {
return jQuery.when([]);
}
if ((navigator.offline) ||
((new Date() - cache_date) < cache_timeout) ||
unsaved.length) {
return jQuery.when(lines[date] || []);
}
var line_url = sanitizeURL(
url + '/' + db + '/timesheet/employee/' + employee +
'/lines/' + date);
return jQuery.ajax({
'url': line_url,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'type': 'GET'})
.then(function(lines) {
runWithLock(lock, function() {
var lines_all = JSON.parse(localStorage.getItem('lines')) || {};
var lines_date = JSON.parse(
localStorage.getItem('lines_date')) || {};
var unsaved = (lines_all[date] || []).filter(function(line) {
return line.dirty || (line.id < 0);
});
if (unsaved.length) {
return lines_all[date];
}
lines_all[date] = lines;
lines_date[date] = new Date();
localStorage.setItem('lines', JSON.stringify(lines_all));
localStorage.setItem('lines_date', JSON.stringify(lines_date));
});
return lines;
}, function() {
return lines[date] || [];
});
}
function updateLine(date, id, values) {
var lines_all = JSON.parse(localStorage.getItem('lines')) || {};
var lines = lines_all[date] || [];
var line;
values.dirty = true;
var min = 0;
for (var i = 0; i < lines.length; i++) {
line = lines[i];
if ((line.id === id) ||
(values.uuid && (line.uuid === values.uuid))) {
jQuery.extend(line, values);
break;
}
min = Math.min(min, line.id);
}
if (!id) {
line = {'id': --min};
values.uuid = uuid4();
lines.push(jQuery.extend(line, values));
}
lines_all[date] = lines;
localStorage.setItem('lines', JSON.stringify(lines_all));
}
function deleteLine(date, id) {
var lines_all = JSON.parse(localStorage.getItem('lines')) || {};
var lines = lines_all[date] || [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.id === id) {
if (line.id < 0) {
lines.splice(i, 1);
} else {
line.deleted = true;
}
break;
}
}
lines_all[date] = lines;
localStorage.setItem('lines', JSON.stringify(lines_all));
}
function syncLines() {
var url = localStorage.getItem('url');
var db = localStorage.getItem('db');
var key = localStorage.getItem('key');
var employee = localStorage.getItem('employee');
if (!(url && db && key) || navigator.offline) {
return;
}
url = sanitizeURL(url + '/' + db + '/timesheet/line');
var to_delete = [],
to_create = [],
to_update = [],
to_clear = [];
var lines_all = JSON.parse(localStorage.getItem('lines')) || {};
for (var date in lines_all) {
var lines = lines_all[date];
var clearable = true;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.deleted) {
clearable = false;
to_delete.push([date, line.id]);
} else if (line.dirty || line.id < 0) {
clearable = false;
var values = Object.assign({
'employee': employee,
'date': date,
}, line);
if (line.id < 0) {
to_create.push([date, line.id, values]);
} else {
to_update.push([date, line.id, values]);
}
}
}
if (clearable &&
(Math.abs(new Date() - new Date(date)) > cache_lifetime)) {
to_clear.push(date);
}
}
localStorage.setItem('lines', JSON.stringify(lines_all));
to_clear.forEach(clear);
var promises = [];
[[to_delete, delete_], [to_create, create], [to_update, update]]
.forEach(function(e) {
var array = e[0],
method = e[1];
for (var i = 0; i < array.length; i++) {
var args = array[i];
promises.push(method.apply(null, args));
}
});
function delete_(date, id) {
return jQuery.ajax({
'url': url + '/' + id,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'type': 'DELETE'})
.then(function() {
store(date, id);
});
}
function create(date, id, values) {
return jQuery.ajax({
'url': url,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'data': JSON.stringify(values),
'type': 'POST'})
.then(function(line) {
store(date, id, line);
});
}
function update(date, id, values) {
return jQuery.ajax({
'url': url + '/' + id,
'headers': {
'Authorization': 'bearer ' + key
},
'contentType': 'application/json',
'data': JSON.stringify(values),
'type': 'PUT'})
.then(function(line) {
store(date, id, line);
});
}
function store(date, id, line) {
var lines_all = JSON.parse(localStorage.getItem('lines')) || {};
var lines = lines_all[date] || [];
for (var i = 0; i < lines.length; i++) {
var cur = lines[i];
if (cur.id == id) {
if (line) {
lines.splice(i, 1, line);
} else {
lines.splice(i, 1);
}
break;
}
}
lines_all[date] = lines;
localStorage.setItem('lines', JSON.stringify(lines_all));
}
function clear(date) {
var lines = JSON.parse(localStorage.getItem('lines')) || {};
var lines_date = JSON.parse(localStorage.getItem('lines_date')) || {};
delete lines[date];
delete lines_date[date];
localStorage.setItem('lines', JSON.stringify(lines));
localStorage.setItem('lines_date', JSON.stringify(lines_date));
}
return jQuery.when.apply(jQuery, promises);
}
try {
chrome;
} catch(err) {
function sync() {
runWithLock(lock, function() {
return syncLines().always(function() {
window.setTimeout(sync, sync_delay_timeout);
});
});
}
sync();
}