-
-
Notifications
You must be signed in to change notification settings - Fork 646
Expand file tree
/
Copy pathgroups-lists.js
More file actions
598 lines (545 loc) · 18.5 KB
/
Copy pathgroups-lists.js
File metadata and controls
598 lines (545 loc) · 18.5 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/* 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, groups:false, apiFailure:false, updateFtlInfo:false, getGroups:false, processGroupResult:false, delGroupItems:false */
/* exported initTable */
"use strict";
let table;
let GETDict = {};
$(() => {
GETDict = utils.parseQueryString();
$("#btnAddAllow").on("click", { type: "allow" }, addList);
$("#btnAddBlock").on("click", { type: "block" }, addList);
getGroups();
});
function format(data) {
// Generate human-friendly status string
const statusText = setStatusText(data, true);
let numbers = true;
if (data.status === 0 || data.status === 4) {
numbers = false;
}
// Compile extra info for displaying
const dateAddedISO = utils.datetime(data.date_added, false);
const dateModifiedISO = utils.datetime(data.date_modified, false);
const dateUpdated =
data.date_updated > 0
? utils.datetimeRelative(data.date_updated) +
" (" +
utils.datetime(data.date_updated, false) +
")"
: "N/A";
const numberOfEntries =
(data.number !== null && numbers === true ? Math.trunc(data.number).toLocaleString() : "N/A") +
(data.abp_entries !== null && Math.trunc(data.abp_entries) > 0 && numbers === true
? " (out of which " + Math.trunc(data.abp_entries).toLocaleString() + " are in ABP-style)"
: "");
const nonDomains =
data.invalid_domains !== null && numbers === true
? Math.trunc(data.invalid_domains).toLocaleString()
: "N/A";
return `<table>
<tr class="dataTables-child">
<td>Type: </td><td>${setTypeIcon(data.type)}${data.type}list</td>
</tr>
<tr class="dataTables-child">
<td>Health status: </td><td>${statusText}</td>
</tr>
<tr class="dataTables-child">
<td>Added to Pi-hole: </td>
<td>${utils.datetimeRelative(data.date_added)} (${dateAddedISO})</td>
</tr>
<tr class="dataTables-child">
<td>Database entry last modified: </td>
<td>${utils.datetimeRelative(data.date_modified)} (${dateModifiedISO})</td>
</tr>
<tr class="dataTables-child">
<td>Content last updated on: </td><td>${dateUpdated}</td>
</tr>
<tr class="dataTables-child">
<td>Number of entries: </td><td>${numberOfEntries}</td>
</tr>
<tr class="dataTables-child">
<td>Number of non-domains: </td><td>${nonDomains}</td>
</tr>
<tr class="dataTables-child">
<td>Database ID:</td><td>${data.id}</td>
</tr>
</table>`;
}
// Define the status icon element
function setStatusIcon(data) {
const statusCode = Math.trunc(data.status);
const statusTitle = setStatusText(data) + "\nClick for details about this list";
let statusIcon;
switch (statusCode) {
case 1:
statusIcon = "fa-check-circle";
break;
case 2:
statusIcon = "fa-history";
break;
case 3:
statusIcon = "fa-exclamation-circle";
break;
case 4:
statusIcon = "fa-times-circle";
break;
default:
statusIcon = "fa-question-circle";
break;
}
// Match the coloured `list-status-N` classes used by the legend so the
// table icons are coloured the same way instead of the default text colour.
const statusClass = [1, 2, 3, 4].includes(statusCode)
? `list-status-${statusCode}`
: "list-status-0";
return `<span class='fa fa-fw ${statusIcon} ${statusClass}' title='${statusTitle}'></span>`;
}
// Define human-friendly status string
function setStatusText(data, showdetails = false) {
let statusText = "Unknown";
let statusDetails = "";
if (data.status !== null) {
switch (Math.trunc(data.status)) {
case 0:
statusText =
data.enabled === 0
? "List is disabled and not checked"
: "List was not downloaded so far";
break;
case 1:
statusText = "List download was successful";
statusDetails = ' (<span class="list-status-1">OK</span>)';
break;
case 2:
statusText = "List unchanged upstream, Pi-hole used a local copy";
statusDetails = ' (<span class="list-status-2">OK</span>)';
break;
case 3:
statusText = "List unavailable, Pi-hole used a local copy";
statusDetails = ' (<span class="list-status-3">check list</span>)';
break;
case 4:
statusText =
"List unavailable, there is no local copy of this list available on your Pi-hole";
statusDetails = ' (<span class="list-status-4">replace list</span>)';
break;
default:
statusText = "Unknown";
statusDetails = ' (<span class="list-status-0">' + Math.trunc(data.status) + "</span>)";
break;
}
}
return statusText + (showdetails === true ? statusDetails : "");
}
// Define the type icon element
function setTypeIcon(type) {
//Add red ban icon if data["type"] is "block"
//Add green check icon if data["type"] is "allow"
let iconClass = "fa-question text-orange";
let title = "This list is of unknown type";
if (type === "block") {
iconClass = "fa-ban text-red";
title = "This is a blocklist";
} else if (type === "allow") {
iconClass = "fa-check text-green";
title = "This is an allowlist";
}
return `<span class='fa fa-fw ${iconClass}' title='${title}\nClick for details about this list'></span>`;
}
function initTable() {
table = $("#listsTable").DataTable({
processing: true,
ajax: {
url: document.body.dataset.apiurl + "/lists",
dataSrc: "lists",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "2rem" },
{ data: "status", searchable: false, class: "details-control" },
{ data: "type", searchable: false, class: "details-control" },
{ data: "address" },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render() {
return "";
},
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback() {
// Hide buttons if all lists were deleted
const hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
$('button[id^="deleteList_"]').on("click", deleteList);
},
rowCallback(row, data) {
const dataId = utils.hexEncode(data.address + "_" + data.type);
$(row).attr("data-id", dataId);
$(row).attr("data-address", utils.hexEncode(data.address));
$(row).attr("data-type", data.type);
let statusCode = 0;
// If there is no status or the list is disabled, we keep
// status 0 (== unknown)
if (data.status !== null && data.enabled) {
statusCode = Math.trunc(data.status);
}
$("td:eq(1)", row).addClass("list-status-" + statusCode);
$("td:eq(1)", row).html(setStatusIcon(data));
$("td:eq(2)", row).addClass("list-type-" + statusCode);
$("td:eq(2)", row).html(setTypeIcon(data.type));
if (data.address.startsWith("file://")) {
// Local files cannot be downloaded from a distant client so don't show
// a link to such a list here
const codeElem = document.createElement("code");
codeElem.id = "address_" + dataId;
codeElem.className = "breakall";
codeElem.textContent = data.address;
$("td:eq(3)", row).empty().append(codeElem);
} else {
const aElem = document.createElement("a");
aElem.id = "address_" + dataId;
aElem.className = "breakall";
aElem.href = data.address;
aElem.target = "_blank";
aElem.rel = "noopener noreferrer";
aElem.textContent = data.address;
$("td:eq(3)", row).empty().append(aElem);
}
$("td:eq(4)", row).html(
'<input type="checkbox" id="enabled_' +
dataId +
'"' +
(data.enabled ? " checked" : "") +
">"
);
const statusEl = $("#enabled_" + dataId, row);
statusEl.bootstrapToggle({
onlabel: "Enabled",
offlabel: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
statusEl.on("change", editList);
$("td:eq(5)", row).html('<input id="comment_' + dataId + '" class="form-control">');
const commentEl = $("#comment_" + dataId, row);
commentEl.val(data.comment);
commentEl.on("change", editList);
$("td:eq(6)", row).empty();
$("td:eq(6)", row).append(
'<select class="group-select" id="multiselect_' + dataId + '" multiple></select>'
);
const selectEl = $("#multiselect_" + dataId, row);
// Add all known groups
for (const group of groups) {
const label = group.enabled ? group.name : group.name + " (disabled)";
selectEl.append($("<option/>").val(group.id).text(label));
}
const applyBtn = "#btn_apply_" + dataId;
// Select assigned groups
selectEl.val(data.groups);
// Initialize group multi-select
const ts = utils.createGroupSelect(selectEl, {
onChange() {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", () => {
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
ts.close();
editList.call(selectEl);
});
}
},
onDropdownClose() {
// Restore values if the dropdown is closed without clicking the Apply button
if ($(applyBtn).prop("disabled")) {
return;
}
ts.setValue(data.groups);
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
},
});
$(ts.dropdown)
.find(".multiselect-actions-box")
.append(
'<button type="button" id=btn_apply_' +
dataId +
' class="btn btn-sm" disabled>Apply</button>'
);
// Highlight row (if url parameter "listid=" is used)
if ("listid" in GETDict && data.id === Math.trunc(GETDict.listid)) {
$(row).find("td").addClass("highlight");
}
const button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteList_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(7)", row).html(button);
},
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"],
],
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() {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action() {
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() {
// For each ".selected" row ...
const ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push({ item: $(this).attr("data-address"), type: $(this).attr("data-type") });
});
// Delete all selected rows at once
delGroupItems("list", ids, table, "multiple ");
},
},
],
stateSave: true,
stateDuration: 0,
stateSaveCallback(settings, data) {
utils.stateSaveCallback("groups-lists-table", data);
},
stateLoadCallback() {
const data = utils.stateLoadCallback("groups-lists-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;
},
initComplete() {
if (!("listid" in GETDict)) {
return;
}
const pos = table.column(0, { order: "current" }).data().indexOf(Math.trunc(GETDict.listid));
if (pos !== -1) {
const page = Math.floor(pos / table.page.info().length);
table.page(page).draw(false);
}
},
});
table.on("init select deselect", () => {
utils.changeTableButtonStates(table);
});
table.on("order.dt", () => {
const order = table.order();
if (order[0][0] !== 0 || order[0][1] !== "asc") {
$("#resetButton").removeClass("hidden");
} else {
$("#resetButton").addClass("hidden");
}
});
$("#resetButton").on("click", () => {
table.order([[0, "asc"]]).draw();
$("#resetButton").addClass("hidden");
});
// Add event listener for opening and closing details
$("#listsTable tbody").on("click", "td.details-control", function () {
const tr = $(this).closest("tr");
const row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass("shown");
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass("shown");
}
});
// Disable autocorrect in the search box
const 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);
}
}
// Remove 'bnt-group' class from container, to avoid grouping
$.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteList() {
const tr = $(this).closest("tr");
const listType = tr.attr("data-type");
const ids = [{ item: tr.attr("data-address"), type: listType }];
delGroupItems("list", ids, table, listType);
}
function addList(event) {
const type = event.data.type;
const comment = $("#new_comment").val();
// Convert all group IDs to integers
const group = $("#new_group").val().map(Number);
// Check if the user wants to add multiple domains (space or newline separated)
// If so, split the input and store it in an array
let addresses = $("#new_address")
.val()
.split(/[\s,]+/u);
// Remove empty elements
addresses = addresses.filter(el => el !== "");
const addressestr = JSON.stringify(addresses);
utils.disableAll();
utils.showAlert("info", "", "Adding subscribed " + type + "list(s)...", addressestr);
if (addresses.length === 0) {
// enable the ui elements again
utils.enableAll();
utils.showAlert("warning", "", "Warning", "Please specify " + type + "list address");
return;
}
$.ajax({
url: document.body.dataset.apiurl + "/lists?type=" + encodeURIComponent(type),
method: "post",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ address: addresses, comment, groups: group }),
success(data) {
utils.enableAll();
utils.listsAlert(type + "list", addresses, data);
$("#new_address").val("");
$("#new_comment").val("");
table.ajax.reload(null, false);
table.rows().deselect();
// Update number of groups in the sidebar
updateFtlInfo();
},
error(data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new " + type + "list", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editList() {
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const type = tr.attr("data-type");
const dataId = tr.attr("data-id");
const address = utils.hexDecode(tr.attr("data-address"));
const enabled = tr.find("#enabled_" + dataId).is(":checked");
const comment = tr.find("#comment_" + dataId).val();
// Convert list of string integers to list of integers using map(Number)
const groups = tr
.find("#multiselect_" + dataId)
.val()
.map(Number);
let done = "edited";
let notDone = "editing";
switch (elem) {
case "enabled_" + dataId:
if (!enabled) {
done = "disabled";
notDone = "disabling";
} else {
done = "enabled";
notDone = "enabling";
}
break;
case "comment_" + dataId:
done = "edited comment of";
notDone = "editing comment of";
break;
case "multiselect_" + dataId:
done = "edited groups of";
notDone = "editing groups of";
break;
default:
alert("bad element (" + elem + ") or invalid data-id!");
return;
}
utils.disableAll();
utils.showAlert("info", "", "Editing address...", address);
$.ajax({
url: document.body.dataset.apiurl + "/lists/" + encodeURIComponent(address) + "?type=" + type,
method: "put",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
groups,
comment,
enabled,
type,
}),
success(data) {
utils.enableAll();
processGroupResult(data, type + "list", done, notDone);
table.ajax.reload(null, false);
},
error(data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + type + "list " + address,
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},
});
}