Debian Codegraph @

public/js/list.js

raw symbols SCIP
1 /**
2 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
3 * Copyright (C) 2020-2025 Aleksey Andreev (liuch)
4 *
5 * Available at:
6 * https://github.com/liuch/dmarc-srg
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the Free
10 * Software Foundation, either version 3 of the License.
11 *
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 class ReportList {
22 constructor() {
23 this._page = null;
24 this._table = null;
25 this._scroll = null;
26 this._filter = null;
27 this._sort = { column: "begin_time", direction: "descent" };
28 this._element = document.getElementById("main-block");
29 this._element2 = document.getElementById("detail-block");
30 this._fetching = false;
31 this._filter_btn = null;
32 this._rep_counter = null;
33 this._cnt_updated = 0;
34 this._settings_dlg = null;
35 this._column_list = [
36 { name: "domain", content: "Domain", class: "fqdn" },
37 { name: "begin_time", content: "Date", sortable: true },
38 { name: "organization", content: "Reporting Organization", class: "orgname" },
39 { name: "report_id", content: "Report ID", class: "report-id" },
40 { name: "messages", content: "Messages" },
41 { name: "result", content: "Result" },
42 { name: "disposition", content: "Disposition" },
43 { name: "quarantined", content: "Quarantined" },
44 { name: "rejected", content: "Rejected" }
45 ];
46 }
47
48 display() {
49 this._make_page_container();
50 this._make_scroll_container();
51 this._make_table();
52 const t_el = this._table.element();
53 const b_el = this._make_toolbar().element();
54 b_el.setAriaControls(t_el);
55 this._scroll.append(t_el);
56 this._page.append(b_el, this._scroll);
57 this._element.append(this._page);
58 this._ensure_report_widget();
59 this._element2.appendChild(ReportWidget.instance().element());
60 ReportWidget.instance().hide();
61 this._table.focus();
62 }
63
64 update() {
65 this._filter = Common.getFilterFromURL(new URL(document.location));
66 this._update_table();
67 this._update_settings_button();
68 }
69
70 title() {
71 return "Report List";
72 }
73
74 onpopstate() {
75 if (!this._page) {
76 this.display();
77 this.update();
78 }
79 else {
80 if (!this._element.contains(this._page)) this._element.replaceChildren(this._page);
81 const f = Common.getFilterFromURL(new URL(document.location), this._filter);
82 if (f !== undefined) {
83 this._filter = f;
84 Status.instance().reset();
85 Status.instance().update({ page: "list" });
86 this._update_table();
87 this._update_settings_button();
88 }
89 }
90 this._ensure_report_widget();
91 if (this._table) {
92 this._table.focus();
93 }
94 }
95
96 _ensure_report_widget() {
97 let wdg = ReportWidget.instance();
98 wdg.hide();
99 let el = wdg.element();
100 if (!this._element2.contains(el)) {
101 this._element2.appendChild(el);
102 }
103 }
104
105 _update_settings_button() {
106 if (this._filter_btn) {
107 this._filter_btn.element().classList[ this._filter ? "add" : "remove" ]("active");
108 }
109 }
110
111 _make_page_container() {
112 const el = document.createElement("div");
113 el.classList.add("page-container");
114 this._page = el;
115 }
116
117 _make_scroll_container() {
118 const el = document.createElement("div");
119 el.tabIndex = -1;
120 el.classList.add("table-wrapper");
121 el.addEventListener("scroll", event => {
122 if (!this._fetching && el.scrollTop + el.clientHeight >= el.scrollHeight * 0.95) {
123 if (this._table.frames_count() === 0 || this._table.more()) {
124 this._fetch_list();
125 }
126 }
127 });
128 this._scroll = el;
129 }
130
131 _make_toolbar() {
132 const tb = new Toolbar("Report list toolbar");
133 this._filter_btn = new ToolbarButton({
134 title: "Filter",
135 content: "filter_icon",
136 onclick: () => this._display_settings_dialog()
137 });
138 const cb = new ToolbarButton({
139 title: "Columns",
140 content: "columns_icon",
141 onclick: () => this._display_columns_dialog()
142 });
143 this._rep_counter = new ReportCounter();
144 tb.appendItem(this._filter_btn).appendItem(cb).appendSpacer().appendItem(this._rep_counter.element());
145 return tb;
146 }
147
148 _make_table() {
149 this._table = new ReportTable({
150 class: "main-table report-list small-cards",
151 onclick: function(row) {
152 let data = row.userdata();
153 if (data)
154 this._display_report(data, row.id());
155 }.bind(this),
156 onsort: function(col) {
157 let dir = col.sorted() && "toggle" || "descent";
158 this._table.set_sorted(col.name(), dir);
159 this._sort.column = col.name();
160 this._sort.direction = col.sorted();
161 this.update();
162 }.bind(this),
163 onfocus: function(el) {
164 scroll_to_element(el, this._scroll);
165 }.bind(this)
166 });
167 this._column_list.forEach(col => {
168 let c = this._table.add_column(col);
169 if (c.name() === this._sort.column) {
170 c.sort(this._sort.direction);
171 }
172 });
173 this._get_visible_columns(true);
174 }
175
176 _update_table() {
177 this._table.clear();
178 let that = this;
179 let frcnt = -1;
180 let again = function() {
181 if (frcnt < that._table.frames_count() && that._scroll.clientHeight * 1.5 >= that._scroll.scrollHeight) {
182 frcnt = that._table.frames_count();
183 that._fetch_list().then(function(frame) {
184 if (frame && frame.more())
185 again();
186 else
187 that._table.focus();
188 });
189 }
190 else
191 that._table.focus();
192 }
193 again();
194 }
195
196 _display_report(data, id) {
197 if (data.domain && data.time && data.org && data.report_id) {
198 let url = new URL("report.php", document.location);
199 url.searchParams.set("org", data.org);
200 url.searchParams.set("time", data.time);
201 url.searchParams.set("domain", data.domain);
202 url.searchParams.set("report_id", data.report_id);
203 window.history.pushState({ from: "list" }, "", url);
204 let filter = this._filter && {
205 dkim: this._filter.dkim || "",
206 spf: this._filter.spf || "",
207 disposition: this._filter.disposition || ""
208 } || null;
209 ReportWidget.instance().show_report(data.domain, data.time, data.org, data.report_id, filter).then(() => {
210 if (!this._table.seen(id)) {
211 this._table.seen(id, true);
212 this._rep_counter.decrease();
213 }
214 }).catch(err => {
215 Common.displayError(err);
216 if (err.error_code && err.error_code === -2) {
217 LoginDialog.start();
218 }
219 });
220 Router.update_title(ReportWidget.instance().title());
221 ReportWidget.instance().focus();
222 }
223 }
224
225 _fetch_list() {
226 this._table.display_status("wait");
227 this._fetching = true;
228 const qlist = [ "reports" ];
229 const pos = this._table.last_row_index() + 1;
230 const now = Date.now();
231 if (!pos || now - this._cnt_updated >= 60000) {
232 qlist.push("count");
233 this._cnt_updated = now;
234 }
235
236 const uparams = new URLSearchParams();
237 uparams.set("list", qlist.join(","));
238 uparams.set("position", pos);
239 uparams.set("order", this._sort.column);
240 uparams.set("direction", this._sort.direction);
241 if (this._filter) {
242 for (let nm in this._filter) {
243 uparams.append("filter[]", nm + ":" + this._filter[nm]);
244 }
245 }
246
247 return window.fetch("list.php?" + uparams, {
248 method: "GET",
249 cache: "no-store",
250 headers: HTTP_HEADERS,
251 credentials: "same-origin"
252 }).then(resp => {
253 if (!resp.ok)
254 throw new Error("Failed to fetch the report list");
255 return resp.json();
256 }).then(data => {
257 this._table.display_status(null);
258 Common.checkResult(data);
259 let d = { more: data.more };
260 d.rows = data.reports.map(it => {
261 return new ReportTableRow(this._make_row_data(it));
262 });
263 let fr = new ITableFrame(d, pos);
264 this._table.add_frame(fr);
265 if (data.count) this._rep_counter.set(data.count);
266 return fr;
267 }).catch(err => {
268 Common.displayError(err);
269 this._table.display_status("error");
270 }).finally(() => {
271 this._fetching = false;
272 });
273 }
274
275 _make_row_data(d) {
276 let rd = {
277 cells: [],
278 userdata: { domain: d.domain, time: d.date.begin, org: d.org_name, report_id: d.report_id },
279 seen: d.seen && true || false
280 };
281 rd.cells.push({ content: d.domain, label: "Domain", class: "fqdn" });
282 let d1 = new Date(d.date.begin);
283 let d2 = new Date(d.date.end);
284 rd.cells.push({
285 content: date_range_to_string(d1, d2),
286 title: d1.toUIString(true) + " - " + d2.toUIString(true),
287 label: "Date"
288 });
289 rd.cells.push({ content: d.org_name, label: "Reporting Organization", class: "orgname" });
290 rd.cells.push({ content: d.report_id, label: "Report ID", class: "report-id" });
291 rd.cells.push({ content: Common.abbrNumber(d.messages, 1e6), label: "Messages" });
292 rd.cells.push(new ResultColumn({ dkim_align: d.dkim_align, spf_align: d.spf_align }, { label: "Result" }));
293 rd.cells.push(new DispositionColumn({
294 none: d.messages - d.rejected - d.quarantined,
295 rejected: d.rejected,
296 quarantined: d.quarantined
297 }, { label: "Disposition" }));
298 rd.cells.push(new FailsColumn(d.quarantined, { label: "Quarantined" }));
299 rd.cells.push(new FailsColumn(d.rejected, { label: "Rejected" }));
300 return rd;
301 }
302
303 _display_settings_dialog() {
304 let dlg = this._settings_dlg;
305 if (!this._settings_dlg) {
306 dlg = new ReportListFilterDialog({ filter: this._filter });
307 this._settings_dlg = dlg;
308 }
309 this._element.append(dlg.element());
310 dlg.show().then(d => {
311 if (!d) return;
312 const url = new URL(document.location);
313 url.searchParams.delete("filter[]");
314 for (const k in d) {
315 if (d[k]) url.searchParams.append("filter[]", `${k}:${d[k]}`);
316 }
317 window.history.replaceState(null, "", url);
318 const f = Common.getFilterFromURL(url, this._filter);
319 if (f !== undefined) {
320 this._filter = f;
321 Status.instance().reset();
322 Status.instance().update({ page: "list" });
323 this._update_table();
324 this._update_settings_button();
325 }
326
327 }).finally(() => {
328 this._table.focus();
329 });
330 }
331
332 _get_visible_columns(update) {
333 let names = null;
334 try {
335 names = JSON.parse(window.localStorage.getItem("reportListColumns"));
336 } catch (err) {
337 }
338 let res = null;
339 if (Array.isArray(names)) {
340 res = names.filter(name => this._column_list.find(c => (c.name === name)));
341 }
342 if (!res || !res.length) res = [ "domain", "begin_time", "organization", "messages", "result", "disposition" ];
343 if (update) {
344 this._table.set_columns_visible(this._column_list.reduce((list, col, idx) => {
345 if (res.includes(col.name)) list.push(idx);
346 return list;
347 }, []));
348 }
349 return res;
350 }
351
352 _save_visible_columns (columns) {
353 try {
354 window.localStorage.setItem("reportListColumns", JSON.stringify(columns));
355 } catch (err) {
356 Notification.add({ text: "Unable to save the column set", type: "error" });
357 }
358 }
359
360 _display_columns_dialog() {
361 const dlg = new ReportListColumnsDialog({ columns: this._column_list, checked: this._get_visible_columns(false) });
362 this._element.append(dlg.element())
363 dlg.show().then(d => {
364 if (!d) return;
365 this._save_visible_columns(d);
366 this._get_visible_columns(true);
367 }).finally(() => {
368 dlg.element().remove();
369 this._table.focus();
370 });
371 }
372 }
373
374 class ReportCounter {
375 constructor() {
376 this._total = null;
377 this._unread = null;
378 this._element = null;
379 this._total_el = null;
380 this._unread_el = null;
381 }
382
383 set(data) {
384 this._total = data.total;
385 this._unread = data.unread;
386 if (this._element) this._update_element();
387 }
388
389 decrease() {
390 --this._unread;
391 if (this._element) this._update_element();
392 }
393
394 element() {
395 if (!this._element) {
396 this._element = document.createElement("span");
397 this._total_el = document.createElement("strong");
398 this._unread_el = document.createElement("strong");
399 this._update_element();
400 this._element.append("Unread: ", this._unread_el, " of ", this._total_el);
401 }
402 return this._element;
403 }
404
405 _update_element() {
406 this._total_el.textContent = this._total !== null ? this._total : '-';
407 this._unread_el.textContent = this._unread !== null ? this._unread : '-';
408 }
409 }
410
411 class ReportTable extends ITable {
412 seen(row_id, flag) {
413 let row = super._get_row(row_id);
414 if (row) {
415 if (flag === undefined)
416 return row.seen();
417 row.seen(flag);
418 }
419 }
420 }
421
422 class ReportTableRow extends ITableRow {
423 constructor(data) {
424 super(data);
425 this._seen = data.seen && true || false;
426 }
427
428 element() {
429 if (!this._element) {
430 super.element();
431 this._update_seen_element();
432 }
433 return this._element;
434 }
435
436 seen(flag) {
437 if (flag === undefined)
438 return this._seen;
439
440 this._seen = flag && true || false;
441 if (this._element)
442 this._update_seen_element();
443 }
444
445 _update_seen_element() {
446 if (this._seen)
447 this._element.classList.remove("unseen");
448 else
449 this._element.classList.add("unseen");
450 }
451 }
452
453 class ResultColumn extends ITableCell {
454 value(target) {
455 if (target === "dom") {
456 let d = this._content;
457 let fr = document.createDocumentFragment();
458 [ [ "dkim_align", "DKIM" ], [ "spf_align", "SPF" ] ].forEach(ai => {
459 const align = d[ai[0]];
460 if (align) {
461 if (![ "fail", "unknown" ].reduce((cnt, ares) => {
462 if (align[ares]) {
463 const val = Common.abbrNumber(align[ares]);
464 fr.append(Common.createReportResultElement(ai[1], ares, val))
465 ++cnt;
466 }
467 return cnt;
468 }, 0)) {
469 fr.append(Common.createReportResultElement(ai[1], "pass"));
470 }
471 }
472 });
473 return fr;
474 }
475 return super.value(target);
476 }
477 }
478
479 class DispositionColumn extends ITableCell {
480 value(target) {
481 if (target === "dom") {
482 const fr = document.createDocumentFragment();
483 const d = this._content;
484 [ [ "none", "None", "pass" ], [ "quarantined", "Quar", "fail" ], [ "rejected", "Rej", "fail" ] ].forEach(it => {
485 if (d[it[0]]) fr.append(Common.createReportResultElement(it[1], it[2], Common.abbrNumber(d[it[0]])));
486 });
487 return fr;
488 }
489 return super.value(target);
490 }
491 }
492
493 class ColoredIntColumn extends ITableCell {
494 _make_colored_int_element(value, factor) {
495 const el = document.createElement("span");
496 factor *= value;
497 if (factor) el.classList.add("report-result-" + (factor > 0 ? "pass" : "fail"));
498 el.append(Common.abbrNumber(value, 1e6));
499 return el;
500 }
501 }
502
503 class FailsColumn extends ColoredIntColumn {
504 value(target) {
505 if (target !== "dom") return super.value(target);
506 return this._make_colored_int_element(this._content, -1);
507 }
508 }
509
510 class ReportListFilterDialog extends ReportFilterDialog {
511 constructor(params) {
512 params.title = "Report list filter";
513 params.item_list = [ "domain", "month", "organization", "dkim", "spf", "disposition", "status" ];
514 super(params);
515 }
516
517 _fetch_data() {
518 this._enable_ui(false);
519 this.display_status("wait", "Getting data...");
520 window.fetch("list.php?list=filters", {
521 method: "GET",
522 cache: "no-store",
523 headers: HTTP_HEADERS,
524 credentials: "same-origin"
525 }).then(resp => {
526 if (!resp.ok) throw new Error("Failed to fetch the filter list");
527 return resp.json();
528 }).then(data => {
529 Common.checkResult(data);
530 this._data.loaded_filters = data.filters;
531 this._update_ui();
532 this._enable_ui(true);
533 }).catch(err => {
534 Common.displayError(err);
535 this.display_status("error", err.message);
536 }).finally(() => {
537 this.display_status("wait", null);
538 });
539 }
540 }
541
542 class ReportListColumnsDialog extends ModalDialog {
543 constructor(params) {
544 super({ title: "Columns", buttons: [ "apply", "close" ] });
545 this._columns = params.columns;
546 this._checked = params.checked;
547 }
548
549 element() {
550 if (!this._element) {
551 super.element();
552 const fs = document.createElement("fieldset");
553 this._content.replaceWith(fs);
554 fs.classList.add("vertical-content", "round-border");
555 fs.appendChild(document.createElement("legend")).textContent = "Check visible columns";
556 this._columns.forEach(ci => {
557 fs.append(this._make_column_checkbox(ci.name, ci.content, this._checked.includes(ci.name)));
558 });
559 fs.addEventListener("change", event => {
560 this._buttons[1].disabled = !fs.querySelector("input[type=checkbox]:checked");
561 });
562 fs.dispatchEvent(new Event("change"));
563 this._content = fs;
564 }
565 return this._element;
566 }
567
568 _submit() {
569 this._result = [];
570 for (const chb of this._content.querySelectorAll("input[type=checkbox]")) {
571 if (chb.checked) this._result.push(chb.name);
572 }
573 this.hide();
574 }
575
576 _make_column_checkbox(name, title, checked) {
577 const lb = document.createElement("label");
578 const cb = lb.appendChild(document.createElement("input"));
579 cb.type = "checkbox";
580 cb.name = name;
581 if (checked) cb.checked = true;
582 lb.append(title);
583 return lb;
584 }
585 }