-
-
Notifications
You must be signed in to change notification settings - Fork 583
/
Copy pathgroups.js
359 lines (331 loc) · 10.2 KB
/
groups.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/* Pi-hole: A black hole for Internet advertisements
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false, apiFailure:false, updateFtlInfo:false, processGroupResult:false, delGroupItems:false */
var table;
function handleAjaxError(xhr, textStatus) {
if (textStatus === "timeout") {
alert("The server took too long to send the data.");
} else {
alert("An unknown error occurred while loading the data.\n" + xhr.responseText);
}
table.clear();
table.draw();
}
$(function () {
$("#btnAdd").on("click", addGroup);
table = $("#groupsTable").DataTable({
processing: true,
ajax: {
url: "/api/groups",
error: handleAjaxError,
dataSrc: "groups",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "name" },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
},
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all groups were deleted
// if there is one row, it's the default group
var hasRows = this.api().rows({ filter: "applied" }).data().length > 1;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
$('button[id^="deleteGroup_"]').on("click", deleteGroup);
},
rowCallback: function (row, data) {
var dataId = utils.hexEncode(data.name);
$(row).attr("data-id", dataId);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
$("td:eq(1)", row).html(
'<input id="name_' + dataId + '" title="' + tooltip + '" class="form-control">'
);
var nameEl = $("#name_" + dataId, row);
nameEl.val(data.name);
nameEl.on("change", editGroup);
$("td:eq(2)", row).html(
'<input type="checkbox" id="enabled_' +
dataId +
'"' +
(data.enabled ? " checked" : "") +
">"
);
var enabledEl = $("#enabled_" + dataId, row);
enabledEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
enabledEl.on("change", editGroup);
$("td:eq(3)", row).html('<input id="comment_' + dataId + '" class="form-control">');
var comment = data.comment !== null ? data.comment : "";
var commentEl = $("#comment_" + dataId, row);
commentEl.val(comment);
commentEl.on("change", editGroup);
$("td:eq(4)", row).empty();
// Show delete button for all but the default group
if (data.id !== 0) {
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteGroup_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(4)", row).html(button);
}
},
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push({ item: $(this).attr("data-id") });
});
// Delete all selected rows at once
delGroupItems("group", ids, table);
},
},
],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
});
// Disable autocorrect in the search box
var input = document.querySelector("input[type=search]");
if (input !== null) {
input.setAttribute("autocomplete", "off");
input.setAttribute("autocorrect", "off");
input.setAttribute("autocapitalize", "off");
input.setAttribute("spellcheck", false);
}
table.on("init select deselect", function () {
// if the Default group is selected, undo the selection of it
if (table.rows({ selected: true }).data().pluck("id").indexOf(0) !== -1) {
table.rows(0).deselect();
}
utils.changeBulkDeleteStates(table);
});
table.on("order.dt", function () {
var order = table.order();
if (order[0][0] !== 0 || order[0][1] !== "asc") {
$("#resetButton").removeClass("hidden");
} else {
$("#resetButton").addClass("hidden");
}
});
$("#resetButton").on("click", function () {
table.order([[0, "asc"]]).draw();
$("#resetButton").addClass("hidden");
});
});
// Remove 'bnt-group' class from container, to avoid grouping
$.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteGroup() {
// Passes the button data-del-id attribute as ID
const ids = [{ item: $(this).attr("data-id") }];
delGroupItems("group", ids, table);
}
function addGroup() {
const comment = $("#new_comment").val();
// Check if the user wants to add multiple groups (space or newline separated)
// If so, split the input and store it in an array, however, do not split
// group names enclosed in quotes
var names = utils
.escapeHtml($("#new_name"))
.val()
.match(/(?:[^\s"]+|"[^"]*")+/g)
.map(function (name) {
return name.replaceAll(/(^"|"$)/g, "");
});
// Remove empty elements
names = names.filter(function (el) {
return el !== "";
});
const groupStr = JSON.stringify(names);
utils.disableAll();
utils.showAlert("info", "", "Adding group(s)...", groupStr);
if (names.length === 0) {
// enable the ui elements again
utils.enableAll();
utils.showAlert("warning", "", "Warning", "Please specify a group name");
return;
}
$.ajax({
url: "/api/groups",
method: "post",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
name: names,
comment: comment,
enabled: true,
}),
success: function (data) {
utils.enableAll();
utils.listsAlert("group", names, data);
$("#new_name").val("");
$("#new_comment").val("");
table.ajax.reload();
table.rows().deselect();
$("#new_name").focus();
// Update number of groups in the sidebar
updateFtlInfo();
},
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new group", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editGroup() {
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const id = tr.attr("data-id");
const oldName = utils.hexDecode(id);
const name = tr.find("#name_" + id).val();
const enabled = tr.find("#enabled_" + id).is(":checked");
const comment = tr.find("#comment_" + id).val();
var done = "edited";
var notDone = "editing";
switch (elem) {
case "enabled_" + id:
if (!enabled) {
done = "disabled";
notDone = "disabling";
} else {
done = "enabled";
notDone = "enabling";
}
break;
case "name_" + id:
done = "edited name of";
notDone = "editing name of";
break;
case "comment_" + id:
done = "edited comment of";
notDone = "editing comment of";
break;
default:
alert("bad element ( " + elem + " ) or invalid data-id!");
return;
}
utils.disableAll();
utils.showAlert("info", "", "Editing group...", oldName);
$.ajax({
url: "/api/groups/" + oldName,
method: "put",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
name: name,
comment: comment,
enabled: enabled,
}),
success: function (data) {
utils.enableAll();
processGroupResult(data, "group", done, notDone);
table.ajax.reload(null, false);
},
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " group with name " + oldName,
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},
});
}