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

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