Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
559 lines (511 loc) · 19.5 KB
/
Copy pathscript.js
File metadata and controls
559 lines (511 loc) · 19.5 KB
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
554
555
556
557
558
559
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
let settingsPanelIsVisible = false;
window.onload = function() {
giveSwayaaangBordersToItems()
initVariablesIfNotSet()
checkStatus().then((res) => {
setInterval(checkStatus, 10000)
})
fillInDaysInput()
fillInRecentTransactions()
}
function initVariablesIfNotSet() {
getStorageVariable("transactions").then((transactions) => {
if (!Array.isArray(transactions)) {
let transactionsArr = []
browser.storage.local.set({
"transactions": transactionsArr
}).then(() => {
console.log("Successfully set empty transactions")
}, (err) => {
console.error(`Failed to set empty transactions: ${err}`)
})
}
}, (err) => {
console.error(`failed to get transactions: ${err}`)
})
getStorageVariable("backendURL").then((backendURL) => {
if (backendURL == "" || backendURL === undefined) {
browser.storage.local.set({
"backendURL": "empty"
}).then(() => {
console.log("Successfully set empty backendURL")
}, (err) => {
console.error(`Failed to set empty backendURL: ${err}`)
})
} else {
console.log(`backendURL was not empty: ${backendURL}`)
}
}, (err) => {
console.error(`failed to get backendURL: ${err}`)
})
}
function giveSwayaaangBordersToItems() {
document.getElementById("settingsButton").style = swayaaangBorders(0.6)
// document.getElementById("importTransactions").style += swayaaangBorders(0.6)
}
function swayaaangBorders(borderRadius) {
const borderArr = [
`border-top-right-radius: ${borderRadius}rem;`,
`border-bottom-right-radius: ${borderRadius}rem;`,
`border-top-left-radius: ${borderRadius}rem;`,
`border-bottom-left-radius: ${borderRadius}rem;`,
]
let borderRadiuses = "";
for (let k = 0; k < 4; k++) {
const randNum = Math.floor(Math.random() * 2)
if (randNum % 2 == 0) {
borderRadiuses += borderArr[k]
}
}
return borderRadiuses
}
function getMostRecentTransactions(numTransactions) {
return new Promise((resolve, reject) => {
getStorageVariable("transactions", []).then((res) => {
if (res === undefined) {
resolve([])
} else if (res.length >= numTransactions) {
resolve(res.slice(numTransactions))
} else {
resolve(res)
}
}, (err) => {
reject(err)
})
})
}
function fillInDaysInput() {
getStorageVariable("daysInput", []).then((res) => {
if (res === undefined) {
document.getElementById("daysInput").value = "1"
} else {
document.getElementById("daysInput").value = res
}
}, (err) => {
console.error(`err getting daysInput:${err}`)
})
}
function fillInRecentTransactions() {
let outputHTML = "";
getMostRecentTransactions(5).then((transactions) => {
for (let i = 0; i < transactions.length; i++) {
const curr = transactions[i];
const transactionDate = new Date(curr.currTime);
let dateAtBeginningOfScan = new Date(curr.currTime);
dateAtBeginningOfScan = new Date(dateAtBeginningOfScan.setDate(dateAtBeginningOfScan.getDate() - curr.daysLookedUp))
// Add a bottom margin if its not the last element
const bottomMargin = i == (transactions.length - 1) ? '' : 'margin-bottom: 0.3rem;';
outputHTML += `
<td>
</td>
<div style="${bottomMargin} padding: 0.2rem 0.4rem 0.2rem 0.4rem; border: 1px solid grey; ${swayaaangBorders(0.55)}">
<table>
<tr style="text-align: center; width: 100%; float: center">
<td style="width: 1.5rem">
<img
src="https://i.imgur.com/vNnbGKp.png"
width="100%"
style="filter: invert()"
>
</td>
<td>
</td>
<td style="font-weight: bold; width: 20%; margin-left: 0.4vh; text-align: left">
${curr.n26FoundTransactions}
</td>
<td style="width: 20%">
</td>
<td style="font-weight: bold; width: 20%; text-align: right ">
${curr.lunchMoneyInseredTransactions}
</td>
<td>
</td>
<td style="width: 50%;float: right">
<img
src="https://i.imgur.com/aD0grat.png"
width="60%"
>
</td>
</tr>
</table>
<div style="text-align: center">
<div style="display: inline; font-size: 0.65rem">
${getDaysApartOutputString(dateAtBeginningOfScan, transactionDate)}
</div>
</div>
</div>
`
}
document.getElementById("transactionBay").innerHTML = outputHTML;
}, (err) => {
console.error(err)
})
}
document.getElementById("importTransactionsButton").addEventListener("click", function(e){
e.preventDefault();
getInfoForRequest().then((info) => {
const backendURLObject = new URL(info.backendURL)
const ws = new WebSocket(`ws://${backendURLObject.host}/ws/transactions?days=${info.daysInput}&apikey=${info.apiKey}`);
ws.onopen = function(e) {
createRequestStatusBox()
};
ws.onmessage = function(event) {
handleNewWsMessage(event)
}
ws.onclose = function(event) {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.log('[close] Connection died');
}
hideCreateStatusRequestBox()
};
}, (err) => {
console.error(`failed to get backendURL: ${err}`)
})
});
function handleNewWsMessage(event) {
const res = JSON.parse(event.data)
console.log(res)
// This is not best practice teehee
if (res.msg == "N26 has been authorized") {
document.getElementById("waitingFor2FAIcon").classList.remove("skeleton");
}
else if (res.msg == "Retrieved transactions from N26") {
document.getElementById("retrievingFromN26Icon").classList.remove("skeleton");
}
else if (res.msg == "transactions inserted into LunchMoney") {
document.getElementById("insertingIntoLunchMoneyIcon").classList.remove("skeleton");
}
else if (res.msg == "transaction finished") {
document.getElementById("savingSummaryIcon").classList.remove("skeleton");
const newTransaction = res.summarystats;
getStorageVariable("transactions").then((transactions) => {
if (!Array.isArray(transactions)) {
transactions = []
}
transactions.unshift(newTransaction)
console.log(`New transaction list:`)
console.log(transactions)
browser.storage.local.set({
"transactions": transactions
}).then(() => {
console.log("Successfully set new transactions")
fillInRecentTransactions()
}, (err) => {
console.error(`Failed to set new transactions: ${err}`)
})
}, (err) => {
console.error(err)
})
}
}
function getDaysApartOutputString(first, second) {
if (first.getMonth() == second.getMonth()) {
return `${first.getDate()} - ${second.getDate()} ${monthNames[first.getMonth()]}`
} else {
return `${first.getDate()} ${monthNames[first.getMonth()]} - ${second.getDate()} ${monthNames[second.getMonth()]}`
}
}
function dateString(date) {
return date.getDate() + " " + monthNames[date.getMonth()]
}
function checkStatus() {
return new Promise((resolve, reject) => {
getInfoForRequest().then((info) => {
if (info.backendURL === "empty") {
resolve()
}
console.log(`getting status from ${info.backendURL}/status`)
fetch(`${info.backendURL}/status`, {
method: 'POST',
mode: 'cors',
headers: {
'API_KEY': info.apiKey
}
})
.then((res) => res.json())
.then((data) => JSON.parse(data))
.then((data) => {
const currTime = new Date()
const timeAtServerStartUp = new Date(data.startuptime * 1000);
document.getElementById("upTime").textContent = timeSince(timeAtServerStartUp)
document.getElementById("onlineStatusText").textContent = "Online"
resolve()
}, (err) => {
document.getElementById("upTime").textContent = "";
document.getElementById("onlineStatusText").textContent = "Offline"
document.getElementById("onlineStatusIndicator").style = "filter: invert(30)"
reject()
});
}, (err) => {
console.error("failed to get backendURL and apikey")
reject(err)
})
})
}
function createRequestStatusBox() {
console.log("opening")
document.getElementById("requestStatusBox").innerHTML = `
<div style="text-align: center; margin-bottom: 0.0; margin-top: 0.3rem; border: 1px solid grey">
<table style="font-size: 0.75rem">
<tr>
<td>
<span style="margin-left: 0.5vh; margin-right: 0.5vh">
<img
src="https://i.imgur.com/3Ktp7tL.png"
width="4%"
style="margin-top: 0.3vh;"
id="waitingFor2FAIcon"
class="skeleton"
>
</span>
Authorize login within <span id="2FACountdownText">5m</span>
</td>
</tr>
<tr>
<td>
<span style="margin-left: 0.5vh; margin-right: 0.5vh">
<img
src="https://i.imgur.com/3Ktp7tL.png"
width="4%"
style="margin-top: 0.3vh"
id="retrievingFromN26Icon"
class="skeleton"
>
</span>
Retrieving from N26
</td>
</tr>
<tr>
<td>
<span style="margin-left: 0.5vh; margin-right: 0.5vh">
<img
src="https://i.imgur.com/3Ktp7tL.png"
width="4%"
style="margin-top: 0.3vh"
id="insertingIntoLunchMoneyIcon"
class="skeleton"
>
</span>
Inserting into LunchMoney
</td>
</tr>
<tr>
<td>
<span style="margin-left: 0.5vh; margin-right: 0.5vh">
<img
src="https://i.imgur.com/3Ktp7tL.png"
width="4%"
style="margin-top: 0.3vh"
id="savingSummaryIcon"
class="skeleton"
>
</span>
Saving summary
</td>
</tr>
</table>
</div>
`;
}
function hideCreateStatusRequestBox() {
console.log("closing")
document.getElementById("requestStatusBox").innerHTML = ``;
}
// https://stackoverflow.com/a/3177838
// no point in rewriting this
function timeSince(date) {
let seconds = Math.floor((new Date() - date) / 1000);
let interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + "y";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + "m";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + "d";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + "h";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + "m";
}
return Math.floor(seconds) + "s";
}
document.getElementById("daysInput").addEventListener("change", (ev) => {
const inputNum = parseInt(document.getElementById("daysInput").value)
console.log(inputNum)
if (Number.isInteger(parseInt(inputNum))) {
if (inputNum > 0 && inputNum < 365) {
browser.storage.local.set({
"daysInput": inputNum
}).then((res) => {
console.log("Successfully set daysInput")
}, (err) => {
console.error(`err setting daysInput: ${err}`)
})
}
} else {
console.log("is not in range")
}
})
document.getElementById("settingsButton").addEventListener("click", (event) => {
settingsPanelButtonClicked()
});
function settingsPanelButtonClicked() {
if (settingsPanelIsVisible) {
document.getElementById("settingsPanel").innerHTML = ``
settingsPanelIsVisible = false
return
}
settingsPanelIsVisible = true
getInfoForRequest().then((info) => {
document.getElementById("settingsPanel").innerHTML = `
<div style="padding-top: 0; padding-bottom: 0; padding-left: 0.8vh; padding-right: 0.8vh">
<hr style="padding: 0; margin: 0; margin-top: 0.4vh"/>
<table style="text-align: center; width: 100%">
<tr>
<td style="font-size: 0.8rem;">
Backend URL
</td>
</tr>
<tr>
<td style="width: 100%">
<input
type="text" id="backendURLInput"
style="font-size: 0.6rem; background-color: #464646; border: 1px solid grey; color: white; width: 100%"
value=${info.backendURL === "empty" ? "" : info.backendURL}
>
</td>
</tr>
<tr>
<td style="font-size: 0.8rem;">
API Key
</td>
</tr>
<tr>
<td style="width: 100%">
<input
type="text" id="apiKeyInput"
style="font-size: 0.6rem; background-color: #464646; border: 1px solid grey; color: white; width: 100%"
value=${info.apiKey === "empty" ? "" : info.apiKey}
>
</td>
</tr>
<tr>
<td style="float: left">
<span>
<button id="testBackendURL" style="font-size: 3.8vh; width: 14vh">
Test
</button>
</span>
<span id="testBackendStatus" style="font-size: 4vh;">
</span>
</td>
</tr>
</table>
</div>
`
document.getElementById("testBackendURL").addEventListener("click", (event) => {
const newURLString = document.getElementById("backendURLInput").value;
const apiKey = document.getElementById("apiKeyInput").value;
try {
const testURL = new URL(newURLString)
} catch (_) {
document.getElementById("testBackendStatus").textContent = "Nope"
return
}
console.log(`curl ${newURLString}/status API_KEY: ${apiKey}`)
fetch(`${newURLString}/status`, {
method: 'POST',
mode: 'cors',
headers: {
'API_KEY': apiKey
}
})
.then((res) => res.json())
.then((data) => JSON.parse(data))
.then((data) => {
if (data.status == "operational") {
document.getElementById("testBackendStatus").textContent = "Working :)"
setBackendURL(newURLString).then(() => {}, (err) => {
console.error(`failed to set backendURL: ${err}`)
})
setApiKey(apiKey).then(() => {}, (err) => {
console.error(`failed to set apiKey: ${err}`)
})
} else {
console.log("invalid response")
console.log(data)
document.getElementById("testBackendStatus").textContent = "Nope"
}
}, (err) => {
console.log("err response")
document.getElementById("testBackendStatus").textContent = "Nope"
});
});
})
}
function getInfoForRequest() {
return new Promise((resolve, reject) => {
getStorageVariable("backendURL").then((backendURL) => {
getStorageVariable("apiKey").then((apiKey) => {
getStorageVariable("daysInput").then((daysInput) => {
resolve({"backendURL": backendURL, "apiKey": apiKey, "daysInput": daysInput})
}, (err) => {
reject(`failed to get daysInput: ${err}`)
})
}, (err) => {
reject(`failed to get apiKey: ${err}`)
})
}, (err) => {
reject(`failed to get backendURL: ${err}`)
})
})
}
function setBackendURL(URL) {
return new Promise((resolve, reject) => {
browser.storage.local.set({
"backendURL": URL
}).then((res) => {
console.log("Successfully set backend URL")
resolve()
}, (err) => {
reject(err)
})
})
}
function setApiKey(apiKey) {
return new Promise((resolve, reject) => {
browser.storage.local.set({
"apiKey": apiKey
}).then((res) => {
console.log("Successfully set apiKey")
resolve()
}, (err) => {
reject(err)
})
})
}
function getStorageVariable(variable) {
return new Promise((resolve, reject) => {
browser.storage.local.get(variable).then(
(res) => {
console.log(`Retrieved: '${res[variable]}' type: ${typeof res} from get '${variable}'`)
resolve(res[variable])
}, (err) => {
reject(err)
}
)
})
}