-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
executable file
·553 lines (477 loc) · 18.4 KB
/
script.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
if(typeof require !== 'undefined') {
var electron = require('electron');
var getGlobal = electron.remote.getGlobal;
var ipcRenderer = electron.ipcRenderer;
var openExternalURL = electron.shell.openExternal;
document.body.classList.add('no-preload');
} else {
var getGlobal = window.Bridge.getGlobal;
var ipcRenderer = window.Bridge.ipcRenderer;
var ReconnectingWebSocket = window.Bridge.ReconnectingWebSocket;
var storage = window.Bridge.storage;
var openExternalURL = getGlobal('openExternalURL');
}
document.querySelector('html').style.fontSize = getGlobal('fontSize')/1.5;
getGlobal('goNormalSize')();
var client_id = '7JomVQ7FyglKL2PvIxCVS1rIo9kMQKcv78lk4vwM';
var tokenStore = getGlobal('token');
var token;
var refreshToken;
var doneToday = 0;
var streak = 0;
var userId = 0;
var lastSyncedDateString = '0';
var todos = [];
var socket;
if(typeof tokenStore === 'undefined') {
login();
} else {
tokenStore = tokenStore.split('|');
token = tokenStore[0];
if(tokenStore.length >= 2) {
refreshToken = tokenStore[1];
}
setInterval(refreshMakerlogToken, 59*60*1000); // Every 59 minutes
checkForNewUpdate();
//setInterval(checkForNewUpdate,10*60*1000); // Every 10 minutes
fetchHashtags();
}
console.log(ipcRenderer.on);
ipcRenderer.on('toggleProgressBar', (event, arg) => {
toggleProgressBar();
})
ipcRenderer.on('darkModeChange', (event, arg) => {
data.darkMode = getGlobal('darkMode');
})
ipcRenderer.on('focusContent', (event, arg) => {
document.querySelector('.content').focus();
})
ipcRenderer.on('zoomIn', (event, arg) => {
zoomIn();
});
ipcRenderer.on('zoomOut', (event, arg) => {
zoomOut();
});
ipcRenderer.on('resetZoom', (event, arg) => {
resetZoom();
});
ipcRenderer.on('markTodoAsDone', (event, taskId) => {
console.log('MARKING TODO AS DONE', taskId);
myFetch(`https://api.getmakerlog.com/tasks/${taskId}/`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
done: true,
in_progress: false
})
}).then(r => console.log(r));
});
var data = {
dragover: false,
darkMode: getGlobal('darkMode'),
taskComposer: {
content: '',
content_autocompleted: '',
done: true,
in_progress: false,
processing: false,
attachment: undefined,
attachmentURL: undefined
},
hashtags: [],
progressBar: {
show: true,
showTooltip: false,
percentage: calculateDayProgress()
},
heatmap: {
data: [],
max: 0,
}
}
if(localStorage.hideProgressBar === true || localStorage.hideProgressBar === 'true') {
data.progressBar.show = false;
} else {
localStorage.hideProgressBar = !data.progressBar.show;
}
var vm = new Vue({
el: '#app',
data: data
});
setInterval(updateDayProgress, 60*1000); // Every 60 seconds, because that's how long it takes for the percentage to change anyway: https://i.imgur.com/cP67s2L.png
function notifyAboutStreak(force = false) {
if(doneToday == 0 || force) {
var notification = new Notification(`Your ${streak} day streak is about to end!`, {
body: `Click here to log a task and keep it up!`,
silent: false,
requireInteraction: true,
sticky: true
});
notification.onclick = function(event) {
getGlobal('openMenubar')();
};
}
}
function syncShadowContentScroll() {
document.querySelector('.shadow-content').scrollLeft = document.querySelector('.content').scrollLeft;
}
function updateDayProgress() {
data.progressBar.percentage = calculateDayProgress();
console.log(data.progressBar.percentage);
vm.$forceUpdate();
}
function calculateDayProgress() {
return (((new Date().getHours() * 60) + new Date().getMinutes()) / 1440) * 100
// Calculation identical to Sergio's: https://gitlab.com/makerlog/web/blob/173ca1fe22dad7672d60be51e948b19088b843bb/src/pages/StreamPage/components/DayProgressBar.js#L40
}
function toggleProgressBar () {
console.log('Toggling progress bar!');
data.progressBar.show = !data.progressBar.show;
localStorage.hideProgressBar = !data.progressBar.show;
}
window.onkeydown = function(e){
//console.log(e);
if(e.keyCode == 68 && (e.ctrlKey || e.metaKey)) { // aka CtrlOrCommand+D
var dropdown = document.querySelector('.status');
var options = Array.from(dropdown.options).map(o => o.getAttribute('value'));
var newIndex = options.indexOf(dropdown.value) + 1;
if(newIndex >= options.length) {
newIndex = 0;
}
dropdown.value = options[newIndex];
// From v-on:input attribute
data.taskComposer.done = dropdown.value == 'done';
data.taskComposer.in_progress = dropdown.value == 'in_progress'
}
if(e.keyCode == 82 && (e.ctrlKey || e.metaKey)) { // aka CtrlOrCommand+R
console.log('Reloading!');
window.location.reload();
}
if(e.keyCode == 187 && (e.ctrlKey || e.metaKey)) { // aka CtrlOrCommand+=
zoomIn();
}
if(e.keyCode == 189 && (e.ctrlKey || e.metaKey)) { // aka CtrlOrCommand+-
zoomOut();
}
if(e.keyCode == 48 && (e.ctrlKey || e.metaKey)) { // aka CtrlOrCommand+0
resetZoom();
}
}
var zoomStepSize = 2;
var setFontSize = getGlobal('setFontSize');
function zoomIn () {
console.log('Zooming in!');
var newFontSize = Number(getComputedStyle(document.querySelector('html')).fontSize.replace('px','')) + zoomStepSize;
document.querySelector('html').style.fontSize = newFontSize;
setFontSize(newFontSize);
vm.$forceUpdate();
}
function zoomOut () {
console.log('Zooming out!');
var newFontSize = Number(getComputedStyle(document.querySelector('html')).fontSize.replace('px','')) - zoomStepSize;
document.querySelector('html').style.fontSize = newFontSize;
setFontSize(newFontSize);
vm.$forceUpdate();
}
function resetZoom () {
console.log('Resetting zoom!');
var newFontSize = 16;
document.querySelector('html').style.fontSize = newFontSize;
setFontSize(newFontSize);
vm.$forceUpdate();
}
window.addEventListener('paste', function(e){
//console.log(e);
var items = e.clipboardData.items;
if (items) {
// Loop through all items, looking for any kind of image
for (var i = 0; i < items.length; i++) {
console.log(items[i]);
if (items[i].kind == 'file') {
e.preventDefault();
setAttachment(items[i].getAsFile());
}
}
}
});
function dropEvent(e) {
setAttachment(e.dataTransfer.files[0]);
}
function setAttachment(file) {
data.taskComposer.attachment = file;
getBase64(data.taskComposer.attachment)
.then(result => data.taskComposer.attachmentURL = result)
}
function createTask(content, done, in_progress, attachment) {
data.taskComposer.processing = true;
var formData = new FormData();
formData.append('content',content);
formData.append('done',done);
formData.append('in_progress',in_progress);
if(typeof attachment !== 'undefined') {
formData.append('attachment',attachment);
}
return myFetch('https://api.getmakerlog.com/tasks/', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
}).then(r => {
console.log(r);
data.taskComposer.processing = false;
data.taskComposer.content = '';
document.querySelector('.content').value = '';
data.taskComposer.content_autocompleted = '';
data.taskComposer.attachment = undefined;
data.taskComposer.attachmentURL = undefined;
document.querySelector('.attachment').value = '';
doneToday++;
getGlobal('setDoneToday')(doneToday);
})
}
function fetchHashtags() {
return myFetch('https://api.getmakerlog.com/me/', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
}).then(r => {
console.log('ME', r);
userId = r.id;
myFetch(r.avatar).then(r => r.blob()).then(blob => {
return new Promise(resolve => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(blob);
}).then(dataURL => getGlobal('setUser')(r.username, dataURL));
});
if (ReconnectingWebSocket) {
subscribeToWebSocket();
}
getTodos();
getHeatmap();
return myFetch(`https://api.getmakerlog.com/users/${r.id}/stats/`)
})
.then(r => {
console.log('STATS', r);
streak = r.streak;
getGlobal('setStreak')(streak);
doneToday = r.done_today;
getGlobal('setDoneToday')(doneToday);
getGlobal('setMakerScore')(r.maker_score);
getGlobal('setTDA')(r.tda);
getGlobal('setRemainingTasks')(r.remaining_tasks);
getGlobal('setRestDays')(r.rest_day_balance);
storage.getMany(['streakNotificationsOn', 'streakNotificationsTime'], function(err, data){
if(data.streakNotificationsOn === true) {
var time = data.streakNotificationsTime;
var hours = time.split(':')[0];
var minutes = time.split(':')[1];
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var hoursUntilNotification = hours - currentHours;
var minutesUntilNotification = minutes - currentMinutes;
var timeoutMilliseconds = minutesUntilNotification*60*1000 + hoursUntilNotification*60*60*1000;
console.log(`${hoursUntilNotification} hours and ${minutesUntilNotification} minutes until notification.`);
if(hours >= 0) {
setTimeout(notifyAboutStreak, timeoutMilliseconds);
}
}
})
return myFetch(`https://api.getmakerlog.com/projects/`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
})
.then(r => {
console.log('PROJECTS', r)
data.hashtags = r.map(project => project.name);
})
}
function getTodos(nextURL = null) {
myFetch(nextURL ? nextURL : `https://api.getmakerlog.com/tasks/?user=${userId}&done=false`).then(r => {
console.log('TODOS', r);
todos = todos.concat(r.results);
getGlobal('setTodos')(todos);
if (todos.length > 0) {
lastSyncedDateString = todos[0].updated_at;
}
if (r.next) {
return getTodos(r.next);
}
});
}
function syncTodos() {
myFetch(`https://api.getmakerlog.com/tasks/sync?done=false&last_sync_date=${lastSyncedDateString}`, {
headers: {
'Authorization': `Bearer ${token}`
}
}).then(r => {
console.log('SYNCED TODOS', r);
lastSyncedDateString = r.sync_date;
todos = r.data.concat(todos).sort((a,b) => new Date(b.updated_at) - new Date(a.updated_at));
getGlobal('setTodos')(todos);
})
}
//setInterval(syncTodos, 1000);
function subscribeToWebSocket() {
socket = new ReconnectingWebSocket(`wss://api.getmakerlog.com/users/${userId}/stream`);
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`Makerlog: Event received through WS. (${data.type})`, data.payload)
switch(data.type) {
case 'task.created':
case 'task.updated':
case 'task.sync':
let tasks = data.batch ? data.batch : [data.payload]; // Sometimes the API sends batch data to save bandwidth. Prepare for payload to be an array.
console.log("Tasks created/updated/synced", tasks)
todos = tasks.filter(task => task.done === false).concat(todos).sort((a,b) => new Date(b.updated_at) - new Date(a.updated_at));
lastSyncedDateString = todos[0].updated_at;
getGlobal('setTodos')(todos);
break;
case 'task.deleted':
console.log("Task deleted", data.payload)
if (todos.map(t => t.id).includes(data.payload.id)) {
todos.splice(todos.map(t => t.id).indexOf(data.payload.id), 1);
getGlobal('setTodos')(todos);
}
break;
default:
console.log("Other event", data.payload)
return;
}
}
socket.onreconnect = (event) => {
console.log('SOCKET RECONNECT', event)
syncTodos();
}
}
function getHeatmap() {
myFetch(`https://api.getmakerlog.com/users/${userId}/activity_graph/`).then(r => {
console.log('HEATMAP', r);
data.heatmap.data = r.data;
vm.$forceUpdate();
setTimeout(() => {
document.querySelector('#heatmap .vch__months__labels__wrapper').style.display = 'none';
document.querySelector('#heatmap .vch__days__labels__wrapper').style.display = 'none';
document.querySelector('#heatmap .vch__legend__wrapper').style.display = 'none';
document.querySelector('#heatmap .vch__year__wrapper').removeAttribute('transform')
document.querySelector('#heatmap').setAttribute('viewBox', '0 0 647 83');
svgElemToPngDataURL(document.querySelector('#heatmap')).then(dataURL => getGlobal('setHeatmap')(dataURL));
}, 100);
});
}
function autofillHashtag() {
if((/#./).test(data.taskComposer.content)) {
console.log('AUTOCOMPLETE');
var fullTextWithSuggestion = data.taskComposer.content;
var split = data.taskComposer.content.split('#');
var hashtagText = split[split.length - 1];
//console.log(hashtagText);
var possibleHashtags = data.hashtags.filter(hashtag => hashtag.startsWith(hashtagText));
//console.log(possibleHashtags);
var bestSuggestion = possibleHashtags[0]; // Sorted by number of times used
//console.log(bestSuggestion);
fullTextWithSuggestion = split;
fullTextWithSuggestion[split.length - 1] = bestSuggestion;
fullTextWithSuggestion = fullTextWithSuggestion.join('#');
data.taskComposer.content_autocompleted = fullTextWithSuggestion;
} else if (data.taskComposer.content_autocompleted != '') {
data.taskComposer.content_autocompleted = '';
}
//console.log(fullTextWithSuggestion);
}
function login() {
document.body.innerHTML = '';
var storeAppHref = getGlobal('storeAppHref');
storeAppHref(window.location.href);
getGlobal('goFullscreen')();
window.location = `https://api.getmakerlog.com/oauth/authorize/?client_id=${client_id}&scope=user:read%20tasks:write%20projects:read&response_type=code`;
}
function refreshMakerlogToken(notify = false) {
if(typeof refreshToken !== 'undefined' && refreshToken.length > 0) {
return fetch('https://makerlog-menubar-cloud-functions.netlify.app/.netlify/functions/refreshMakerlogToken', {
method: 'POST',
body: JSON.stringify({refresh_token: refreshToken})
}).then(r => r.json()).then(r => {
token = r.access_token;
refreshToken = r.refresh_token;
getGlobal('storeToken')(`${token}|${refreshToken}`);
if(notify) {
alert('Failed. Please try that again!')
}
if(data.taskComposer.content.length == 0) {
window.location.reload();
}
}, err => alert('Failed. Please try that again!'))
.catch(r => alert('Failed. Please try that again!'))
} else {
login(); // Can't refresh so log in again
}
}
function checkForNewUpdate() {
return myFetch('https://api.github.com/repos/Booligoosh/makerlog-menubar/releases/latest')
.then(latest => {
var currentNum = Number(getGlobal('appVersion').replace(/\./g,''));
var latestNum = Number(latest.tag_name.replace('v','').replace(/\./g,''));
if(latestNum > currentNum) {
if(typeof localStorage.lastUpdateNotificationTime == 'undefined' || Date.time() - Number(localStorage.lastUpdateNotificationTime) > 1000*60*60*24) { // 24 hours
alert(`Please update to the latest version!\n${latest.name}\n\nYou can download it here:\nhttps://github.com/Booligoosh/makerlog-menubar/releases/tag/${latest.tag_name}`);
}
}
})
}
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
function svgElemToPngDataURL(svg) {
return new Promise(resolve => {
var svgData = new XMLSerializer().serializeToString(svg);
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width * 3;
canvas.height = svgSize.height * 3;
canvas.style.width = svgSize.width;
canvas.style.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))));
img.onload = function () {
ctx.drawImage(img, 0, 0);
var canvasdata = canvas.toDataURL("image/png", 1);
resolve(canvasdata)
};
})
}
function myFetch(input,init = {}) {
return fetch(input,init)
.then(async r => {
if(r.status === 403) {
let json = await r.json()
if (json && json.detail === `You do not have permission to perform this action.`) {
// Wrong scopes
login()
} else if (new URL(r.url).host.includes('getmakerlog')) { // NOT SECURE for validating but fine here
// Makerlog credentials timed out
refreshMakerlogToken(true);
}
} else {
return r.headers.get('content-type').startsWith('application/json') ? r.json() : r;
}
}, err => {
// No internet connection
});
}
window.addEventListener('DOMContentLoaded', function(){vm.$forceUpdate()})