-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpopup_menu_bundle_save.js
626 lines (516 loc) · 23.1 KB
/
popup_menu_bundle_save.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
{/* j-Lawyer Thunderbird Extension - saves Messages to j-Lawyer Server Cases.
Copyright (C) 2023, Maximilian Steinert
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */}
// ************************* ZUORDNEN DIALOG *************************
let currentSelectedCase = null; // Speichert den aktuell ausgewählten Case
let selectedIndex = -1; // Tastaturnavigation durch Suchergebnisse
let currentMessageToSaveID = null; // Speichert die ID der Nachricht, die gespeichert werden soll
let caseFolders = {}; // Speichert die Ordner des aktuell ausgewählten Cases
let selectedCaseFolderID = null; // Speichert den aktuell ausgewählten Ordner des aktuell ausgewählten Cases
let emailTemplatesNames = {}; // Speichert die Email-Templates
document.addEventListener("DOMContentLoaded", async function () {
const recommendCaseButton = document.getElementById("recommendCaseButton");
const feedback = document.getElementById("feedback");
const customizableLabel = document.getElementById("customizableLabel");
const updateDataButton = document.getElementById("updateDataButton");
const progressBar = document.getElementById("progressBar");
await fillTagsList();
// Setzt den Fokus auf das Suchfeld
document.getElementById("searchInput").focus();
// Überprüfen, ob der Code heute bereits ausgeführt wurde
const today = new Date().toISOString().split('T')[0];
const lastUpdate = await browser.storage.local.get("lastUpdate");
if (lastUpdate.lastUpdate !== today) {
updateData(feedback, progressBar);
logActivity("sendEmailToServer", "Daten aktualisiert");
}
// Code für den recommendCaseButton
if (recommendCaseButton && customizableLabel) {
recommendCaseButton.addEventListener("click", function () {
if (!currentSelectedCase) {
feedback.textContent = "Kein passendes Aktenzeichen gefunden!";
feedback.style.color = "red";
return;
}
browser.storage.local.get(["username", "password", "serverAddress"]).then(result => {
browser.runtime.sendMessage({
type: "case",
source: "popup_menu_bundle_save",
content: currentSelectedCase.fileNumber,
selectedCaseFolderID: selectedCaseFolderID,
username: result.username,
password: result.password,
serverAddress: result.serverAddress
});
// Setzt Feedback zurück, während auf eine Antwort gewartet wird
feedback.textContent = "Speichern...";
feedback.style.color = "blue";
});
feedback.textContent = "An empfohlene Akte gesendet!";
feedback.style.color = "green";
});
}
// Speichern der ausgewählten Etiketten in "selectedTags"
const tagsSelect = document.getElementById("tagsSelect");
let selectedTags = [];
tagsSelect.addEventListener("change", function () {
selectedTags = Array.from(tagsSelect.selectedOptions).map(option => option.value);
console.log("Ausgewählte Tags:", selectedTags);
browser.storage.local.set({
selectedTags: selectedTags
});
});
// Event Listener für den "Daten aktualisieren" Button
if (updateDataButton) {
updateDataButton.addEventListener("click", async function () {
updateData(feedback, progressBar);
});
}
// Code, um die options.html in einem neuen Tab zu öffnen
const settingsButton = document.getElementById("settingsButton");
if (settingsButton) {
settingsButton.addEventListener("click", function () {
browser.tabs.create({ url: "options.html" });
});
}
});
// Hört auf Antworten vom Hintergrund-Skript background.js
browser.runtime.onMessage.addListener((message) => {
const feedback = document.getElementById("feedback");
if (message.type === "success") {
feedback.textContent = "Erfolgreich gesendet!";
feedback.style.color = "green";
} else if (message.type === "error") {
feedback.textContent = "Fehler: " + message.content;
feedback.style.color = "red";
}
});
// Event-Listener für die Tastaturnavigation durch Suchergebnisse
document.addEventListener("keydown", function (event) {
const resultsElements = document.querySelectorAll(".resultItem");
if (resultsElements.length === 0) return;
if (event.key === "ArrowDown") {
if (selectedIndex >= 0) {
resultsElements[selectedIndex].classList.remove("selected");
}
selectedIndex = (selectedIndex + 1) % resultsElements.length;
resultsElements[selectedIndex].classList.add("selected");
} else if (event.key === "ArrowUp") {
if (selectedIndex >= 0) {
resultsElements[selectedIndex].classList.remove("selected");
}
selectedIndex = (selectedIndex - 1 + resultsElements.length) % resultsElements.length;
resultsElements[selectedIndex].classList.add("selected");
} else if (event.key === "Enter" && selectedIndex >= 0) {
resultsElements[selectedIndex].click();
}
});
function getCasesFromSelection(username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v1/cases/list';
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
// headers.append('Authorization', 'Basic ' + btoa('' + username + ':' + password + ''));
headers.append('Content-Type', 'application/json');
return fetch(url, {
method: 'GET',
headers: headers,
timeOut: 10000
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
});
}
async function getTags(username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v7/configuration/optiongroups/document.tags';
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
// headers.append('Authorization', 'Basic ' + btoa('' + username + ':' + password + ''));
headers.append('Content-Type', 'application/json');
return fetch(url, {
method: 'GET',
headers: headers
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const valuesArray = data.map(item => item.value);
console.log("Tags heruntergeladen: " + valuesArray);
browser.storage.local.set({ 'documentTags': valuesArray });
return valuesArray;
});
}
// Event-Listener für die Suche
document.getElementById("searchInput").addEventListener("input", function() {
const query = this.value.trim();
if (query) {
searchCases(query);
} else {
document.getElementById("resultsList").textContent = "";
}
});
// Funktion zum Suchen von Fällen
async function searchCases(query) {
document.getElementById("resultsList").style.display = "block";
let storedData = await browser.storage.local.get("cases");
let casesArray = storedData.cases;
let loginData = await browser.storage.local.get(["username", "password", "serverAddress"]);
query = query.toUpperCase();
let results = casesArray.filter(item =>
item.name.toUpperCase().includes(query) ||
item.fileNumber.toUpperCase().includes(query) ||
(item.reason && item.reason.toUpperCase().includes(query)) // Neue Bedingung für reason
);
// Ergebnisse bewerten und sortieren basierend auf Übereinstimmungslänge
results = results.map(item => {
let nameMatchLength = getConsecutiveMatchCount(item.name.toUpperCase(), query);
let fileNumberMatchLength = getConsecutiveMatchCount(item.fileNumber.toUpperCase(), query);
let reasonMatchLength = item.reason ?
getConsecutiveMatchCount(item.reason.toUpperCase(), query) : 0;
return {
...item,
matchLength: Math.max(nameMatchLength, fileNumberMatchLength, reasonMatchLength)
};
}).filter(item => item.matchLength > 0)
.sort((a, b) => b.matchLength - a.matchLength);
const resultsListElement = document.getElementById("resultsList");
while (resultsListElement.firstChild) {
resultsListElement.removeChild(resultsListElement.firstChild);
}
results.forEach(item => {
const div = document.createElement("div");
div.className = "resultItem";
div.setAttribute("data-id", item.id);
div.textContent = `${item.name} (${item.fileNumber})`;
if (item.reason) {
div.textContent += ` - ${item.reason}`;
}
resultsListElement.appendChild(div);
});
// Event Handler für Suchergebnisse
document.querySelectorAll(".resultItem").forEach(item => {
item.addEventListener("click", async function() {
currentSelectedCase = {
id: this.getAttribute("data-id"),
name: this.textContent.split(" (")[0],
fileNumber: this.textContent.split("(")[1].split(")")[0],
reason: item.getAttribute("data-tooltip")
};
caseMetaData = await getCaseMetaData(currentSelectedCase.id, loginData.username, loginData.password, loginData.serverAddress);
caseFolders = await getCaseFolders(currentSelectedCase.id, loginData.username, loginData.password, loginData.serverAddress);
console.log("caseFolders:", caseFolders);
displayTreeStructure(caseFolders);
document.getElementById("resultsList").style.display = "none";
// Label aktualisieren
const customizableLabel = document.getElementById("customizableLabel");
customizableLabel.textContent = `${currentSelectedCase.fileNumber}: ${currentSelectedCase.name} (${caseMetaData.reason} - ${caseMetaData.lawyer})`;
});
});
}
function getConsecutiveMatchCount(str, query) {
let count = 0;
let maxCount = 0;
for (let i = 0, j = 0; i < str.length; i++) {
if (str[i] === query[j]) {
count++;
j++;
if (count > maxCount) {
maxCount = count;
}
} else {
count = 0;
j = 0;
}
}
return maxCount;
}
// Füllen der Tagsliste
async function fillTagsList() {
try {
const result = await browser.storage.local.get("documentTags");
const tagsSelect = document.getElementById("tagsSelect");
// Funktion, um zu prüfen, ob ein Tag bereits in der Liste vorhanden ist
function isTagInList(tag) {
for (let i = 0; i < tagsSelect.options.length; i++) {
if (tagsSelect.options[i].value === tag) {
return true;
}
}
return false;
}
if (result.documentTags && result.documentTags.length > 0) {
const sortedTags = result.documentTags.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); // Tags alphabetisch sortieren (unabhängig von Groß- und Kleinschreibung)
sortedTags.forEach(tag => {
// Nur hinzufügen, wenn der Tag noch nicht in der Liste ist
if (!isTagInList(tag)) {
const option = document.createElement("option");
option.value = tag;
option.text = tag;
tagsSelect.appendChild(option);
}
});
}
} catch (error) {
console.error("Fehler beim Befüllen der Tags-Liste:", error);
}
}
async function getCaseMetaData(caseId, username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v1/cases/' + caseId;
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
// headers.append('Authorization', 'Basic ' + btoa('' + username + ':' + password + ''));
headers.append('Content-Type', 'application/json');
return fetch(url, {
method: 'GET',
headers: headers
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
let extractedData = {};
if ('reason' in data && data.reason !== null) {
extractedData.reason = data.reason;
}
if ('lawyer' in data && data.lawyer !== null) {
extractedData.lawyer = data.lawyer;
}
extractedData;
return extractedData;
});
}
async function getCaseFolders(caseId, username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v3/cases/' + caseId + '/folders';
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
// headers.append('Authorization', 'Basic ' + btoa('' + username + ':' + password + ''));
headers.append('Content-Type', 'application/json');
return fetch(url, {
method: 'GET',
headers: headers
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log("Folders des Case " + caseId + " heruntergeladen: ", data);
return data;
});
}
// Funktion zum Erstellen eines Ordnerbaums einer Akte
function createTreeElement(obj) {
if (!obj) return null; // Behandlung von null-Werten
const element = document.createElement('div');
element.className = 'treeItem';
element.textContent = obj.name;
element.style.paddingLeft = '20px';
element.style.cursor = 'pointer';
element.onclick = function(event) {
// Verhindern, dass das Klick-Event sich nach oben durch den Baum fortpflanzt
event.stopPropagation();
// Entfernen der Auswahl von allen anderen Elementen
const selectedElements = document.querySelectorAll('.treeItem.selectedItem');
selectedElements.forEach(el => el.classList.remove('selectedItem'));
// Hinzufügen der Auswahl zum aktuellen Element
this.classList.add('selectedItem');
selectedCaseFolderID = obj.id;
console.log("Name des ausgewählten Ordners: " + obj.name);
console.log("Id des ausgewählten Ordners: " + selectedCaseFolderID);
};
if (obj.children && obj.children.length > 0) {
// Sortiert alphabetisch nach dem Namen
obj.children.sort((a, b) => a.name.localeCompare(b.name));
obj.children.forEach(child => {
const childElement = createTreeElement(child);
if (childElement) {
element.appendChild(childElement);
}
});
}
return element;
}
function displayTreeStructure(folderData) {
// Überprüfen Sie, ob folderData nicht null ist
if (!folderData) {
console.log("Keine Folder-Daten vorhanden.");
return;
}
const treeRoot = createTreeElement(folderData);
const treeContainer = document.getElementById('treeContainer');
if (treeContainer) {
treeContainer.innerHTML = ''; // Bestehenden Inhalt löschen
treeContainer.appendChild(treeRoot);
}
}
async function getCalendars(username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v4/calendars/list/'+ username;
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
headers.append('Content-Type', 'application/json');
try {
const response = await fetch(url, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
data.forEach(calendar => {
console.log('Kalender ID:', calendar.id);
console.log('Anzeigename: (displayName)', calendar.displayName);
console.log('Hintergrund:', calendar.background);
console.log('Cloud-Host:', calendar.cloudHost);
console.log('Cloud-Pfad:', calendar.cloudPath);
console.log('Cloud-Port:', calendar.cloudPort);
console.log('Cloud-SSL:', calendar.cloudSsl);
console.log('Ereignistyp: (eventType - FOLLOWUP, RESPITE, EVENT)', calendar.eventType);
console.log('Href:', calendar.href);
console.log('-----------------------------------');
});
return data;
} catch (error) {
console.error('Fehler beim Abrufen der Kalender:', error);
}
}
async function getUsers(username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v6/security/users';
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
headers.append('Content-Type', 'application/json');
try {
const response = await fetch(url, {
method: 'GET',
headers: headers,
timeOut: 10000
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fehler beim Abrufen der User:', error);
}
}
function getEmailTemplates(username, password, serverAddress) {
const url = serverAddress + '/j-lawyer-io/rest/v6/templates/email';
const headers = new Headers();
const loginBase64Encoded = btoa(unescape(encodeURIComponent(username + ':' + password)));
headers.append('Authorization', 'Basic ' + loginBase64Encoded);
headers.append('Content-Type', 'application/json');
return fetch(url, {
method: 'GET',
headers: headers
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
});
}
// Funktion zum Aktualisieren der Daten
async function updateData(feedback, progressBar) {
progressBar.value = 0;
progressBar.style.display = "block";
try {
const { username, password, serverAddress } = await browser.storage.local.get(["username", "password", "serverAddress"]);
feedback.textContent = "Daten werden aktualisiert...";
feedback.style.color = "blue";
let tasksCompleted = 0;
const totalTasks = 5;
function updateProgress() {
tasksCompleted++;
progressBar.value = (tasksCompleted / totalTasks) * 100;
if (tasksCompleted === totalTasks) {
feedback.textContent = "Daten aktualisiert!";
feedback.style.color = "green";
const today = new Date().toISOString().split('T')[0];
browser.storage.local.set({ lastUpdate: today });
}
}
// Alle asynchronen Aufgaben parallel ausführen
await Promise.all([
(async () => {
await getTags(username, password, serverAddress);
fillTagsList();
updateProgress();
})(),
(async () => {
const casesRaw = await getCases(username, password, serverAddress);
await browser.storage.local.set({ cases: casesRaw });
console.log("Cases heruntergeladen: " + casesRaw);
updateProgress();
})(),
(async () => {
const calendarsRaw = await getCalendars(username, password, serverAddress);
await browser.storage.local.set({ calendars: calendarsRaw });
// Kalenderdaten filtern und speichern
const followUpCalendars = calendarsRaw.filter(calendar => calendar.eventType === 'FOLLOWUP')
.map(calendar => ({ id: calendar.id, displayName: calendar.displayName }));
const respiteCalendars = calendarsRaw.filter(calendar => calendar.eventType === 'RESPITE')
.map(calendar => ({ id: calendar.id, displayName: calendar.displayName }));
const eventCalendars = calendarsRaw.filter(calendar => calendar.eventType === 'EVENT')
.map(calendar => ({ id: calendar.id, displayName: calendar.displayName }));
await browser.storage.local.set({
followUpCalendars,
respiteCalendars,
eventCalendars
});
console.log("Kalender heruntergeladen: " + calendarsRaw);
updateProgress();
})(),
(async () => {
const emailTemplates = (await getEmailTemplates(username, password, serverAddress))
.map((item, index) => ({ id: index + 1, name: item.name }))
.sort((a, b) => a.name.localeCompare(b.name));
await browser.storage.local.set({ emailTemplates, emailTemplatesNames: emailTemplates });
console.log("E-Mail-Vorlagen: ", emailTemplates);
updateProgress();
})(),
(async () => {
const users = (await getUsers(username, password, serverAddress)).filter(user => user.displayName);
await browser.storage.local.set({ users: users.map(user => user.displayName) });
console.log("Benutzer heruntergeladen: ", users);
updateProgress();
})()
]);
} catch (error) {
console.error("Error during updateData:", error);
feedback.textContent = "Fehler: " + error.message;
feedback.style.color = "red";
}
}
async function logActivity(action, details) {
const timestamp = new Date().toISOString();
const logEntry = { timestamp, action, details };
let activityLog = await browser.storage.local.get("activityLog");
activityLog = activityLog.activityLog || [];
activityLog.push(logEntry);
await browser.storage.local.set({ activityLog });
}