-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpopup.js
731 lines (628 loc) · 28.1 KB
/
popup.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// const ip_port = '5.153.238.0:24'
const ip_port = '10.5.126.127:8080'
const Incogni_key_list = ["broker.title", "state", "broker.sensitivity", "broker.recurringTaskIntervalDays", "broker.avgResolutionTimeInDays",
"broker.complianceScore", "broker.createdAt", "broker.updatedAt", "recurringDate", "recurringCycles",
"createdAt", "updatedAt", "recurring"]
const DataSeal_key_list = ["brokerId", "brokerUrl", "createdAt", "submittedAt", "confirmedAt", "verifiedAt", "isStuck"]
const Optery_key_list = ["databroker.name", "databroker.exposure_confidence", "is_complete",
"is_pending", "plan", "tier", "removal_status", "exposure", "updated_at"]
const Kanary_key_list = ["site.domain", "status", "created_at", "updated_at", "last_submitted_at",
"latest_event.created_at", "latest_event.meta.failed", "latest_event.meta.reason", "google_search", "automated", "manually_added"]
var broker_data;
var stat_data;
var service;
var current_prolific_id;
var timestamp;
var fetch_data_time;
var valid_count;
var is_valid;
var task_1_completion_code;
var task_2_completion_code;
var subscription_data;
var send_data = {};
var error_data;
document.addEventListener('DOMContentLoaded', function() {
const userIdInput_1 = document.getElementById('prolificId_1');
const userIdInput_2 = document.getElementById('prolificId_2');
const errorElement_1 = document.getElementById('idError_1');
const errorElement_2 = document.getElementById('idError_2');
const verifyBotton = document.getElementById('verify');
const verifyResult = document.getElementById('verify_result');
const sendButton = document.getElementById('send');
const reportErrorButton = document.getElementById('error');
const sendErrorButton = document.getElementById('errorReport');
const projectIntro = document.getElementById("projectIntro");
const collBotton1 = document.getElementById("collBotton1");
const collBotton2 = document.getElementById("collBotton2");
const dataTableBotton = document.getElementById("dataTable");
const processButton = document.getElementById('processButton');
const inputField = document.getElementById('inputField');
var random_code = null;
window.onload = function() {
// Set pre-input Prolific ID into input box
userIdInput_1.value = localStorage.getItem('prolificIDValue') || '';
userIdInput_2.value = localStorage.getItem('prolificIDValue') || '';
current_prolific_id = localStorage.getItem('prolificIDValue') || '';
errorElement_1.textContent = userIdInput_1.value !== '' ? '' : 'Please input correct Prolific ID.';
errorElement_2.textContent = userIdInput_2.value !== '' ? '' : 'Please input correct Prolific ID.';
verifyBotton.disabled = userIdInput_1.value !== '' ? false : true;
sendButton.disabled = userIdInput_2.value !== '' ? false : true;
reportErrorButton.disabled = userIdInput_2.value !== '' ? false : true;
// Set task 1 state
document.getElementById("task1_state").textContent = localStorage.getItem('task1_state') || '(To be verified)';
document.getElementById("task1_state").style = localStorage.getItem('task1_state_style') || 'font-weight: bold; color: #f6db46;';
const curr_already_send = localStorage.getItem('already_send') || '0';
const curr_remaining_send = localStorage.getItem('remaining_send') || '4';
const curr_next_send_date = localStorage.getItem('next_send_date') || 'Unknown';
document.getElementById("task2_state").textContent = localStorage.getItem('task2_state') || '(Send: ' + curr_already_send + ', Remain: ' + curr_remaining_send + ', Next: ' + curr_next_send_date + ')';
document.getElementById("task2_state").style = localStorage.getItem('task2_state_style') || 'font-weight: bold; color: #f6db46;';
};
// Input Prolific ID in task 1 and verify
userIdInput_1.addEventListener('input', function() {
const userId = userIdInput_1.value.trim();
userIdInput_2.value = userId
current_prolific_id = userId;
// const isValid = userId.length > 0;
verifyBotton.disabled = userId.length > 0 ? false : true;
errorElement_1.textContent = userId.length > 0 ? '' : 'Please input correct Prolific ID.';
errorElement_2.textContent = userId.length > 0 ? '' : 'Please input correct Prolific ID.';
localStorage.setItem('prolificIDValue', userId);
});
// Input Prolific ID in task 2 and verify
userIdInput_2.addEventListener('input', function() {
const userId = userIdInput_2.value.trim();
userIdInput_1.value = userId
current_prolific_id = userId;
// const isValid = userId.length > 0;
sendButton.disabled = userId.length > 0 ? false : true;
reportErrorButton.disabled = userId.length > 0 ? false : true;
errorElement_1.textContent = userId.length > 0 ? '' : 'Please input correct Prolific ID.';
errorElement_2.textContent = userId.length > 0 ? '' : 'Please input correct Prolific ID.';
localStorage.setItem('prolificIDValue', userId);
});
// collapse project intro
projectIntro.addEventListener('click', function() {
this.classList.toggle("active");
var intro = document.getElementById("introContent");
if (intro.style.display === "block") {
intro.style.display = "none";
} else {
intro.style.display = "block";
}
});
// collapse task 1
collBotton1.addEventListener('click', function() {
this.classList.toggle("active");
var content1 = document.getElementById("task1Content");
if (content1.style.display === "block") {
content1.style.display = "none";
} else {
content1.style.display = "block";
}
});
// collapse task 2
collBotton2.addEventListener('click', function() {
this.classList.toggle("active");
var content2 = document.getElementById("task2Content");
if (content2.style.display === "block") {
content2.style.display = "none";
} else {
content2.style.display = "block";
}
});
// data table
dataTableBotton.addEventListener('click', function() {
this.classList.toggle("active");
var table = document.getElementById("dataTableContent");
if (table.style.display === "block") {
table.style.display = "none";
} else {
table.style.display = "block";
}
});
// Check the subsription status
verifyBotton.addEventListener('click', function() {
chrome.storage.local.get(['is_subscribe'], (result) => {
if (result.is_subscribe === true) {
if (random_code === null) {
random_code = Math.floor(Math.random() * (999 - 100 + 1)) + 100;
}
task_1_completion_code = current_prolific_id + '_' + random_code
sendSubscription();
}
if (result.is_subscribe === false) {
verifyResult.textContent = 'Failed to verify subscription.';
verifyResult.style = 'color: #FF003C; font-size: 18px;'
}
});
});
// Send Data
sendButton.addEventListener('click', function() {
sendData();
});
reportErrorButton.addEventListener('click', function() {
const div = document.getElementById('errorOption');
if (div.style.display === 'block') {
div.style.display = 'none'
}
else {
div.style.display = 'block';
}
document.getElementById('completion_code_2').textContent = ''
document.getElementById('result').textContent = ''
});
sendErrorButton.addEventListener('click', function() {
sendErrorData();
});
inputField.addEventListener('input', function() {
processButton.disabled = inputField.value === ''
});
});
// Display remove data on extension
document.addEventListener('DOMContentLoaded', function() {
const contentElement = document.getElementById('table-container');
const stat = document.getElementById('remove_stat');
const inputField = document.getElementById('inputField');
const processButton = document.getElementById('processButton');
const fetchDataTimeIndicator = document.getElementById('fetchDataTime');
chrome.storage.local.get(['service_flag', 'statData', 'fetchData', 'brokerData', 'removedData', 'blockedData', 'update_time'], (result) => {
// Incogni
if (result.service_flag === "Incogni") {
// Print stat data
if (result.statData) {
const temp_total_send = result.statData.progressSummary.sent;
const temp_completed = result.statData.progressSummary.completed;
const temp_inProgress = result.statData.progressSummary.inProgress;
const temp_suppressed = result.statData.suppressedBrokers;
const temp_savedminutes = result.statData.savedMinutes;
const temp_hours = Math.floor(temp_savedminutes / 60);
const temp_minutes = temp_savedminutes % 60;
stat.textContent = "Total send: " + temp_total_send + ", Completed: " + temp_completed +
", In progress: " + temp_inProgress + ", Suppressed: " + temp_suppressed +
", Saved time: " + temp_hours + "hours " + temp_minutes + "minutes";
} else {
stat.textContent = 'No statistics available.';
}
// Print removal progress as table
if (result.fetchData) {
const flattenedData = result.fetchData.map(item => flattenObject(item));
const filteredData = filterData(flattenedData, Incogni_key_list);
contentElement.appendChild(createHtmlTable(filteredData, Incogni_key_list));
broker_data = filteredData;
stat_data = result.statData;
service = "Incogni";
fetch_data_time = result.update_time;
valid_count = countValidObject(filteredData, 'broker.title');
is_valid = countValidObject(filteredData, 'broker.title') > filteredData.length * 0.8
const curr_update_time = result.update_time.replace('T', ' ').slice(0, 10)
fetchDataTimeIndicator.textContent = '(extracted at ' + curr_update_time + ')'
} else {
contentElement.innerHTML = "<p>No data available. Please refresh the page.<p>";
contentElement.style = "font-weight: bold; text-align: center; font-size: 20px; color: #FF003C";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DataSeal
else if (result.service_flag === "DataSeal") {
// Print stat data
if (result.statData) {
const temp_scan = result.statData.nScans;
const temp_found = result.statData.nRecordsFound
const temp_remove = result.statData.nRecordsRemoved
stat.textContent = "Number of scans: " + temp_scan + ", Total records found: " + temp_found +
", Total records removed: " + temp_remove;
} else {
stat.textContent = 'No statistics available.';
}
// Print removal progress as table
if (result.fetchData && result.brokerData) {
// Replace brokerId with broker name
result.fetchData.forEach(record => {
result.brokerData.forEach(brokerInfo => {
if (brokerInfo.id === record.brokerId) {
record.brokerId = brokerInfo.name
record.brokerUrl = brokerInfo.url
}
});
});
const filteredData = filterData(result.fetchData, DataSeal_key_list);
contentElement.appendChild(createHtmlTable(filteredData, DataSeal_key_list));
broker_data = filteredData;
stat_data = result.statData;
service = "DataSeal";
fetch_data_time = result.update_time;
valid_count = countValidObject(filteredData, 'brokerId');
is_valid = countValidObject(filteredData, 'brokerId') > filteredData.length * 0.8;
const curr_update_time = result.update_time.replace('T', ' ').slice(0, 10)
fetchDataTimeIndicator.textContent = '(extracted at ' + curr_update_time + ')'
} else {
contentElement.innerHTML = "<p>No data available. Please refresh the page.<p>";
contentElement.style = "font-weight: bold; text-align: center; font-size: 20px; color: #FF003C";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Optery
else if (result.service_flag === "Optery") {
if (result.statData) {
const temp_broker = result.statData.db_covered;
const temp_exposure = result.statData.exposure_matches;
const temp_notfound = result.statData.exposure_notfound;
const temp_removed = result.statData.protection_removed;
const temp_inprogress = result.statData.protection_in_progress;
const temp_pending = result.statData.protection_pending;
stat.textContent = "Total data brokers: " + temp_broker + ", Exposure found: " + temp_exposure +
", Exposure not found: " + temp_notfound + ", Removed: " + temp_removed +
", In progress: " + temp_inprogress + ", Pending: " + temp_pending;
} else {
stat.textContent = 'No statistics available.';
}
// Print removal progress as table
if (result.fetchData) {
const flattenedData = result.fetchData.map(item => flattenObject(item));
const filteredData = filterData(flattenedData, Optery_key_list);
contentElement.appendChild(createHtmlTable(filteredData, Optery_key_list));
broker_data = filteredData;
stat_data = result.statData;
service = "Optery";
fetch_data_time = result.update_time;
valid_count = countValidObject(filteredData, 'databroker.name');
is_valid = countValidObject(filteredData, 'databroker.name') > filteredData.length * 0.8;
const curr_update_time = result.update_time.replace('T', ' ').slice(0, 10)
fetchDataTimeIndicator.textContent = '(extracted at ' + curr_update_time + ')'
} else {
contentElement.innerHTML = "<p>No data available. Please refresh the page.<p>";
contentElement.style = "font-weight: bold; text-align: center; font-size: 20px; color: #FF003C";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Kanary
else if (result.service_flag === "Kanary") {
if (result.fetchData && result.removedData && result.blockedData) {
const temp_inprogress = result.fetchData.length;
const temp_removed = result.removedData.length;
const temp_blocked = result.blockedData.length;
stat.textContent = "In progress: " + temp_inprogress + ", Removed: " + temp_removed + ", Blocked: " + temp_blocked;
} else {
stat.textContent = 'No statistics available.';
}
// Print removal progress as table
if (result.fetchData) {
const flattenedFetchData = result.fetchData.map(item => flattenObject(item));
const flattenedRemovedData = result.removedData.map(item => flattenObject(item));
const flattenedBlockedData = result.blockedData.map(item => flattenObject(item));
const mergedData = flattenedFetchData.concat(flattenedRemovedData).concat(flattenedBlockedData);
const filteredData = filterData(mergedData, Kanary_key_list);
contentElement.appendChild(createHtmlTable(filteredData, Kanary_key_list));
broker_data = filteredData;
stat_data = {'inprogress': result.fetchData.length, 'removed': result.removedData.length, 'blocked': result.blockedData.length},
service = "Kanary";
fetch_data_time = result.update_time;
valid_count = countValidObject(filteredData, 'site.domain');
is_valid = countValidObject(filteredData, 'site.domain') > filteredData.length * 0.8;
const curr_update_time = result.update_time.replace('T', ' ').slice(0, 10)
fetchDataTimeIndicator.textContent = '(extracted at ' + curr_update_time + ')'
} else {
contentElement.innerHTML = "<p>No data available. Please refresh the page.<p>";
contentElement.style = "font-weight: bold; text-align: center; font-size: 20px; color: #FF003C";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Mozilla
else if (result.service_flag === "Mozilla") {
// Display block
document.getElementById('copyData').style.display = 'block';
// When user clikc process button, then extract data and display in table
processButton.addEventListener('click', function() {
// Extract data, and turn into json format
const extractJson = extractInfoToJSON(inputField.value);
inputField.value = ''
console.log(extractJson);
if (extractJson.hasOwnProperty("manuallyFixed") && extractJson.hasOwnProperty("autoRemoved") && extractJson.hasOwnProperty("inProgress")) {
const temp_manually = extractJson.manuallyFixed;
const temp_auto = extractJson.autoRemoved;
const temp_inProgress = extractJson.inProgress;
stat.textContent = "Auto removed: " + temp_auto + ", Manually fixed: " + temp_manually + ", In progress: " + temp_inProgress;
} else {
stat.textContent = 'No statistics available. Please try copy/paste again!';
}
// Print removal progress as table
if (extractJson.hasOwnProperty("exposures") && extractJson.exposures.length > 0) {
contentElement.innerHTML = "";
contentElement.style = "";
contentElement.appendChild(createHtmlTable(extractJson.exposures, ['dataBroker', 'status', 'dateOfExposure']));
broker_data = extractJson.exposures;
stat_data = {
manuallyFixed: extractJson.manuallyFixed,
autoRemoved: extractJson.autoRemoved,
inProgress: extractJson.inProgress,
},
service = "Mozilla";
fetch_data_time = result.update_time;
valid_count = countValidObject(extractJson.exposures, 'dataBroker');
is_valid = countValidObject(extractJson.exposures, 'dataBroker') > extractJson.exposures.length * 0.8;
const curr_update_time = result.update_time.replace('T', ' ').slice(0, 10)
fetchDataTimeIndicator.textContent = '(extracted at ' + curr_update_time + ')'
} else {
contentElement.innerHTML = "<p>No data available. Please try copy/paste again!<p>";
contentElement.style = "font-weight: bold; text-align: center; font-size: 20px; color: #FF003C";
}
});
// if (result.fetchData) {
// const temp = document.getElementById('mozillaResult');
// temp.innerHTML = result.fetchData;
// temp_button = temp.querySelector(".Button_button__iA3wi");
// var temp_result;
// if (temp_button) {
// temp_result = '<p>True</p>';
// temp_button.click();
// const updatedHtml = temp.innerHTML;
// temp.innerHTML = updatedHtml;
// }
// else {
// temp_result = '<p>False</p>';
// }
// }
}
});
});
// For mozilla monitor, extract json data from copy text
function extractInfoToJSON(data) {
const manuallyFixedRegex = /(\d+)(?:\r\n|\r|\n)Manually fixed/i;
const autoRemovedRegex = /(\d+)(?:\r\n|\r|\n)Auto-removed/i;
const inProgressRegex = /(\d+)(?:\r\n|\r|\n)In progress/i;
const manuallyFixedMatch = data.match(manuallyFixedRegex);
const autoRemovedMatch = data.match(autoRemovedRegex);
const inProgressMatch = data.match(inProgressRegex);
const manuallyFixed = manuallyFixedMatch ? parseInt(manuallyFixedMatch[1]) : 0;
const autoRemoved = autoRemovedMatch ? parseInt(autoRemovedMatch[1]) : 0;
const inProgress = inProgressMatch ? parseInt(inProgressMatch[1]) : 0;
const companyRegex = /Company\s*[\r\n]+(?!Date found|logo|Exposure type)([^\n]+)/gi;
const dateOfExposureRegex = /Date of the exposure\s*[\r\n]+([^\n]+)/gi;
const statusRegex = /Status\s*[\r\n]+(?!Company logo)([^\n]+)/gi;
let matches;
let companies = [];
let datesOfExposure = [];
let statuses = [];
while ((matches = companyRegex.exec(data)) !== null) {
companies.push(matches[1].trim());
}
while ((matches = dateOfExposureRegex.exec(data)) !== null) {
datesOfExposure.push(matches[1].trim());
}
while ((matches = statusRegex.exec(data)) !== null) {
statuses.push(matches[1].trim());
}
const result = {
manuallyFixed: manuallyFixed,
autoRemoved: autoRemoved,
inProgress: inProgress,
exposures: companies.map((company, index) => ({
dataBroker: company,
dateOfExposure: datesOfExposure[index],
status: statuses[index]
}))
};
return result;
}
// Flatten json data
function flattenObject(ob, parentPrefix = '') {
const toReturn = {};
for (const i in ob) {
if (!ob.hasOwnProperty(i)) continue;
const prefix = parentPrefix.length ? parentPrefix + '.' : '';
if ((typeof ob[i]) === 'object' && ob[i] !== null) {
Object.assign(toReturn, flattenObject(ob[i], prefix + i));
} else {
toReturn[prefix + i] = ob[i];
}
}
return toReturn;
}
// Filter the data by pre-define key list
function filterData(data, keys) {
return data.map(item => {
const newItem = {};
keys.forEach(key => {
if (item.hasOwnProperty(key)) {
newItem[key] = item[key];
}
});
return newItem;
});
}
// Use filtered data to create HTML table
function createHtmlTable(data, keys) {
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
const headerRow = document.createElement('tr');
// Create table header, and filter the key
keys.forEach(key => {
const th = document.createElement('th');
th.textContent = key;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
// Create table body
data.forEach(item => {
const row = document.createElement('tr');
keys.forEach(key => {
const td = document.createElement('td');
td.textContent = item.hasOwnProperty(key) ? item[key] : 'None';
row.appendChild(td);
});
tbody.appendChild(row);
});
table.appendChild(thead);
table.appendChild(tbody);
return table;
}
// Count how may object is valid in extracted data
function countValidObject(data, key) {
let validObject = 0;
if (data.length === 0) {
return validObject
}
if (data[0].hasOwnProperty(key)) {
for (let i = 0; i < data.length; i++) {
if (typeof data[i][key] === 'string') {
validObject++;
}
}
return validObject;
}
else {
return validObject;
}
}
function sendSubscription() {
subscription_data = {
"prolific_id": current_prolific_id,
'service': service,
"completion_code_1": task_1_completion_code,
"timestamp": new Date().toISOString()
}
fetch('http://' + ip_port, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription_data)
})
.then(response => {
if (response.ok) {
document.getElementById('verify_result').innerHTML = 'Successfully verify your subscription.<br>Your <u>Task 1 complection code</u> (also the <u>qualifying code for Task 2</u>) is:';
document.getElementById('verify_result').style = 'color: #88C100; font-size: 18px;';
document.getElementById("task1_state").textContent = '(Complete)';
document.getElementById("task1_state").style = 'font-weight: bold; color: #88C100;';
localStorage.setItem('task1_state', '(Complete)');
localStorage.setItem('task1_state_style', 'font-weight: bold; color: #88C100;');
return response.json();
} else {
throw new Error('Failed, please refresh the page and try again.');
}
})
.then(data => {
document.getElementById('completion_code_1').textContent = data.completion_code;
})
.catch(error => {
document.getElementById('verify_result').textContent = 'Failed to verify subscription.' + error;
document.getElementById('verify_result').style = 'color: #FF003C; font-size: 18px;';
document.getElementById('completion_code_1').textContent = '';
});
}
var random_code = null;
function sendData() {
if (is_valid === false) {
document.getElementById('result').textContent = 'Data invalid, please refresh the page and try again.';
document.getElementById('result').style = 'color: #FF003C'
}
else {
send_data = {
"broker_data": broker_data,
"stat_data": stat_data,
"service": service,
"prolific_id": current_prolific_id,
"timestamp": new Date().toISOString(),
"fetch_data_time": fetch_data_time,
"valid_count": valid_count,
"is_valid": is_valid
};
fetch('http://' + ip_port, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(send_data)
})
.then(response => {
if (response.ok) {
// document.getElementById('send').disabled = true;
return response.json();
} else {
throw new Error('Service result send failed, please refresh the page and try again.');
}
})
.then(data => {
curr_count = data.count;
curr_more_than_week = data.more_than_week;
curr_completion_code = data.completion_code
const next_send_date = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
if (curr_count < 4) {
if (curr_more_than_week === true) {
document.getElementById('result').innerHTML = 'Service result send successed.',
document.getElementById('result').style = 'color: #88C100'
document.getElementById("task2_state").textContent = '(Send: ' + curr_count + ', Remain: ' + (4 - curr_count) + ', Next: ' + next_send_date + ')';
document.getElementById("task2_state").style = 'font-weight: bold; color: #f6db46;';
localStorage.setItem('already_send', curr_count);
localStorage.setItem('remaining_send', (4 - curr_count));
localStorage.setItem('next_send_date', next_send_date);
}
else {
document.getElementById('result').textContent = 'Please do not send it too frequently, please send again on ' + next_send_date,
document.getElementById('result').style = 'color: #FF003C'
}
}
else if (curr_count === 4) {
document.getElementById('result').innerHTML = 'Service result send successed, thank you for your participation!<br>Your <u>Task 2 complection code</u> is:',
document.getElementById('result').style = 'color: #88C100'
document.getElementById('completion_code_2').textContent = curr_completion_code;
document.getElementById("task2_state").textContent = '(Complete)';
document.getElementById("task2_state").style = 'font-weight: bold; color: #78eb7c;';
localStorage.setItem('task2_state', '(Complete)');
localStorage.setItem('task2_state_style', 'font-weight: bold; color: #78eb7c;');
}
})
.catch(error => {
document.getElementById('result').textContent = error.message;
document.getElementById('result').style = 'color: #FF003C'
});
}
}
function sendErrorData() {
var radios = document.getElementsByName('option');
var selectedValue;
for (var radio of radios) {
if (radio.checked) {
selectedValue = radio.value;
break;
}
}
if (selectedValue) {
chrome.storage.local.get(['service_flag'], (result) => {
error_data = {
"error": selectedValue,
"service": service,
"prolific_id": current_prolific_id,
"timestamp": new Date().toISOString(),
"valid_count": valid_count,
"is_valid": is_valid
}
fetch('http://' + ip_port, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(error_data)
})
.then(response => {
if (response.ok) {
return response;
} else {
throw new Error('Error report send failed, please try again.');
}
})
.then(data => {
document.getElementById('result').textContent = 'Error report send successed, thank you for your feedback!';
document.getElementById('result').style = 'color: #88C100'
})
.catch(error => {
document.getElementById('result').textContent = 'Error report send failed: ' + error.message;
document.getElementById('result').style = 'color: #FF003C'
});
});
} else {
document.getElementById('result').textContent = 'Please select at least one option.';
document.getElementById('result').style = 'color: #FF003C'
}
}