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

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