You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

libft.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /* global FooTable */
  2. define(["jquery", "app/common", "footable"],
  3. ($, common) => {
  4. "use strict";
  5. const ui = {};
  6. let pageSizeTimerId = null;
  7. let pageSizeInvocationCounter = 0;
  8. function get_compare_function(table) {
  9. const compare_functions = {
  10. magnitude: function (e1, e2) {
  11. return Math.abs(e2.score) - Math.abs(e1.score);
  12. },
  13. name: function (e1, e2) {
  14. return e1.name.localeCompare(e2.name);
  15. },
  16. score: function (e1, e2) {
  17. return e2.score - e1.score;
  18. }
  19. };
  20. return compare_functions[common.getSelector("selSymOrder_" + table)];
  21. }
  22. function sort_symbols(o, compare_function) {
  23. return Object.keys(o)
  24. .map((key) => o[key])
  25. .sort(compare_function)
  26. .map((e) => e.str)
  27. .join("<br>\n");
  28. }
  29. // Public functions
  30. ui.formatBytesIEC = function (bytes) {
  31. // FooTable represents data as text even column type is "number".
  32. if (!Number.isInteger(Number(bytes)) || bytes < 0) return "NaN";
  33. const base = 1024;
  34. const exponent = Math.floor(Math.log(bytes) / Math.log(base));
  35. if (exponent > 8) return "∞";
  36. const value = parseFloat((bytes / (base ** exponent)).toPrecision(3));
  37. let unit = "BKMGTPEZY"[exponent];
  38. if (exponent) unit += "iB";
  39. return value + " " + unit;
  40. };
  41. ui.columns_v2 = function (table) {
  42. return [{
  43. name: "id",
  44. title: "ID",
  45. style: {
  46. minWidth: 130,
  47. overflow: "hidden",
  48. textOverflow: "ellipsis",
  49. wordBreak: "break-all",
  50. whiteSpace: "normal"
  51. }
  52. }, {
  53. name: "file",
  54. title: "File name",
  55. breakpoints: "xs",
  56. sortValue: (val) => ((typeof val === "undefined") ? "" : val)
  57. }, {
  58. name: "ip",
  59. title: "IP address",
  60. breakpoints: "xs sm md",
  61. style: {
  62. "minWidth": "calc(14ch + 8px)",
  63. "word-break": "break-all"
  64. },
  65. // Normalize IPv4
  66. sortValue: (ip) => ((typeof ip === "string") ? ip.split(".").map((x) => x.padStart(3, "0")).join("") : "0")
  67. }, {
  68. name: "sender_mime",
  69. title: "[Envelope From] From",
  70. breakpoints: "xs sm md",
  71. style: {
  72. "minWidth": 100,
  73. "maxWidth": 200,
  74. "word-wrap": "break-word"
  75. }
  76. }, {
  77. name: "rcpt_mime_short",
  78. title: "[Envelope To] To/Cc/Bcc",
  79. breakpoints: "xs sm md",
  80. filterable: false,
  81. classes: "d-none d-xl-table-cell",
  82. style: {
  83. "minWidth": 100,
  84. "maxWidth": 200,
  85. "word-wrap": "break-word"
  86. }
  87. }, {
  88. name: "rcpt_mime",
  89. title: "[Envelope To] To/Cc/Bcc",
  90. breakpoints: "all",
  91. style: {"word-wrap": "break-word"}
  92. }, {
  93. name: "subject",
  94. title: "Subject",
  95. breakpoints: "xs sm md",
  96. style: {
  97. "word-break": "break-all",
  98. "minWidth": 150
  99. }
  100. }, {
  101. name: "action",
  102. title: "Action",
  103. style: {minwidth: 82}
  104. }, {
  105. name: "passthrough_module",
  106. title: '<div title="The module that has set the pre-result"><nobr>Pass-through</nobr> module</div>',
  107. breakpoints: "xs",
  108. style: {minWidth: 98, maxWidth: 98},
  109. sortValue: (val) => ((typeof val === "undefined") ? "" : val)
  110. }, {
  111. name: "score",
  112. title: "Score",
  113. style: {
  114. "maxWidth": 110,
  115. "text-align": "right",
  116. "white-space": "nowrap"
  117. },
  118. sortValue: function (val) { return Number(val.options.sortValue); }
  119. }, {
  120. name: "symbols",
  121. title: "Symbols" +
  122. '<div class="sym-order-toggle">' +
  123. '<br><span style="font-weight:normal;">Sort by:</span><br>' +
  124. '<div class="btn-group btn-group-xs btn-sym-order-' + table + '">' +
  125. '<label type="button" class="btn btn-outline-secondary btn-sym-' + table + '-magnitude">' +
  126. '<input type="radio" class="btn-check" value="magnitude">Magnitude</label>' +
  127. '<label type="button" class="btn btn-outline-secondary btn-sym-' + table + '-score">' +
  128. '<input type="radio" class="btn-check" value="score">Value</label>' +
  129. '<label type="button" class="btn btn-outline-secondary btn-sym-' + table + '-name">' +
  130. '<input type="radio" class="btn-check" value="name">Name</label>' +
  131. "</div>" +
  132. "</div>",
  133. breakpoints: "all",
  134. style: {width: 550, maxWidth: 550}
  135. }, {
  136. name: "size",
  137. title: "Msg size",
  138. breakpoints: "xs sm md",
  139. style: {minwidth: 50},
  140. formatter: ui.formatBytesIEC
  141. }, {
  142. name: "time_real",
  143. title: "Scan time",
  144. breakpoints: "xs sm md",
  145. style: {maxWidth: 72},
  146. sortValue: function (val) { return Number(val); }
  147. }, {
  148. classes: "history-col-time",
  149. sorted: true,
  150. direction: "DESC",
  151. name: "time",
  152. title: "Time",
  153. sortValue: function (val) { return Number(val.options.sortValue); }
  154. }, {
  155. name: "user",
  156. title: "Authenticated user",
  157. breakpoints: "xs sm md",
  158. style: {
  159. "minWidth": 100,
  160. "maxWidth": 130,
  161. "word-wrap": "break-word"
  162. }
  163. }].filter((col) => {
  164. switch (table) {
  165. case "history":
  166. return (col.name !== "file");
  167. case "scan":
  168. return ["ip", "sender_mime", "rcpt_mime_short", "rcpt_mime", "subject", "size", "user"]
  169. .every((name) => col.name !== name);
  170. default:
  171. return null;
  172. }
  173. });
  174. };
  175. ui.set_page_size = function (table, page_size, changeTablePageSize) {
  176. const n = parseInt(page_size, 10); // HTML Input elements return string representing a number
  177. if (n > 0) {
  178. common.page_size[table] = n;
  179. if (changeTablePageSize &&
  180. $("#historyTable_" + table + " tbody").is(":parent")) { // Table is not empty
  181. clearTimeout(pageSizeTimerId);
  182. const t = FooTable.get("#historyTable_" + table);
  183. if (t) {
  184. pageSizeInvocationCounter = 0;
  185. // Wait for input finish
  186. pageSizeTimerId = setTimeout(() => t.pageSize(n), 1000);
  187. } else if (++pageSizeInvocationCounter < 10) {
  188. // Wait for FooTable instance ready
  189. pageSizeTimerId = setTimeout(() => ui.set_page_size(table, n, true), 1000);
  190. }
  191. }
  192. }
  193. };
  194. ui.bindHistoryTableEventHandlers = function (table, symbolsCol) {
  195. function change_symbols_order(order) {
  196. $(".btn-sym-" + table + "-" + order).addClass("active").siblings().removeClass("active");
  197. const compare_function = get_compare_function(table);
  198. $.each(common.tables[table].rows.all, (i, row) => {
  199. const cell_val = sort_symbols(common.symbols[table][i], compare_function);
  200. row.cells[symbolsCol].val(cell_val, false, true);
  201. });
  202. }
  203. $("#selSymOrder_" + table).unbind().change(function () {
  204. const order = this.value;
  205. change_symbols_order(order);
  206. });
  207. $("#" + table + "_page_size").change((e) => ui.set_page_size(table, e.target.value, true));
  208. $(document).on("click", ".btn-sym-order-" + table + " input", function () {
  209. const order = this.value;
  210. $("#selSymOrder_" + table).val(order);
  211. change_symbols_order(order);
  212. });
  213. };
  214. ui.destroyTable = function (table) {
  215. if (common.tables[table]) {
  216. common.tables[table].destroy();
  217. delete common.tables[table];
  218. }
  219. };
  220. ui.initHistoryTable = function (data, items, table, columns, expandFirst, postdrawCallback) {
  221. /* eslint-disable no-underscore-dangle */
  222. FooTable.Cell.extend("collapse", function () {
  223. // call the original method
  224. this._super();
  225. // Copy cell classes to detail row tr element
  226. this._setClasses(this.$detail);
  227. });
  228. /* eslint-enable no-underscore-dangle */
  229. /* eslint-disable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  230. FooTable.actionFilter = FooTable.Filtering.extend({
  231. construct: function (instance) {
  232. this._super(instance);
  233. this.actions = ["reject", "add header", "greylist",
  234. "no action", "soft reject", "rewrite subject"];
  235. this.def = "Any action";
  236. this.$action = null;
  237. },
  238. $create: function () {
  239. this._super();
  240. const self = this;
  241. const $form_grp = $("<div/>", {
  242. class: "form-group d-inline-flex align-items-center"
  243. }).append($("<label/>", {
  244. class: "sr-only",
  245. text: "Action"
  246. })).prependTo(self.$form);
  247. $("<div/>", {
  248. class: "form-check form-check-inline",
  249. title: "Invert action match."
  250. }).append(
  251. self.$not = $("<input/>", {
  252. type: "checkbox",
  253. class: "form-check-input",
  254. id: "not_" + table
  255. }).on("change", {self: self}, self._onStatusDropdownChanged),
  256. $("<label/>", {
  257. class: "form-check-label",
  258. for: "not_" + table,
  259. text: "not"
  260. })
  261. ).appendTo($form_grp);
  262. self.$action = $("<select/>", {
  263. class: "form-select"
  264. }).on("change", {
  265. self: self
  266. }, self._onStatusDropdownChanged).append(
  267. $("<option/>", {
  268. text: self.def
  269. })).appendTo($form_grp);
  270. $.each(self.actions, (i, action) => {
  271. self.$action.append($("<option/>").text(action));
  272. });
  273. },
  274. _onStatusDropdownChanged: function (e) {
  275. const {self} = e.data;
  276. const selected = self.$action.val();
  277. if (selected !== self.def) {
  278. const not = self.$not.is(":checked");
  279. let query = null;
  280. if (selected === "reject") {
  281. query = not ? "-reject OR soft" : "reject -soft";
  282. } else {
  283. query = not ? selected.replace(/(\b\w+\b)/g, "-$1") : selected;
  284. }
  285. self.addFilter("action", query, ["action"]);
  286. } else {
  287. self.removeFilter("action");
  288. }
  289. self.filter();
  290. }
  291. });
  292. /* eslint-enable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  293. common.tables[table] = FooTable.init("#historyTable_" + table, {
  294. columns: columns,
  295. rows: items,
  296. expandFirst: expandFirst,
  297. paging: {
  298. enabled: true,
  299. limit: 5,
  300. size: common.page_size[table]
  301. },
  302. filtering: {
  303. enabled: true,
  304. position: "left",
  305. connectors: false
  306. },
  307. sorting: {
  308. enabled: true
  309. },
  310. components: {
  311. filtering: FooTable.actionFilter
  312. },
  313. on: {
  314. "expand.ft.row": function (e, ft, row) {
  315. setTimeout(() => {
  316. const detail_row = row.$el.next();
  317. const order = common.getSelector("selSymOrder_" + table);
  318. detail_row.find(".btn-sym-" + table + "-" + order)
  319. .addClass("active").siblings().removeClass("active");
  320. }, 5);
  321. },
  322. "postdraw.ft.table": postdrawCallback
  323. }
  324. });
  325. };
  326. ui.preprocess_item = function (item) {
  327. function escape_HTML_array(arr) {
  328. arr.forEach((d, i) => { arr[i] = common.escapeHTML(d); });
  329. }
  330. for (const prop in item) {
  331. if (!{}.hasOwnProperty.call(item, prop)) continue;
  332. switch (prop) {
  333. case "rcpt_mime":
  334. case "rcpt_smtp":
  335. escape_HTML_array(item[prop]);
  336. break;
  337. case "symbols":
  338. Object.keys(item.symbols).forEach((key) => {
  339. const sym = item.symbols[key];
  340. if (!sym.name) {
  341. sym.name = key;
  342. }
  343. sym.name = common.escapeHTML(sym.name);
  344. if (sym.description) {
  345. sym.description = common.escapeHTML(sym.description);
  346. }
  347. if (sym.options) {
  348. escape_HTML_array(sym.options);
  349. }
  350. });
  351. break;
  352. default:
  353. if (typeof item[prop] === "string") {
  354. item[prop] = common.escapeHTML(item[prop]);
  355. }
  356. }
  357. }
  358. if (item.action === "clean" || item.action === "no action") {
  359. item.action = "<div style='font-size:11px' class='badge text-bg-success'>" + item.action + "</div>";
  360. } else if (item.action === "rewrite subject" || item.action === "add header" || item.action === "probable spam") {
  361. item.action = "<div style='font-size:11px' class='badge text-bg-warning'>" + item.action + "</div>";
  362. } else if (item.action === "spam" || item.action === "reject") {
  363. item.action = "<div style='font-size:11px' class='badge text-bg-danger'>" + item.action + "</div>";
  364. } else {
  365. item.action = "<div style='font-size:11px' class='badge text-bg-info'>" + item.action + "</div>";
  366. }
  367. const score_content = (item.score < item.required_score)
  368. ? "<span class='text-success'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>"
  369. : "<span class='text-danger'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>";
  370. item.score = {
  371. options: {
  372. sortValue: item.score
  373. },
  374. value: score_content
  375. };
  376. };
  377. ui.unix_time_format = function (tm) {
  378. const date = new Date(tm ? tm * 1000 : 0);
  379. return (common.locale)
  380. ? date.toLocaleString(common.locale)
  381. : date.toLocaleString();
  382. };
  383. ui.process_history_v2 = function (data, table) {
  384. // Display no more than rcpt_lim recipients
  385. const rcpt_lim = 3;
  386. const items = [];
  387. const unsorted_symbols = [];
  388. const compare_function = get_compare_function(table);
  389. $("#selSymOrder_" + table + ", label[for='selSymOrder_" + table + "']").show();
  390. $.each(data.rows,
  391. (i, item) => {
  392. function more(p) {
  393. const l = item[p].length;
  394. return (l > rcpt_lim) ? " … (" + l + ")" : "";
  395. }
  396. function format_rcpt(smtp, mime) {
  397. let full = "";
  398. let shrt = "";
  399. if (smtp) {
  400. full = "[" + item.rcpt_smtp.join(", ") + "] ";
  401. shrt = "[" + item.rcpt_smtp.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_smtp") + "]";
  402. if (mime) {
  403. full += " ";
  404. shrt += " ";
  405. }
  406. }
  407. if (mime) {
  408. full += item.rcpt_mime.join(", ");
  409. shrt += item.rcpt_mime.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_mime");
  410. }
  411. return {full: full, shrt: shrt};
  412. }
  413. function get_symbol_class(name, score) {
  414. if (name.match(/^GREYLIST$/)) {
  415. return "symbol-special";
  416. }
  417. if (score < 0) {
  418. return "symbol-negative";
  419. } else if (score > 0) {
  420. return "symbol-positive";
  421. }
  422. return null;
  423. }
  424. ui.preprocess_item(item);
  425. Object.values(item.symbols).forEach((sym) => {
  426. sym.str = '<span class="symbol-default ' + get_symbol_class(sym.name, sym.score) + '"><strong>';
  427. if (sym.description) {
  428. sym.str += '<abbr title="' + sym.description + '">' + sym.name + "</abbr>";
  429. } else {
  430. sym.str += sym.name;
  431. }
  432. sym.str += "</strong> (" + sym.score + ")</span>";
  433. if (sym.options) {
  434. sym.str += " [" + sym.options.join(",") + "]";
  435. }
  436. });
  437. unsorted_symbols.push(item.symbols);
  438. item.symbols = sort_symbols(item.symbols, compare_function);
  439. if (table === "scan") {
  440. item.unix_time = (new Date()).getTime() / 1000;
  441. }
  442. item.time = {
  443. value: ui.unix_time_format(item.unix_time),
  444. options: {
  445. sortValue: item.unix_time
  446. }
  447. };
  448. item.time_real = item.time_real.toFixed(3);
  449. item.id = item["message-id"];
  450. if (table === "history") {
  451. let rcpt = {};
  452. if (!item.rcpt_mime.length) {
  453. rcpt = format_rcpt(true, false);
  454. } else if (
  455. $(item.rcpt_mime).not(item.rcpt_smtp).length !== 0 ||
  456. $(item.rcpt_smtp).not(item.rcpt_mime).length !== 0
  457. ) {
  458. rcpt = format_rcpt(true, true);
  459. } else {
  460. rcpt = format_rcpt(false, true);
  461. }
  462. item.rcpt_mime_short = rcpt.shrt;
  463. item.rcpt_mime = rcpt.full;
  464. if (item.sender_mime !== item.sender_smtp) {
  465. item.sender_mime = "[" + item.sender_smtp + "] " + item.sender_mime;
  466. }
  467. }
  468. items.push(item);
  469. });
  470. return {items: items, symbols: unsorted_symbols};
  471. };
  472. return ui;
  473. });