選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

rspamd.js 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. /*
  2. The MIT License (MIT)
  3. Copyright (C) 2012-2013 Anton Simonov <untone@gmail.com>
  4. Copyright (C) 2014-2017 Vsevolod Stakhov <vsevolod@highsecure.ru>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. */
  21. /* global jQuery:false, FooTable:false, Visibility:false */
  22. define(["jquery", "d3pie", "visibility", "nprogress", "stickytabs", "app/stats", "app/graph", "app/config",
  23. "app/symbols", "app/history", "app/upload", "app/selectors"],
  24. // eslint-disable-next-line max-params
  25. function ($, D3pie, visibility, NProgress, stickyTabs, tab_stat, tab_graph, tab_config,
  26. tab_symbols, tab_history, tab_upload, tab_selectors) {
  27. "use strict";
  28. var ui = {
  29. page_size: {
  30. scan: 25,
  31. errors: 25,
  32. history: 25
  33. },
  34. symbols: {
  35. scan: [],
  36. history: []
  37. }
  38. };
  39. var graphs = {};
  40. var tables = {};
  41. var neighbours = []; // list of clusters
  42. var checked_server = "All SERVERS";
  43. var timer_id = [];
  44. var selData = null; // Graph's dataset selector state
  45. var symbolDescriptions = {};
  46. NProgress.configure({
  47. minimum: 0.01,
  48. showSpinner: false,
  49. });
  50. function cleanCredentials() {
  51. sessionStorage.clear();
  52. $("#statWidgets").empty();
  53. $("#listMaps").empty();
  54. $("#modalBody").empty();
  55. }
  56. function stopTimers() {
  57. for (var key in timer_id) {
  58. if (!{}.hasOwnProperty.call(timer_id, key)) continue;
  59. Visibility.stop(timer_id[key]);
  60. }
  61. }
  62. function disconnect() {
  63. [graphs, tables].forEach(function (o) {
  64. Object.keys(o).forEach(function (key) {
  65. o[key].destroy();
  66. delete o[key];
  67. });
  68. });
  69. // Remove jquery-stickytabs listeners
  70. $(window).off("hashchange");
  71. $(".nav-tabs-sticky > .nav-item > .nav-link").off("click").removeClass("active");
  72. stopTimers();
  73. cleanCredentials();
  74. ui.connect();
  75. }
  76. function tabClick(id) {
  77. var tab_id = id;
  78. if ($(id).attr("disabled")) return;
  79. var navBarControls = $("#selSrv, #navBar li, #navBar a, #navBar button");
  80. navBarControls.attr("disabled", true).addClass("disabled", true);
  81. stopTimers();
  82. if (id === "#refresh" || id === "#autoRefresh") {
  83. tab_id = "#" + $(".nav-link.active").attr("id");
  84. }
  85. $("#autoRefresh").hide();
  86. $("#refresh").addClass("radius-right");
  87. function setAutoRefresh(refreshInterval, timer, callback) {
  88. function countdown(interval) {
  89. Visibility.stop(timer_id.countdown);
  90. if (!interval) {
  91. $("#countdown").text("--:--");
  92. return;
  93. }
  94. var timeLeft = interval;
  95. $("#countdown").text("00:00");
  96. timer_id.countdown = Visibility.every(1000, 1000, function () {
  97. timeLeft -= 1000;
  98. $("#countdown").text(new Date(timeLeft).toISOString().substr(14, 5));
  99. if (timeLeft <= 0) Visibility.stop(timer_id.countdown);
  100. });
  101. }
  102. $("#refresh").removeClass("radius-right");
  103. $("#autoRefresh").show();
  104. countdown(refreshInterval);
  105. if (!refreshInterval) return;
  106. timer_id[timer] = Visibility.every(refreshInterval, function () {
  107. countdown(refreshInterval);
  108. callback();
  109. });
  110. }
  111. if (["#scan_nav", "#selectors_nav", "#disconnect"].indexOf(tab_id) !== -1) {
  112. $("#refresh").hide();
  113. } else {
  114. $("#refresh").show();
  115. }
  116. switch (tab_id) {
  117. case "#status_nav":
  118. (function () {
  119. var refreshInterval = $(".dropdown-menu a.active.preset").data("value");
  120. setAutoRefresh(refreshInterval, "status",
  121. function () { return tab_stat.statWidgets(ui, graphs, checked_server); });
  122. if (id !== "#autoRefresh") tab_stat.statWidgets(ui, graphs, checked_server);
  123. $(".preset").show();
  124. $(".dynamic").hide();
  125. }());
  126. break;
  127. case "#throughput_nav":
  128. (function () {
  129. var step = {
  130. day: 60000,
  131. week: 300000
  132. };
  133. var refreshInterval = step[selData] || 3600000;
  134. $("#dynamic-item").text((refreshInterval / 60000) + " min");
  135. if (!$(".dropdown-menu a.active.dynamic").data("value")) {
  136. refreshInterval = null;
  137. }
  138. setAutoRefresh(refreshInterval, "throughput",
  139. function () { return tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData); });
  140. if (id !== "#autoRefresh") tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData);
  141. $(".preset").hide();
  142. $(".dynamic").show();
  143. }());
  144. break;
  145. case "#configuration_nav":
  146. tab_config.getActions(ui, checked_server);
  147. tab_config.getMaps(ui, checked_server);
  148. break;
  149. case "#symbols_nav":
  150. tab_symbols.getSymbols(ui, tables, checked_server);
  151. break;
  152. case "#history_nav":
  153. tab_history.getHistory(ui, tables);
  154. tab_history.getErrors(ui, tables);
  155. break;
  156. case "#disconnect":
  157. disconnect();
  158. break;
  159. default:
  160. }
  161. setTimeout(function () {
  162. navBarControls.removeAttr("disabled").removeClass("disabled");
  163. }, (id === "#autoRefresh") ? 0 : 1000);
  164. }
  165. function drawTooltips() {
  166. // Update symbol description tooltips
  167. $.each(symbolDescriptions, function (key, description) {
  168. $("abbr[data-sym-key=" + key + "]").tooltip({
  169. placement: "bottom",
  170. html: true,
  171. title: description
  172. });
  173. });
  174. }
  175. function getPassword() {
  176. return sessionStorage.getItem("Password");
  177. }
  178. // Get selectors' current state
  179. function getSelector(id) {
  180. var e = document.getElementById(id);
  181. return e.options[e.selectedIndex].value;
  182. }
  183. function get_compare_function(table) {
  184. var compare_functions = {
  185. magnitude: function (e1, e2) {
  186. return Math.abs(e2.score) - Math.abs(e1.score);
  187. },
  188. name: function (e1, e2) {
  189. return e1.name.localeCompare(e2.name);
  190. },
  191. score: function (e1, e2) {
  192. return e2.score - e1.score;
  193. }
  194. };
  195. return compare_functions[getSelector("selSymOrder_" + table)];
  196. }
  197. function saveCredentials(password) {
  198. sessionStorage.setItem("Password", password);
  199. }
  200. function set_page_size(table, page_size, callback) {
  201. var n = parseInt(page_size, 10); // HTML Input elements return string representing a number
  202. if (n !== ui.page_size[table] && n > 0) {
  203. ui.page_size[table] = n;
  204. if (callback) {
  205. return callback(n);
  206. }
  207. }
  208. return null;
  209. }
  210. function sort_symbols(o, compare_function) {
  211. return Object.keys(o)
  212. .map(function (key) {
  213. return o[key];
  214. })
  215. .sort(compare_function)
  216. .map(function (e) { return e.str; })
  217. .join("<br>\n");
  218. }
  219. function unix_time_format(tm) {
  220. var date = new Date(tm ? tm * 1000 : 0);
  221. return date.toLocaleString();
  222. }
  223. function displayUI() {
  224. // In many browsers local storage can only store string.
  225. // So when we store the boolean true or false, it actually stores the strings "true" or "false".
  226. ui.read_only = sessionStorage.getItem("read_only") === "true";
  227. ui.query("auth", {
  228. success: function (neighbours_status) {
  229. $("#selSrv").empty();
  230. $("#selSrv").append($('<option value="All SERVERS">All SERVERS</option>'));
  231. neighbours_status.forEach(function (e) {
  232. $("#selSrv").append($('<option value="' + e.name + '">' + e.name + "</option>"));
  233. if (checked_server === e.name) {
  234. $('#selSrv [value="' + e.name + '"]').prop("selected", true);
  235. } else if (!e.status) {
  236. $('#selSrv [value="' + e.name + '"]').prop("disabled", true);
  237. }
  238. });
  239. if (!ui.read_only) tab_selectors.displayUI(ui);
  240. },
  241. errorMessage: "Cannot get server status",
  242. server: "All SERVERS"
  243. });
  244. if (ui.read_only) {
  245. $(".ro-disable").attr("disabled", true);
  246. $(".ro-hide").hide();
  247. } else {
  248. $(".ro-disable").removeAttr("disabled", true);
  249. $(".ro-hide").show();
  250. }
  251. $("#preloader").addClass("d-none");
  252. $("#navBar, #mainUI").removeClass("d-none");
  253. $(".nav-tabs-sticky").stickyTabs({initialTab:"#status_nav"});
  254. }
  255. function alertMessage(alertClass, alertText) {
  256. var a = $("<div class=\"alert " + alertClass + " alert-dismissible fade in show\">" +
  257. "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" title=\"Dismiss\">&times;</button>" +
  258. "<strong>" + alertText + "</strong>");
  259. $(".notification-area").append(a);
  260. setTimeout(function () {
  261. $(a).fadeTo(500, 0).slideUp(500, function () {
  262. $(this).alert("close");
  263. });
  264. }, 5000);
  265. }
  266. function queryServer(neighbours_status, ind, req_url, o) {
  267. neighbours_status[ind].checked = false;
  268. neighbours_status[ind].data = {};
  269. neighbours_status[ind].status = false;
  270. var req_params = {
  271. jsonp: false,
  272. data: o.data,
  273. headers: $.extend({Password:getPassword()}, o.headers),
  274. url: neighbours_status[ind].url + req_url,
  275. xhr: function () {
  276. var xhr = $.ajaxSettings.xhr();
  277. // Download progress
  278. if (req_url !== "neighbours") {
  279. xhr.addEventListener("progress", function (e) {
  280. if (e.lengthComputable) {
  281. neighbours_status[ind].percentComplete = e.loaded / e.total;
  282. var percentComplete = neighbours_status.reduce(function (prev, curr) {
  283. return curr.percentComplete ? curr.percentComplete + prev : prev;
  284. }, 0);
  285. NProgress.set(percentComplete / neighbours_status.length);
  286. }
  287. }, false);
  288. }
  289. return xhr;
  290. },
  291. success: function (json) {
  292. neighbours_status[ind].checked = true;
  293. neighbours_status[ind].status = true;
  294. neighbours_status[ind].data = json;
  295. },
  296. error: function (jqXHR, textStatus, errorThrown) {
  297. neighbours_status[ind].checked = true;
  298. function errorMessage() {
  299. alertMessage("alert-error", neighbours_status[ind].name + " > " +
  300. (o.errorMessage ? o.errorMessage : "Request failed") +
  301. (errorThrown ? ": " + errorThrown : ""));
  302. }
  303. if (o.error) {
  304. o.error(neighbours_status[ind],
  305. jqXHR, textStatus, errorThrown);
  306. } else if (o.errorOnceId) {
  307. var alert_status = o.errorOnceId + neighbours_status[ind].name;
  308. if (!(alert_status in sessionStorage)) {
  309. sessionStorage.setItem(alert_status, true);
  310. errorMessage();
  311. }
  312. } else {
  313. errorMessage();
  314. }
  315. },
  316. complete: function (jqXHR) {
  317. if (neighbours_status.every(function (elt) { return elt.checked; })) {
  318. if (neighbours_status.some(function (elt) { return elt.status; })) {
  319. if (o.success) {
  320. o.success(neighbours_status, jqXHR);
  321. } else {
  322. alertMessage("alert-success", "Request completed");
  323. }
  324. } else {
  325. alertMessage("alert-error", "Request failed");
  326. }
  327. NProgress.done();
  328. }
  329. },
  330. statusCode: o.statusCode
  331. };
  332. if (o.method) {
  333. req_params.method = o.method;
  334. }
  335. if (o.params) {
  336. $.each(o.params, function (k, v) {
  337. req_params[k] = v;
  338. });
  339. }
  340. $.ajax(req_params);
  341. }
  342. // Public functions
  343. ui.alertMessage = alertMessage;
  344. ui.setup = function () {
  345. $("#selData").change(function () {
  346. selData = this.value;
  347. tabClick("#throughput_nav");
  348. });
  349. $.ajaxSetup({
  350. timeout: 20000,
  351. jsonp: false
  352. });
  353. $(document).ajaxStart(function () {
  354. $("#refresh > svg").addClass("fa-spin");
  355. });
  356. $(document).ajaxComplete(function () {
  357. setTimeout(function () {
  358. $("#refresh > svg").removeClass("fa-spin");
  359. }, 1000);
  360. });
  361. $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
  362. tabClick("#" + $(e.target).attr("id"));
  363. });
  364. $("#refresh, #disconnect").on("click", function (e) {
  365. e.preventDefault();
  366. tabClick("#" + $(e.target).attr("id"));
  367. });
  368. $(".dropdown-menu a").click(function (e) {
  369. e.preventDefault();
  370. var classList = $(this).attr("class");
  371. var menuClass = (/\b(?:dynamic|preset)\b/).exec(classList)[0];
  372. $(".dropdown-menu a.active." + menuClass).removeClass("active");
  373. $(this).addClass("active");
  374. tabClick("#autoRefresh");
  375. });
  376. $("#selSrv").change(function () {
  377. checked_server = this.value;
  378. $("#selSrv [value=\"" + checked_server + "\"]").prop("checked", true);
  379. tabClick("#" + $("#navBar > ul > .nav-item > .nav-link.active").attr("id"));
  380. });
  381. // Radio buttons
  382. $(document).on("click", "input:radio[name=\"clusterName\"]", function () {
  383. if (!this.disabled) {
  384. checked_server = this.value;
  385. tabClick("#status_nav");
  386. }
  387. });
  388. tab_config.setup(ui);
  389. tab_history.setup(ui, tables);
  390. tab_selectors.setup(ui);
  391. tab_symbols.setup(ui, tables);
  392. tab_upload.setup(ui, tables);
  393. selData = tab_graph.setup(ui);
  394. $("#loading").addClass("d-none");
  395. };
  396. ui.connect = function () {
  397. // Query "/stat" to check if user is already logged in or client ip matches "secure_ip"
  398. $.ajax({
  399. type: "GET",
  400. url: "stat",
  401. async: false,
  402. success: function () {
  403. displayUI();
  404. },
  405. error: function () {
  406. $("#connectDialog")
  407. .on("shown.bs.modal", function () {
  408. $("#connectDialog").off("shown.bs.modal");
  409. $("#connectPassword").focus();
  410. })
  411. .modal("show");
  412. $("#connectForm").on("submit", function (e) {
  413. e.preventDefault();
  414. var password = $("#connectPassword").val();
  415. if (!(/^[\u0020-\u007e]*$/).test(password)) {
  416. alertMessage("alert-modal alert-error", "Invalid characters in the password");
  417. $("#connectPassword").focus();
  418. return;
  419. }
  420. ui.query("auth", {
  421. headers: {
  422. Password: password
  423. },
  424. success: function (json) {
  425. var data = json[0].data;
  426. $("#connectPassword").val("");
  427. if (data.auth === "ok") {
  428. sessionStorage.setItem("read_only", data.read_only);
  429. saveCredentials(password);
  430. $("#connectForm").off("submit");
  431. $("#connectDialog").modal("hide");
  432. displayUI();
  433. }
  434. },
  435. error: function (jqXHR) {
  436. ui.alertMessage("alert-modal alert-error", jqXHR.statusText);
  437. $("#connectPassword").val("");
  438. $("#connectPassword").focus();
  439. },
  440. params: {
  441. global: false,
  442. },
  443. server: "local"
  444. });
  445. });
  446. }
  447. });
  448. };
  449. ui.drawPie = function (object, id, data, conf) {
  450. var obj = object;
  451. if (obj) {
  452. obj.updateProp("data.content",
  453. data.filter(function (elt) {
  454. return elt.value > 0;
  455. })
  456. );
  457. } else {
  458. obj = new D3pie(id,
  459. $.extend({}, {
  460. header: {
  461. title: {
  462. text: "Rspamd filter stats",
  463. fontSize: 24,
  464. font: "open sans"
  465. },
  466. subtitle: {
  467. color: "#999999",
  468. fontSize: 12,
  469. font: "open sans"
  470. },
  471. titleSubtitlePadding: 9
  472. },
  473. footer: {
  474. color: "#999999",
  475. fontSize: 10,
  476. font: "open sans",
  477. location: "bottom-left"
  478. },
  479. size: {
  480. canvasWidth: 600,
  481. canvasHeight: 400,
  482. pieInnerRadius: "20%",
  483. pieOuterRadius: "85%"
  484. },
  485. data: {
  486. // "sortOrder": "value-desc",
  487. content: data.filter(function (elt) {
  488. return elt.value > 0;
  489. })
  490. },
  491. labels: {
  492. outer: {
  493. hideWhenLessThanPercentage: 1,
  494. pieDistance: 30
  495. },
  496. inner: {
  497. hideWhenLessThanPercentage: 4
  498. },
  499. mainLabel: {
  500. fontSize: 14
  501. },
  502. percentage: {
  503. color: "#eeeeee",
  504. fontSize: 14,
  505. decimalPlaces: 0
  506. },
  507. lines: {
  508. enabled: true
  509. },
  510. truncation: {
  511. enabled: true
  512. }
  513. },
  514. tooltips: {
  515. enabled: true,
  516. type: "placeholder",
  517. string: "{label}: {value} ({percentage}%)"
  518. },
  519. effects: {
  520. pullOutSegmentOnClick: {
  521. effect: "back",
  522. speed: 400,
  523. size: 8
  524. },
  525. load: {
  526. effect: "none"
  527. }
  528. },
  529. misc: {
  530. gradient: {
  531. enabled: true,
  532. percentage: 100
  533. }
  534. }
  535. }, conf));
  536. }
  537. return obj;
  538. };
  539. ui.getPassword = getPassword;
  540. ui.getSelector = getSelector;
  541. /**
  542. * @param {string} url - A string containing the URL to which the request is sent
  543. * @param {Object} [options] - A set of key/value pairs that configure the Ajax request. All settings are optional.
  544. *
  545. * @param {Object|string|Array} [options.data] - Data to be sent to the server.
  546. * @param {Function} [options.error] - A function to be called if the request fails.
  547. * @param {string} [options.errorMessage] - Text to display in the alert message if the request fails.
  548. * @param {string} [options.errorOnceId] - A prefix of the alert ID to be added to the session storage. If the
  549. * parameter is set, the error for each server will be displayed only once per session.
  550. * @param {Object} [options.headers] - An object of additional header key/value pairs to send along with requests
  551. * using the XMLHttpRequest transport.
  552. * @param {string} [options.method] - The HTTP method to use for the request.
  553. * @param {Object} [options.params] - An object of additional jQuery.ajax() settings key/value pairs.
  554. * @param {string} [options.server] - A server to which send the request.
  555. * @param {Function} [options.success] - A function to be called if the request succeeds.
  556. *
  557. * @returns {undefined}
  558. */
  559. ui.query = function (url, options) {
  560. // Force options to be an object
  561. var o = options || {};
  562. Object.keys(o).forEach(function (option) {
  563. if (["data", "error", "errorMessage", "errorOnceId", "headers", "method", "params", "server", "statusCode",
  564. "success"]
  565. .indexOf(option) < 0) {
  566. throw new Error("Unknown option: " + option);
  567. }
  568. });
  569. var neighbours_status = [{
  570. name: "local",
  571. host: "local",
  572. url: "",
  573. }];
  574. o.server = o.server || checked_server;
  575. if (o.server === "All SERVERS") {
  576. queryServer(neighbours_status, 0, "neighbours", {
  577. success: function (json) {
  578. var data = json[0].data;
  579. if (jQuery.isEmptyObject(data)) {
  580. neighbours = {
  581. local: {
  582. host: window.location.host,
  583. url: window.location.origin + window.location.pathname
  584. }
  585. };
  586. } else {
  587. neighbours = data;
  588. }
  589. neighbours_status = [];
  590. $.each(neighbours, function (ind) {
  591. neighbours_status.push({
  592. name: ind,
  593. host: neighbours[ind].host,
  594. url: neighbours[ind].url,
  595. });
  596. });
  597. $.each(neighbours_status, function (ind) {
  598. queryServer(neighbours_status, ind, url, o);
  599. });
  600. },
  601. errorMessage: "Cannot receive neighbours data"
  602. });
  603. } else {
  604. if (o.server !== "local") {
  605. neighbours_status = [{
  606. name: o.server,
  607. host: neighbours[o.server].host,
  608. url: neighbours[o.server].url,
  609. }];
  610. }
  611. queryServer(neighbours_status, 0, url, o);
  612. }
  613. };
  614. // Scan and History shared functions
  615. ui.drawTooltips = drawTooltips;
  616. ui.unix_time_format = unix_time_format;
  617. ui.set_page_size = set_page_size;
  618. ui.bindHistoryTableEventHandlers = function (table, symbolsCol) {
  619. function change_symbols_order(order) {
  620. $(".btn-sym-" + table + "-" + order).addClass("active").siblings().removeClass("active");
  621. var compare_function = get_compare_function(table);
  622. $.each(tables[table].rows.all, function (i, row) {
  623. var cell_val = sort_symbols(ui.symbols[table][i], compare_function);
  624. row.cells[symbolsCol].val(cell_val, false, true);
  625. });
  626. drawTooltips();
  627. }
  628. $("#selSymOrder_" + table).unbind().change(function () {
  629. var order = this.value;
  630. change_symbols_order(order);
  631. });
  632. $("#" + table + "_page_size").change(function () {
  633. set_page_size(table, this.value, function (n) { tables[table].pageSize(n); });
  634. });
  635. $(document).on("click", ".btn-sym-order-" + table + " input", function () {
  636. var order = this.value;
  637. $("#selSymOrder_" + table).val(order);
  638. change_symbols_order(order);
  639. });
  640. };
  641. ui.destroyTable = function (table) {
  642. if (tables[table]) {
  643. tables[table].destroy();
  644. delete tables[table];
  645. }
  646. };
  647. ui.initHistoryTable = function (rspamd, data, items, table, columns, expandFirst) {
  648. /* eslint-disable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  649. FooTable.actionFilter = FooTable.Filtering.extend({
  650. construct: function (instance) {
  651. this._super(instance);
  652. this.actions = ["reject", "add header", "greylist",
  653. "no action", "soft reject", "rewrite subject"];
  654. this.def = "Any action";
  655. this.$action = null;
  656. },
  657. $create: function () {
  658. this._super();
  659. var self = this, $form_grp = $("<div/>", {
  660. class: "form-group"
  661. }).append($("<label/>", {
  662. class: "sr-only",
  663. text: "Action"
  664. })).prependTo(self.$form);
  665. self.$action = $("<select/>", {
  666. class: "form-control"
  667. }).on("change", {
  668. self: self
  669. }, self._onStatusDropdownChanged).append(
  670. $("<option/>", {
  671. text: self.def
  672. })).appendTo($form_grp);
  673. $.each(self.actions, function (i, action) {
  674. self.$action.append($("<option/>").text(action));
  675. });
  676. },
  677. _onStatusDropdownChanged: function (e) {
  678. var self = e.data.self, selected = $(this).val();
  679. if (selected !== self.def) {
  680. if (selected === "reject") {
  681. self.addFilter("action", "reject -soft", ["action"]);
  682. } else {
  683. self.addFilter("action", selected, ["action"]);
  684. }
  685. } else {
  686. self.removeFilter("action");
  687. }
  688. self.filter();
  689. },
  690. draw: function () {
  691. this._super();
  692. var action = this.find("action");
  693. if (action instanceof FooTable.Filter) {
  694. if (action.query.val() === "reject -soft") {
  695. this.$action.val("reject");
  696. } else {
  697. this.$action.val(action.query.val());
  698. }
  699. } else {
  700. this.$action.val(this.def);
  701. }
  702. }
  703. });
  704. /* eslint-enable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  705. tables[table] = FooTable.init("#historyTable_" + table, {
  706. columns: columns,
  707. rows: items,
  708. expandFirst: expandFirst,
  709. paging: {
  710. enabled: true,
  711. limit: 5,
  712. size: ui.page_size[table]
  713. },
  714. filtering: {
  715. enabled: true,
  716. position: "left",
  717. connectors: false
  718. },
  719. sorting: {
  720. enabled: true
  721. },
  722. components: {
  723. filtering: FooTable.actionFilter
  724. },
  725. on: {
  726. "ready.ft.table": drawTooltips,
  727. "after.ft.sorting": drawTooltips,
  728. "after.ft.paging": drawTooltips,
  729. "after.ft.filtering": drawTooltips,
  730. "expand.ft.row": function (e, ft, row) {
  731. setTimeout(function () {
  732. var detail_row = row.$el.next();
  733. var order = getSelector("selSymOrder_" + table);
  734. detail_row.find(".btn-sym-" + table + "-" + order)
  735. .addClass("active").siblings().removeClass("active");
  736. }, 5);
  737. }
  738. }
  739. });
  740. };
  741. ui.escapeHTML = function (string) {
  742. var htmlEscaper = /[&<>"'/`=]/g;
  743. var htmlEscapes = {
  744. "&": "&amp;",
  745. "<": "&lt;",
  746. ">": "&gt;",
  747. "\"": "&quot;",
  748. "'": "&#39;",
  749. "/": "&#x2F;",
  750. "`": "&#x60;",
  751. "=": "&#x3D;"
  752. };
  753. return String(string).replace(htmlEscaper, function (match) {
  754. return htmlEscapes[match];
  755. });
  756. };
  757. ui.preprocess_item = function (rspamd, item) {
  758. function escape_HTML_array(arr) {
  759. arr.forEach(function (d, i) { arr[i] = ui.escapeHTML(d); });
  760. }
  761. for (var prop in item) {
  762. if (!{}.hasOwnProperty.call(item, prop)) continue;
  763. switch (prop) {
  764. case "rcpt_mime":
  765. case "rcpt_smtp":
  766. escape_HTML_array(item[prop]);
  767. break;
  768. case "symbols":
  769. Object.keys(item.symbols).forEach(function (key) {
  770. var sym = item.symbols[key];
  771. if (!sym.name) {
  772. sym.name = key;
  773. }
  774. sym.name = ui.escapeHTML(sym.name);
  775. if (sym.description) {
  776. sym.description = ui.escapeHTML(sym.description);
  777. }
  778. if (sym.options) {
  779. escape_HTML_array(sym.options);
  780. }
  781. });
  782. break;
  783. default:
  784. if (typeof item[prop] === "string") {
  785. item[prop] = ui.escapeHTML(item[prop]);
  786. }
  787. }
  788. }
  789. if (item.action === "clean" || item.action === "no action") {
  790. item.action = "<div style='font-size:11px' class='badge badge-success'>" + item.action + "</div>";
  791. } else if (item.action === "rewrite subject" || item.action === "add header" || item.action === "probable spam") {
  792. item.action = "<div style='font-size:11px' class='badge badge-warning'>" + item.action + "</div>";
  793. } else if (item.action === "spam" || item.action === "reject") {
  794. item.action = "<div style='font-size:11px' class='badge badge-danger'>" + item.action + "</div>";
  795. } else {
  796. item.action = "<div style='font-size:11px' class='badge badge-info'>" + item.action + "</div>";
  797. }
  798. var score_content = (item.score < item.required_score)
  799. ? "<span class='text-success'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>"
  800. : "<span class='text-danger'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>";
  801. item.score = {
  802. options: {
  803. sortValue: item.score
  804. },
  805. value: score_content
  806. };
  807. };
  808. ui.process_history_v2 = function (rspamd, data, table) {
  809. // Display no more than rcpt_lim recipients
  810. var rcpt_lim = 3;
  811. var items = [];
  812. var unsorted_symbols = [];
  813. var compare_function = get_compare_function(table);
  814. $("#selSymOrder_" + table + ", label[for='selSymOrder_" + table + "']").show();
  815. $.each(data.rows,
  816. function (i, item) {
  817. function more(p) {
  818. var l = item[p].length;
  819. return (l > rcpt_lim) ? " … (" + l + ")" : "";
  820. }
  821. function format_rcpt(smtp, mime) {
  822. var full = "";
  823. var shrt = "";
  824. if (smtp) {
  825. full = "[" + item.rcpt_smtp.join(", ") + "] ";
  826. shrt = "[" + item.rcpt_smtp.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_smtp") + "]";
  827. if (mime) {
  828. full += " ";
  829. shrt += " ";
  830. }
  831. }
  832. if (mime) {
  833. full += item.rcpt_mime.join(", ");
  834. shrt += item.rcpt_mime.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_mime");
  835. }
  836. return {full:full, shrt:shrt};
  837. }
  838. function get_symbol_class(name, score) {
  839. if (name.match(/^GREYLIST$/)) {
  840. return "symbol-special";
  841. }
  842. if (score < 0) {
  843. return "symbol-negative";
  844. } else if (score > 0) {
  845. return "symbol-positive";
  846. }
  847. return null;
  848. }
  849. rspamd.preprocess_item(rspamd, item);
  850. Object.keys(item.symbols).forEach(function (key) {
  851. var sym = item.symbols[key];
  852. sym.str = '<span class="symbol-default ' + get_symbol_class(sym.name, sym.score) + '"><strong>';
  853. if (sym.description) {
  854. sym.str += '<abbr data-sym-key="' + key + '">' +
  855. sym.name + "</abbr></strong> (" + sym.score + ")</span>";
  856. // Store description for tooltip
  857. symbolDescriptions[key] = sym.description;
  858. } else {
  859. sym.str += sym.name + "</strong> (" + sym.score + ")</span>";
  860. }
  861. if (sym.options) {
  862. sym.str += " [" + sym.options.join(",") + "]";
  863. }
  864. });
  865. unsorted_symbols.push(item.symbols);
  866. item.symbols = sort_symbols(item.symbols, compare_function);
  867. if (table === "scan") {
  868. item.unix_time = (new Date()).getTime() / 1000;
  869. }
  870. item.time = {
  871. value: unix_time_format(item.unix_time),
  872. options: {
  873. sortValue: item.unix_time
  874. }
  875. };
  876. item.time_real = item.time_real.toFixed(3);
  877. item.id = item["message-id"];
  878. if (table === "history") {
  879. var rcpt = {};
  880. if (!item.rcpt_mime.length) {
  881. rcpt = format_rcpt(true, false);
  882. } else if ($(item.rcpt_mime).not(item.rcpt_smtp).length !== 0 || $(item.rcpt_smtp).not(item.rcpt_mime).length !== 0) {
  883. rcpt = format_rcpt(true, true);
  884. } else {
  885. rcpt = format_rcpt(false, true);
  886. }
  887. item.rcpt_mime_short = rcpt.shrt;
  888. item.rcpt_mime = rcpt.full;
  889. if (item.sender_mime !== item.sender_smtp) {
  890. item.sender_mime = "[" + item.sender_smtp + "] " + item.sender_mime;
  891. }
  892. }
  893. items.push(item);
  894. });
  895. return {items:items, symbols:unsorted_symbols};
  896. };
  897. ui.waitForRowsDisplayed = function (table, rows_total, callback, iteration) {
  898. var i = (typeof iteration === "undefined") ? 10 : iteration;
  899. var num_rows = $("#historyTable_" + table + " > tbody > tr:not(.footable-detail-row)").length;
  900. if (num_rows === ui.page_size[table] ||
  901. num_rows === rows_total) {
  902. return callback();
  903. } else if (--i) {
  904. setTimeout(function () {
  905. ui.waitForRowsDisplayed(table, rows_total, callback, i);
  906. }, 500);
  907. }
  908. return null;
  909. };
  910. return ui;
  911. });