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.

symbols.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*
  2. The MIT License (MIT)
  3. Copyright (C) 2017 Vsevolod Stakhov <vsevolod@highsecure.ru>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /* global FooTable */
  21. define(["jquery", "app/common", "footable"],
  22. ($, common) => {
  23. "use strict";
  24. const ui = {};
  25. let altered = {};
  26. function clear_altered() {
  27. $("#save-alert").addClass("d-none");
  28. altered = {};
  29. }
  30. function saveSymbols(server) {
  31. $("#save-alert button").attr("disabled", true);
  32. const values = [];
  33. Object.entries(altered).forEach(([key, value]) => values.push({name: key, value: value}));
  34. common.query("./savesymbols", {
  35. success: function () {
  36. clear_altered();
  37. common.alertMessage("alert-modal alert-success", "Symbols successfully saved");
  38. },
  39. complete: () => $("#save-alert button").removeAttr("disabled"),
  40. errorMessage: "Save symbols error",
  41. method: "POST",
  42. params: {
  43. data: JSON.stringify(values),
  44. dataType: "json",
  45. },
  46. server: server
  47. });
  48. }
  49. function process_symbols_data(data) {
  50. const items = [];
  51. const lookup = {};
  52. const freqs = [];
  53. const distinct_groups = [];
  54. data.forEach((group) => {
  55. group.rules.forEach((item) => {
  56. const formatter = new Intl.NumberFormat("en", {
  57. minimumFractionDigits: 2,
  58. maximumFractionDigits: 6,
  59. useGrouping: false
  60. });
  61. item.group = group.group;
  62. let label_class = "";
  63. if (item.weight < 0) {
  64. label_class = "scorebar-ham";
  65. } else if (item.weight > 0) {
  66. label_class = "scorebar-spam";
  67. }
  68. item.weight = '<input class="form-control input-sm mb-disabled scorebar ' + label_class +
  69. '" autocomplete="off" type="number" step="0.01" tabindex="1" ' +
  70. 'value="' + formatter.format(item.weight) + '" id="_sym_' + item.symbol + '"></input>';
  71. if (!item.time) {
  72. item.time = 0;
  73. }
  74. item.time = Number(item.time).toFixed(2) + "s";
  75. if (!item.frequency) {
  76. item.frequency = 0;
  77. }
  78. freqs.push(item.frequency);
  79. item.frequency = Number(item.frequency).toFixed(2);
  80. if (!(item.group in lookup)) {
  81. lookup[item.group] = 1;
  82. distinct_groups.push(item.group);
  83. }
  84. items.push(item);
  85. });
  86. });
  87. // For better mean calculations
  88. const avg_freq = freqs
  89. .sort((a, b) => Number(a) < Number(b))
  90. .reduce((f1, acc) => f1 + acc) / (freqs.length !== 0 ? freqs.length : 1.0);
  91. let mult = 1.0;
  92. let exp = 0.0;
  93. if (avg_freq > 0.0) {
  94. while (mult * avg_freq < 1.0) {
  95. mult *= 10;
  96. exp++;
  97. }
  98. }
  99. $.each(items, (i, item) => {
  100. item.frequency = Number(item.frequency) * mult;
  101. if (exp > 0) {
  102. item.frequency = item.frequency.toFixed(2) + "e-" + exp;
  103. } else {
  104. item.frequency = item.frequency.toFixed(2);
  105. }
  106. });
  107. return [items, distinct_groups];
  108. }
  109. // @get symbols into modal form
  110. ui.getSymbols = function () {
  111. $("#refresh, #updateSymbols").attr("disabled", true);
  112. clear_altered();
  113. common.query("symbols", {
  114. success: function (json) {
  115. const [{data}] = json;
  116. const items = process_symbols_data(data);
  117. /* eslint-disable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  118. FooTable.groupFilter = FooTable.Filtering.extend({
  119. construct: function (instance) {
  120. this._super(instance);
  121. [,this.groups] = items;
  122. this.def = "Any group";
  123. this.$group = null;
  124. },
  125. $create: function () {
  126. this._super();
  127. const self = this;
  128. const $form_grp = $("<div/>", {
  129. class: "form-group"
  130. }).append($("<label/>", {
  131. class: "sr-only",
  132. text: "Group"
  133. })).prependTo(self.$form);
  134. self.$group = $("<select/>", {
  135. class: "form-select"
  136. }).on("change", {
  137. self: self
  138. }, self._onStatusDropdownChanged).append(
  139. $("<option/>", {
  140. text: self.def
  141. })).appendTo($form_grp);
  142. $.each(self.groups, (i, group) => {
  143. self.$group.append($("<option/>").text(group));
  144. });
  145. common.appendButtonsToFtFilterDropdown(self);
  146. },
  147. _onStatusDropdownChanged: function (e) {
  148. const {self} = e.data;
  149. const selected = $(this).val();
  150. if (selected !== self.def) {
  151. self.addFilter("group", selected, ["group"]);
  152. } else {
  153. self.removeFilter("group");
  154. }
  155. self.filter();
  156. },
  157. draw: function () {
  158. this._super();
  159. const group = this.find("group");
  160. if (group instanceof FooTable.Filter) {
  161. this.$group.val(group.query.val());
  162. } else {
  163. this.$group.val(this.def);
  164. }
  165. }
  166. });
  167. /* eslint-enable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  168. common.tables.symbols = FooTable.init("#symbolsTable", {
  169. breakpoints: common.breakpoints,
  170. cascade: true,
  171. columns: [
  172. {sorted: true, direction: "ASC", name: "group", title: "Group"},
  173. {name: "symbol", title: "Symbol"},
  174. {name: "description", title: "Description", breakpoints: "md"},
  175. {name: "weight", title: "Score"},
  176. {name: "frequency",
  177. title: "Frequency",
  178. breakpoints: "md",
  179. sortValue: function (value) { return Number(value).toFixed(2); }},
  180. {name: "time", title: "Avg. time", breakpoints: "md"},
  181. ],
  182. rows: items[0],
  183. paging: {
  184. enabled: true,
  185. limit: 5,
  186. size: 25
  187. },
  188. filtering: {
  189. enabled: true,
  190. position: "left",
  191. connectors: false
  192. },
  193. sorting: {
  194. enabled: true
  195. },
  196. components: {
  197. filtering: FooTable.groupFilter
  198. },
  199. on: {
  200. "ready.ft.table": function () {
  201. if (common.read_only) {
  202. $(".mb-disabled").attr("disabled", true);
  203. }
  204. },
  205. "postdraw.ft.table":
  206. () => $("#refresh, #updateSymbols").removeAttr("disabled")
  207. }
  208. });
  209. },
  210. error: () => $("#refresh, #updateSymbols").removeAttr("disabled"),
  211. server: common.getServer()
  212. });
  213. };
  214. $("#updateSymbols").on("click", (e) => {
  215. e.preventDefault();
  216. $("#refresh, #updateSymbols").attr("disabled", true);
  217. clear_altered();
  218. common.query("symbols", {
  219. success: function (data) {
  220. const [items] = process_symbols_data(data[0].data);
  221. common.tables.symbols.rows.load(items);
  222. },
  223. error: () => $("#refresh, #updateSymbols").removeAttr("disabled"),
  224. server: common.getServer()
  225. });
  226. });
  227. $("#symbolsTable")
  228. .on("input", ".scorebar", ({target}) => {
  229. const t = $(target);
  230. t.removeClass("scorebar-ham scorebar-spam");
  231. if (target.value < 0) {
  232. t.addClass("scorebar-ham");
  233. } else if (target.value > 0) {
  234. t.addClass("scorebar-spam");
  235. }
  236. })
  237. .on("change", ".scorebar", ({target}) => {
  238. altered[$(target).attr("id").substring(5)] = parseFloat(target.value);
  239. $("#save-alert").removeClass("d-none");
  240. });
  241. $("#save-alert button")
  242. .on("click", ({target}) => saveSymbols($(target).data("save")));
  243. return ui;
  244. });