Debian Codegraph @

public/js/common.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 const HTTP_HEADERS = {
22 "Accept": "application/json"
23 };
24
25 const HTTP_HEADERS_POST = {
26 "Content-Type": "application/json"
27 };
28
29 function set_wait_status(el, text) {
30 const wait = document.createElement("div");
31 wait.classList.add("wait-message");
32 wait.append(text || "Getting data...");
33 if (el) el.replaceChildren(wait);
34 return wait;
35 }
36
37 function set_error_status(el, text) {
38 const err = document.createElement("div");
39 err.classList.add("error-message");
40 err.append(text || "Error!");
41 if (el) el.replaceChildren(err);
42 return err;
43 }
44
45 function date_range_to_string(d1, d2) {
46 let s1 = d1.toISOString().substr(0, 10);
47 let s2 = d2.toISOString().substr(0, 10);
48 if (s1 !== s2) {
49 let d3 = new Date(d2);
50 d3.setSeconds(d3.getSeconds() - 1);
51 if (s1 !== d3.toISOString().substr(0, 10))
52 s1 += " - " + s2;
53 }
54 return s1;
55 }
56
57 function scroll_to_element(element, container) { // because scrollIntoView is poorly supported by browsers
58 let diff = null;
59 let e_rect = element.getBoundingClientRect();
60 let c_rect = container.getBoundingClientRect();
61 let height = Math.min(e_rect.height, 64);
62 if (e_rect.top < c_rect.top + height * 2) {
63 diff = e_rect.top - c_rect.top - height * 2;
64 }
65 else if (e_rect.bottom > c_rect.bottom - height) {
66 diff = e_rect.bottom - c_rect.bottom + height;
67 }
68 if (diff) {
69 container.scrollBy(0, diff);
70 }
71 }
72
73 function bytes2size(bytes) {
74 if (!bytes) {
75 return "0 bytes";
76 }
77 const k = 1024;
78 const sizes = [ 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ];
79 const i = Math.floor(Math.log(bytes) / Math.log(k));
80 return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
81 }
82
83 class Common {
84 static initAriaMethods() {
85 if (HTMLElement.idSequenceValue === undefined) HTMLElement.idSequenceValue = 0;
86 if (!HTMLElement.prototype.getId) {
87 HTMLElement.prototype.getId = function() {
88 if (!this.id) this.id = `id-${++HTMLElement.idSequenceValue}`;
89 return this.id;
90 };
91 }
92 if (!HTMLElement.prototype.setAriaControls) {
93 HTMLElement.prototype.setAriaControls = function(element) {
94 this.setAttribute("aria-controls", element.getId());
95 };
96 }
97 if (!HTMLElement.prototype.setAriaLabelledBy) {
98 HTMLElement.prototype.setAriaLabelledBy = function(element) {
99 this.setAttribute("aria-labelledby", element.getId());
100 };
101 }
102 }
103
104 static tuneDateTimeOutput(mode) {
105 Date.prototype.outputMode = mode;
106 if (!Date.prototype.toUIString) {
107 Date.prototype.toUIString = function(prefer_utc) {
108 if (this.outputMode === "local" || (this.outputMode === "auto" && !prefer_utc)) {
109 return this.toLocaleString();
110 }
111 return this.toLocaleString(undefined, { timeZone: 'UTC', timeZoneName: 'short' });
112 };
113 }
114 if (!Date.prototype.toUIDateString) {
115 Date.prototype.toUIDateString = function(prefer_utc) {
116 if (this.outputMode === "local" || (this.outputMode === "auto" && !prefer_utc)) {
117 return this.toLocaleDateString(
118 undefined,
119 { year:"numeric", month:"short", day:"numeric" }
120 );
121 }
122 return this.toLocaleDateString(
123 undefined,
124 { timeZone:"UTC", year:"numeric", month:"short", day:"numeric" }
125 );
126 };
127 }
128 }
129
130 static makeIpElement(ip) {
131 let url = null;
132 let type = ip.includes(":") && 6 || 4;
133 switch (type) {
134 case 4:
135 url = Common.ipv4_url;
136 break;
137 case 6:
138 url = Common.ipv6_url;
139 break;
140 }
141 let tn = document.createTextNode(ip);
142 if (url) {
143 const r = /^(!*)(.+)$/.exec(url);
144 if (r && r[1].length <= 2) {
145 url = r[2].replace("{$ip}", ip).replace("{$eip}", encodeURIComponent(ip));
146 let el = document.createElement("a");
147 el.setAttribute("href", url);
148 if (r[1].length == 1) {
149 el.target = "ip-info";
150 } else if (r[1].length == 2) {
151 el.target = "_blank";
152 }
153 el.appendChild(tn).title = "IP address information";
154 return el;
155 }
156 }
157 return tn;
158 }
159
160 static createReportResultElement(name, result, value) {
161 const span = document.createElement("span");
162 if (value) name += ": " + value;
163 span.textContent = name;
164 const atitle = [ result, value ].reduce((res, it, idx) => {
165 if (it && (!idx || it !== res[0])) res.push(it);
166 return res;
167 }, []);
168 if (atitle.length) span.title = atitle.join(": ");
169 span.classList.add("report-result");
170 if (result) span.classList.add("report-result-" + result);
171 return span;
172 }
173
174 static checkResult(data) {
175 if (data.error_code !== undefined && data.error_code !== 0) {
176 throw data;
177 }
178 }
179
180 static displayError(obj) {
181 console.warn(obj.message || "Unknown error");
182 if (!(obj instanceof Error) && obj.debug_info) {
183 console.warn('Error code: ' + obj.debug_info.code);
184 console.warn('Error content: ' + obj.debug_info.content);
185 }
186 }
187
188 /**
189 * Reduces large numbers with the addition of postfixes K, M, B.
190 */
191 static abbrNumber(val, min) {
192 if (min !== undefined && val < min) return val.toLocaleString();
193 let f = 1;
194 let u = "";
195 if (val >= 1e9) {
196 f = 1e9;
197 u = "B";
198 } else if (val >= 1e6) {
199 f = 1e6;
200 u = "M";
201 } else if (val >= 1e3) {
202 f = 1e3;
203 u = "K";
204 }
205 return (Math.round((val / f + Number.EPSILON) * 10) / 10).toLocaleString() + u;
206 }
207
208 /**
209 * Gets the filter value as an object from the passed url, compares it to the passed cfilter,
210 * returns the new value, or undefined if the filter has not changed.
211 */
212 static getFilterFromURL(url, cfilter) {
213 let cnt = 0;
214 const nfilter = {};
215 url.searchParams.getAll("filter[]").forEach(function(it) {
216 let k = null;
217 let v = null;
218 const i = it.indexOf(":");
219 if (i !== 0) {
220 if (i > 0) {
221 k = it.substr(0, i);
222 v = it.substr(i + 1);
223 } else {
224 k = it;
225 v = "";
226 }
227 nfilter[k] = v;
228 ++cnt;
229 }
230 });
231 if (cfilter === undefined) return cnt ? nfilter : null;
232
233 let changed = !cfilter && cnt > 0;
234 if (!changed && cfilter) {
235 let cnt2 = 0;
236 changed = Object.keys(cfilter).some(function(k) {
237 ++cnt2;
238 return cnt < cnt2 || cfilter[k] !== nfilter[k];
239 }) || cnt !== cnt2;
240 }
241 return changed ? (cnt ? nfilter : null) : undefined;
242 }
243 }
244
245 Common.initAriaMethods();
246 Common.tuneDateTimeOutput("auto");