1
0
mirror of https://github.com/donaldzou/WGDashboard.git synced 2024-11-06 07:50:13 +01:00

Removed all deprecated JS files

This commit is contained in:
Donald Zou 2024-08-17 00:52:38 -04:00
parent da4bb9b83d
commit 5669e22548
11 changed files with 0 additions and 2705 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,929 +0,0 @@
let $body = $("body");
let available_ips = [];
let $add_peer = document.getElementById("save_peer");
$("#configuration_delete").on("click", function(){
configurations.configurationDeleteModal().toggle();
});
function ajaxPostJSON(url, data, doneFunc){
$.ajax({
url: url,
method: "POST",
data: JSON.stringify(data),
headers: {"Content-Type": "application/json"}
}).done(function (res) {
doneFunc(res);
});
}
function ajaxGetJSON(url, doneFunc){
$.ajax({
url: url,
headers: {"Content-Type": "application/json"}
}).done(function (res) {
doneFunc(res);
});
}
$("#sure_delete_configuration").on("click", function () {
configurations.removeConfigurationInterval();
let ele = $(this)
ele.attr("disabled", "disabled");
function done(res){
if (res.status){
$('#configuration_delete_modal button[data-dismiss="modal"]').remove();
ele.text("Delete Successful! Redirecting in 5 seconds.");
setTimeout(function(){
window.location.replace('/');
}, 5000)
}else{
$("#remove_configuration_alert").removeClass("d-none").text(res.reason);
}
}
ajaxPostJSON("/api/deleteConfiguration", {"name": configurations.getConfigurationName()}, done);
});
function loadPeerDataUsageChartDone(res){
if (res.status === true){
let t = new Date();
let string = `${t.getDate()}/${t.getMonth()}/${t.getFullYear()} ${t.getHours() > 10 ? t.getHours():`0${t.getHours()}`}:${t.getMinutes() > 10 ? t.getMinutes():`0${t.getMinutes()}`}:${t.getSeconds() > 10 ? t.getSeconds():`0${t.getSeconds()}`}`;
$(".peerDataUsageUpdateTime").html(`Updated on: ${string}`);
configurations.peerDataUsageChartObj().data.labels = [];
configurations.peerDataUsageChartObj().data.datasets[0].data = [];
configurations.peerDataUsageChartObj().data.datasets[1].data = [];
console.log(res);
let data = res.data;
if (data.length > 0){
configurations.peerDataUsageChartObj().data.labels.push(data[data.length - 1].time);
configurations.peerDataUsageChartObj().data.datasets[0].data.push(0);
configurations.peerDataUsageChartObj().data.datasets[1].data.push(0);
configurations.peerDataUsageChartObj().data.datasets[0].lastData = data[data.length - 1].total_sent
configurations.peerDataUsageChartObj().data.datasets[1].lastData = data[data.length - 1].total_receive
for(let i = data.length - 2; i >= 0; i--){
let sent = data[i].total_sent - configurations.peerDataUsageChartObj().data.datasets[0].lastData;
let receive = data[i].total_receive - configurations.peerDataUsageChartObj().data.datasets[1].lastData;
configurations.peerDataUsageChartObj().data.datasets[0].data.push(sent);
configurations.peerDataUsageChartObj().data.datasets[1].data.push(receive);
configurations.peerDataUsageChartObj().data.labels.push(data[i].time);
configurations.peerDataUsageChartObj().data.datasets[0].lastData = data[i].total_sent;
configurations.peerDataUsageChartObj().data.datasets[1].lastData = data[i].total_receive;
}
configurations.peerDataUsageChartObj().update();
}
}
}
let peerDataUsageInterval;
$body.on("click", ".btn-data-usage-peer", function(){
configurations.peerDataUsageChartObj().data.peerID = $(this).data("peer-id");
configurations.peerDataUsageModal().toggle();
peerDataUsageInterval = setInterval(function(){
ajaxPostJSON("/api/getPeerDataUsage", {"config": configurations.getConfigurationName(), "peerID": configurations.peerDataUsageChartObj().data.peerID, "interval": window.localStorage.getItem("peerTimePeriod")}, loadPeerDataUsageChartDone);
}, 30000);
ajaxPostJSON("/api/getPeerDataUsage", {"config": configurations.getConfigurationName(), "peerID": configurations.peerDataUsageChartObj().data.peerID, "interval": window.localStorage.getItem("peerTimePeriod")}, loadPeerDataUsageChartDone);
});
$('#peerDataUsage').on('shown.bs.modal', function() {
configurations.peerDataUsageChartObj().resize();
}).on('hidden.bs.modal', function() {
clearInterval(peerDataUsageInterval);
configurations.peerDataUsageChartObj().data.peerID = "";
configurations.peerDataUsageChartObj().data.labels = [];
configurations.peerDataUsageChartObj().data.datasets[0].data = [];
configurations.peerDataUsageChartObj().data.datasets[1].data = [];
configurations.peerDataUsageChartObj().update();
});
$(".switchTimePeriod").on("click", function(){
let peerTimePeriod = window.localStorage.peerTimePeriod;
$(".switchTimePeriod").removeClass("active");
$(this).addClass("active");
if ($(this).data('time') !== peerTimePeriod){
ajaxPostJSON("/api/getPeerDataUsage", {"config": configurations.getConfigurationName(), "peerID": configurations.peerDataUsageChartObj().data.peerID, "interval": $(this).data('time')}, loadPeerDataUsageChartDone);
window.localStorage.peerTimePeriod = $(this).data('time');
}
})
/**
* Edit Configuration
*/
$editConfiguration = $("#edit_configuration");
$editConfiguration.on("click", function(){
configurations.getConfigurationDetails();
configurations.configurationEditModal().toggle();
});
$saveConfiguration = $("#editConfigurationBtn");
$saveConfiguration.on("click", function(){
$(this).html("Saving...")
$(this).siblings().hide();
$(this).attr("disabled", "disabled");
let data = {
"configurationName": configurations.getConfigurationName(),
"ListenPort": $("#editConfigurationListenPort").val(),
"PostUp": $("#editConfigurationPostUp").val(),
"PostDown": $("#editConfigurationPostDown").val(),
"PreDown": $("#editConfigurationPreDown").val(),
"PreUp": $("#editConfigurationPreUp").val(),
}
function done(res){
console.log(res);
$saveConfiguration.removeAttr("disabled");
if (res.status){
configurations.configurationEditModal().toggle();
configurations.loadPeers("");
showToast("Configuration saved");
}else{
showToast(res.reason);
}
$saveConfiguration.html("Save");
$saveConfiguration.siblings().show();
}
ajaxPostJSON("/api/saveConfiguration", data, done);
})
/**
* ==========
* Add peers
* ==========
*/
/**
* Toggle add peers modal when add button clicked
*/
document.querySelector(".add_btn").addEventListener("click", () => {
configurations.addModal().toggle();
});
/**
* When configuration switch got click
*/
$(".toggle--switch").on("change", function(){
console.log('lol')
$(this).addClass("waiting").attr("disabled", "disabled");
let id = configurations.getConfigurationName();
let status = $(this).prop("checked");
let ele = $(this);
$.ajax({
url: `/switch/${id}`
}).done(function(res){
if (res.status){
if (status){
showToast(`${id} is running.`)
}else{
showToast(`${id} is stopped.`)
}
}else{
if (status){
ele.prop("checked", false)
}else{
ele.prop("checked", true)
}
showToast(res.reason, true);
$(".index-alert").removeClass("d-none").text(`Configuration toggle failed. Please check the following error message:\n${res.message}`);
}
ele.removeClass("waiting");
ele.removeAttr("disabled");
configurations.loadPeers($('#search_peer_textbox').val())
});
});
/**
* Generate Public key when private got change
*/
document.querySelector("#private_key").addEventListener("change", (event) => {
let publicKey = document.querySelector("#public_key");
if (event.target.value.length === 44) {
publicKey.value = window.wireguard.generatePublicKey(event.target.value);
publicKey.setAttribute("disabled", "disabled");
} else {
publicKey.attributes.removeNamedItem("disabled");
publicKey.value = "";
}
});
/**
* Handle when add modal is show and hide
*/
$('#add_modal').on('show.bs.modal', function() {
configurations.generateKeyPair();
configurations.getAvailableIps();
}).on('hide.bs.modal', function() {
$("#allowed_ips_indicator").html('');
});
/**
* Handle when user clicked the regenerate button
*/
$("#re_generate_key").on("click", function() {
$("#public_key").attr("disabled", "disabled");
$("#re_generate_key i").addClass("rotating");
configurations.generateKeyPair();
});
/**
* Handle when user is editing in allowed ips textbox
*/
$("#allowed_ips").on("keyup", function() {
let s = configurations.cleanIp($(this).val());
s = s.split(",");
if (available_ips.includes(s[s.length - 1])) {
$("#allowed_ips_indicator").removeClass().addClass("text-success")
.html('<i class="bi bi-check-circle-fill"></i>');
} else {
$("#allowed_ips_indicator").removeClass().addClass("text-warning")
.html('<i class="bi bi-exclamation-circle-fill"></i>');
}
});
/**
* Change peer name when user typing in peer name textbox
*/
$("#peer_name_textbox").on("keyup", function() {
$(".peer_name").html($(this).val());
});
/**
* When Add Peer button got clicked
*/
$add_peer.addEventListener("click", function() {
let $bulk_add = $("#bulk_add");
if ($bulk_add.prop("checked")) {
if (!$("#new_add_amount").hasClass("is-invalid")) {
configurations.addPeersByBulk();
}
} else {
let $public_key = $("#public_key");
let $private_key = $("#private_key");
let $allowed_ips = $("#allowed_ips");
$allowed_ips.val(configurations.cleanIp($allowed_ips.val()));
let $new_add_DNS = $("#new_add_DNS");
$new_add_DNS.val(configurations.cleanIp($new_add_DNS.val()));
let $new_add_endpoint_allowed_ip = $("#new_add_endpoint_allowed_ip");
$new_add_endpoint_allowed_ip.val(configurations.cleanIp($new_add_endpoint_allowed_ip.val()));
let $new_add_name = $("#new_add_name");
let $new_add_MTU = $("#new_add_MTU");
let $new_add_keep_alive = $("#new_add_keep_alive");
let $enable_preshare_key = $("#enable_preshare_key");
$add_peer.setAttribute("disabled", "disabled");
$add_peer.innerHTML = "Adding...";
if ($allowed_ips.val() !== "" && $public_key.val() !== "" && $new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== "") {
let conf = configurations.getConfigurationName();
let data_list = [$private_key, $allowed_ips, $new_add_name, $new_add_DNS, $new_add_endpoint_allowed_ip, $new_add_MTU, $new_add_keep_alive];
data_list.forEach((ele) => ele.attr("disabled", "disabled"));
$.ajax({
method: "POST",
url: "/add_peer/" + conf,
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
"private_key": $private_key.val(),
"public_key": $public_key.val(),
"allowed_ips": $allowed_ips.val(),
"name": $new_add_name.val(),
"DNS": $new_add_DNS.val(),
"endpoint_allowed_ip": $new_add_endpoint_allowed_ip.val(),
"MTU": $new_add_MTU.val(),
"keep_alive": $new_add_keep_alive.val(),
"enable_preshared_key": $enable_preshare_key.prop("checked"),
"preshared_key": $enable_preshare_key.val()
}),
success: function(response) {
if (response !== "true") {
$("#add_peer_alert").html(response).removeClass("d-none");
data_list.forEach((ele) => ele.removeAttr("disabled"));
$add_peer.removeAttribute("disabled");
$add_peer.innerHTML = "Save";
} else {
configurations.loadPeers("");
data_list.forEach((ele) => ele.removeAttr("disabled"));
$("#add_peer_form").trigger("reset");
$add_peer.removeAttribute("disabled");
$add_peer.innerHTML = "Save";
showToast("Add peer successful!");
configurations.addModal().toggle();
}
}
});
} else {
$("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");
$add_peer.removeAttribute("disabled");
$add_peer.innerHTML = "Add";
}
}
});
/**
* Handle when user is typing the amount of peers they want to add, and will check if the amount is less than 1 or
* is larger than the amount of available ips
*/
$("#new_add_amount").on("keyup", function() {
let $bulk_amount_validation = $("#bulk_amount_validation");
// $(this).removeClass("is-valid").addClass("is-invalid");
if ($(this).val().length > 0) {
if (isNaN($(this).val())) {
$(this).removeClass("is-valid").addClass("is-invalid");
$bulk_amount_validation.html("Please enter a valid integer");
} else if ($(this).val() > available_ips.length) {
$(this).removeClass("is-valid").addClass("is-invalid");
$bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`);
} else if ($(this).val() < 1) {
$(this).removeClass("is-valid").addClass("is-invalid");
$bulk_amount_validation.html("Please enter at least 1 or more.");
} else {
$(this).removeClass("is-invalid").addClass("is-valid");
}
} else {
$(this).removeClass("is-invalid").removeClass("is-valid");
}
});
/**
* Handle when user toggled add peers by bulk
*/
$("#bulk_add").on("change", function() {
let hide = $(".non-bulk");
let amount = $("#new_add_amount");
if ($(this).prop("checked") === true) {
for (let i = 0; i < hide.length; i++) {
$(hide[i]).attr("disabled", "disabled");
}
amount.removeAttr("disabled");
} else {
for (let i = 0; i < hide.length; i++) {
if ($(hide[i]).attr('id') !== "public_key") {
$(hide[i]).removeAttr("disabled");
}
}
amount.attr("disabled", "disabled");
}
});
/**
* =======================
* Available IP Related
* =======================
*/
/**
* Handle when available ip modal show and hide
*/
$("#available_ip_modal").on("show.bs.modal", () => {
document.querySelector('#add_modal').classList.add("ip_modal_open");
}).on("hidden.bs.modal", () => {
document.querySelector('#add_modal').classList.remove("ip_modal_open");
let ips = [];
let $selected_ip_list = document.querySelector("#selected_ip_list");
for (let i = 0; i < $selected_ip_list.childElementCount; i++) {
ips.push($selected_ip_list.children[i].dataset.ip);
}
ips.forEach((ele) => configurations.triggerIp(ele));
});
/**
* When IP Badge got click
*/
$body.on("click", ".available-ip-badge", function() {
$(".available-ip-item[data-ip='" + $(this).data("ip") + "']").removeClass("active");
$(this).remove();
});
/**
* When available ip item got click
*/
$body.on("click", ".available-ip-item", function() {
configurations.triggerIp($(this).data("ip"));
});
/**
* When search IP button got clicked
*/
$("#search_available_ip").on("click", function() {
configurations.ipModal().toggle();
let $allowed_ips = document.querySelector("#allowed_ips");
if ($allowed_ips.value.length > 0) {
let s = $allowed_ips.value.split(",");
for (let i = 0; i < s.length; i++) {
s[i] = s[i].trim();
configurations.triggerIp(s[i]);
}
}
}).tooltip();
/**
* When confirm IP is clicked
*/
$("#confirm_ip").on("click", () => {
configurations.ipModal().toggle();
let ips = [];
let $selected_ip_list = $("#selected_ip_list");
$selected_ip_list.children().each(function() {
ips.push($(this).data("ip"));
});
$("#allowed_ips").val(ips.join(", "));
ips.forEach((ele) => configurations.triggerIp(ele));
});
/**
* =======
* QR Code
* =======
*/
/**
* When the QR-code button got clicked on each peer
*/
$body.on("click", ".btn-qrcode-peer", function() {
let src = $(this).data('imgsrc');
$.ajax({
"url": src,
"method": "GET"
}).done(function(res) {
$("#qrcode_img").attr('src', res);
configurations.qrcodeModal().toggle();
});
});
/**
* ===========
* Delete Peer
* ===========
*/
/**
* When the delete button got clicked on each peer
*/
$body.on("click", ".btn-delete-peer", function() {
let peer_id = $(this).data('peer-id')
$("#delete_peer").data("peer-id", peer_id);
configurations.deleteModal().toggle();
});
$body.on("click", ".btn-lock-peer", function() {
configurations.toggleAccess($(this).data('peer-id'), configurations.getConfigurationName());
if ($(this).hasClass("lock")) {
console.log($(this).data("peer-name"))
showToast(`Enabled ${$(this).children().data("peer-name")}`)
$(this).removeClass("lock")
$(this).children().tooltip('hide').attr('data-original-title', 'Peer enabled. Click to disable peer.').tooltip('show');
} else {
// Currently unlocked
showToast(`Disabled ${$(this).children().data("peer-name")}`)
$(this).addClass("lock");
$(this).children().tooltip('hide').attr('data-original-title', 'Peer disabled. Click to enable peer.').tooltip('show');
}
});
/**
* When the confirm delete button clicked
*/
$("#delete_peer").on("click", function() {
$(this).attr("disabled", "disabled");
$(this).html("Deleting...");
let config = configurations.getConfigurationName();
let peer_ids = [$(this).data("peer-id")];
configurations.deletePeers(config, peer_ids);
});
/**
* =============
* Peer Settings
* =============
*/
/**
* Handle when setting button got clicked for each peer
*/
$body.on("click", ".btn-setting-peer", function() {
// configurations.startProgressBar();
let peer_id = $(this).data("peer-id");
$("#save_peer_setting").attr("peer_id", peer_id);
$.ajax({
method: "POST",
url: "/get_peer_data/" + configurations.getConfigurationName(),
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({ "id": peer_id }),
success: function(response) {
let peer_name = ((response.name === "") ? "Untitled" : response.name);
$("#setting_modal .peer_name").html(peer_name);
$("#setting_modal #peer_name_textbox").val(response.name);
$("#setting_modal #peer_private_key_textbox").val(response.private_key);
$("#setting_modal #peer_DNS_textbox").val(response.DNS);
$("#setting_modal #peer_allowed_ip_textbox").val(response.allowed_ip);
$("#setting_modal #peer_endpoint_allowed_ips").val(response.endpoint_allowed_ip);
$("#setting_modal #peer_mtu").val(response.mtu);
$("#setting_modal #peer_keep_alive").val(response.keep_alive);
$("#setting_modal #peer_preshared_key_textbox").val(response.preshared_key);
configurations.settingModal().toggle();
configurations.endProgressBar();
}
});
});
/**
* Handle when setting modal is closing
*/
$('#setting_modal').on('hidden.bs.modal', function() {
$("#setting_peer_alert").addClass("d-none");
});
/**
* Handle when private key text box in setting modal got changed
*/
$("#peer_private_key_textbox").on("change", function() {
let $save_peer_setting = $("#save_peer_setting");
if ($(this).val().length > 0) {
$.ajax({
"url": "/check_key_match/" + configurations.getConfigurationName(),
"method": "POST",
"headers": { "Content-Type": "application/json" },
"data": JSON.stringify({
"private_key": $("#peer_private_key_textbox").val(),
"public_key": $save_peer_setting.attr("peer_id")
})
}).done(function(res) {
if (res.status === "failed") {
$("#setting_peer_alert").html(res.status).removeClass("d-none");
} else {
$("#setting_peer_alert").addClass("d-none");
}
});
}
});
/**
* When save peer setting button got clicked
*/
$("#save_peer_setting").on("click", function() {
$(this).attr("disabled", "disabled");
$(this).html("Saving...");
let $peer_DNS_textbox = $("#peer_DNS_textbox");
let $peer_allowed_ip_textbox = $("#peer_allowed_ip_textbox");
let $peer_endpoint_allowed_ips = $("#peer_endpoint_allowed_ips");
let $peer_name_textbox = $("#peer_name_textbox");
let $peer_private_key_textbox = $("#peer_private_key_textbox");
let $peer_preshared_key_textbox = $("#peer_preshared_key_textbox");
let $peer_mtu = $("#peer_mtu");
let $peer_keep_alive = $("#peer_keep_alive");
if ($peer_DNS_textbox.val() !== "" &&
$peer_allowed_ip_textbox.val() !== "" && $peer_endpoint_allowed_ips.val() !== "") {
let peer_id = $(this).attr("peer_id");
let conf_id = $(this).attr("conf_id");
let data_list = [$peer_name_textbox, $peer_DNS_textbox, $peer_private_key_textbox, $peer_preshared_key_textbox, $peer_allowed_ip_textbox, $peer_endpoint_allowed_ips, $peer_mtu, $peer_keep_alive];
data_list.forEach((ele) => ele.attr("disabled", "disabled"));
$.ajax({
method: "POST",
url: "/save_peer_setting/" + conf_id,
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
id: peer_id,
name: $peer_name_textbox.val(),
DNS: $peer_DNS_textbox.val(),
private_key: $peer_private_key_textbox.val(),
allowed_ip: $peer_allowed_ip_textbox.val(),
endpoint_allowed_ip: $peer_endpoint_allowed_ips.val(),
MTU: $peer_mtu.val(),
keep_alive: $peer_keep_alive.val(),
preshared_key: $peer_preshared_key_textbox.val()
}),
success: function(response) {
if (response.status === "failed") {
$("#setting_peer_alert").html(response.msg).removeClass("d-none");
} else {
configurations.settingModal().toggle();
configurations.loadPeers($('#search_peer_textbox').val());
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Peer Saved!");
}
$("#save_peer_setting").removeAttr("disabled").html("Save");
data_list.forEach((ele) => ele.removeAttr("disabled"));
}
});
} else {
$("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none");
$("#save_peer_setting").removeAttr("disabled").html("Save");
}
});
/**
* Toggle show or hide for the private key textbox in the setting modal
*/
$(".peer_private_key_textbox_switch").on("click", function() {
let $peer_private_key_textbox = $("#peer_private_key_textbox");
let mode = (($peer_private_key_textbox.attr('type') === 'password') ? "text" : "password");
let icon = (($peer_private_key_textbox.attr('type') === 'password') ? "bi bi-eye-slash-fill" : "bi bi-eye-fill");
$peer_private_key_textbox.attr('type', mode);
$(".peer_private_key_textbox_switch i").removeClass().addClass(icon);
});
/**
* ===========
* Search Peer
* ===========
*/
let typingTimer; // Timeout object
let doneTypingInterval = 200; // Timeout interval
/**
* Handle when the user keyup and keydown on the search textbox
*/
$('#search_peer_textbox').on('keyup', function() {
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
configurations.loadPeers($(this).val());
}, doneTypingInterval);
}).on('keydown', function() {
clearTimeout(typingTimer);
});
/**
* Manage Peers
*/
/**
* Handle when sort peers changed
*/
$body.on("change", "#sort_by_dropdown", function() {
$.ajax({
method: "POST",
data: JSON.stringify({ 'sort': $("#sort_by_dropdown option:selected").val() }),
headers: { "Content-Type": "application/json" },
url: "/update_dashboard_sort",
success: function() {
configurations.loadPeers($('#search_peer_textbox').val());
}
});
});
/**
* Handle copy public key
*/
$body.on("mouseenter", ".key", function() {
let label = $(this).parent().siblings().children()[1];
label.style.opacity = "100";
}).on("mouseout", ".key", function() {
let label = $(this).parent().siblings().children()[1];
label.style.opacity = "0";
setTimeout(function() {
label.innerHTML = "CLICK TO COPY";
}, 200);
}).on("click", ".key", function() {
let label = $(this).parent().siblings().children()[1];
configurations.copyToClipboard($(this));
label.innerHTML = "COPIED!";
});
/**
* Handle when interval button got clicked
*/
$body.on("click", ".update_interval", function() {
$(".interval-btn-group button").removeClass("active");
let _new = $(this);
_new.addClass("active");
let interval = $(this).data("refresh-interval");
if ([5000, 10000, 30000, 60000].includes(interval)) {
configurations.updateRefreshInterval(interval);
}
// $.ajax({
// method:"POST",
// data: "interval="+$(this).data("refresh-interval"),
// url: "/update_dashboard_refresh_interval",
// success: function (res){
// configurations.updateRefreshInterval(res, interval);
// }
// });
});
/**
* Handle when refresh button got clicked
*/
$body.on("click", ".refresh", function() {
configurations.loadPeers($('#search_peer_textbox').val());
});
/**
* Handle when display mode button got clicked
*/
$body.on("click", ".display_mode", function() {
$(".display-btn-group button").removeClass("active");
$(this).addClass("active");
window.localStorage.setItem("displayMode", $(this).data("display-mode"));
configurations.updateDisplayMode();
if ($(this).data("display-mode") === "list") {
Array($(".peer_list").children()).forEach(function(child) {
$(child).removeClass().addClass("col-12");
});
showToast("Displaying as List");
} else {
Array($(".peer_list").children()).forEach(function(child) {
$(child).removeClass().addClass("col-sm-6 col-lg-4");
});
showToast("Displaying as Grids");
}
});
/**
* =================
* Configuration Menu
* =================
*/
let $setting_btn_menu = $(".setting_btn_menu");
$setting_btn_menu.css("top", ($setting_btn_menu.height() + 54) * (-1));
let $setting_btn = $(".setting_btn");
/**
* When the menu button got clicked
*/
$setting_btn.on("click", function() {
if ($setting_btn_menu.hasClass("show")) {
$setting_btn_menu.removeClass("showing");
setTimeout(function() {
$setting_btn_menu.removeClass("show");
}, 201);
} else {
$setting_btn_menu.addClass("show");
setTimeout(function() {
$setting_btn_menu.addClass("showing");
}, 10);
}
});
/**
* Whenever the user clicked, if it is outside the menu and the menu is opened, hide the menu
*/
$("html").on("click", function(r) {
if (document.querySelector(".setting_btn") !== r.target) {
if (!document.querySelector(".setting_btn").contains(r.target)) {
if (!document.querySelector(".setting_btn_menu").contains(r.target)) {
$setting_btn_menu.removeClass("showing");
setTimeout(function() {
$setting_btn_menu.removeClass("show");
}, 310);
}
}
}
});
/**
* ====================
* Delete Peers by Bulk
* ====================
*/
/**
* When delete peers by bulk clicked
*/
$("#delete_peers_by_bulk_btn").on("click", () => {
let $delete_bulk_modal_list = $("#delete_bulk_modal .list-group");
$delete_bulk_modal_list.html('');
peers.forEach((peer) => {
let name;
if (peer.name === "") { name = "Untitled Peer"; } else { name = peer.name; }
$delete_bulk_modal_list.append('<a class="list-group-item list-group-item-action delete-bulk-peer-item" style="cursor: pointer" data-id="' +
peer.id + '" data-name="' + name + '">' + name + '<br><code>' + peer.id + '</code></a>');
});
configurations.deleteBulkModal().toggle();
});
/**
* When the item or tag of delete peers by bulk got clicked
*/
$body.on("click", ".delete-bulk-peer-item", function() {
configurations.toggleDeleteByBulkIP($(this));
}).on("click", ".delete-peer-bulk-badge", function() {
configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='" + $(this).data("id") + "']"));
});
let $selected_peer_list = document.getElementById("selected_peer_list");
/**
* The change observer to observe when user choose 1 or more peers to delete
* @type {MutationObserver}
*/
let changeObserver = new MutationObserver(function() {
if ($selected_peer_list.hasChildNodes()) {
$("#confirm_delete_bulk_peers").removeAttr("disabled");
} else {
$("#confirm_delete_bulk_peers").attr("disabled", "disabled");
}
});
changeObserver.observe($selected_peer_list, {
attributes: true,
childList: true,
characterData: true
});
let confirm_delete_bulk_peers_interval;
/**
* When the user clicked the delete button in the delete peers by bulk
*/
$("#confirm_delete_bulk_peers").on("click", function() {
let btn = $(this);
if (confirm_delete_bulk_peers_interval !== undefined) {
clearInterval(confirm_delete_bulk_peers_interval);
confirm_delete_bulk_peers_interval = undefined;
btn.html("Delete");
} else {
let timer = 5;
btn.html(`Deleting in ${timer} secs... Click to cancel`);
confirm_delete_bulk_peers_interval = setInterval(function() {
timer -= 1;
btn.html(`Deleting in ${timer} secs... Click to cancel`);
if (timer === 0) {
btn.html(`Deleting...`);
btn.attr("disabled", "disabled");
let ips = [];
$selected_peer_list.childNodes.forEach((ele) => ips.push(ele.dataset.id));
configurations.deletePeers(configurations.getConfigurationName(), ips);
clearInterval(confirm_delete_bulk_peers_interval);
confirm_delete_bulk_peers_interval = undefined;
}
}, 1000);
}
});
/**
* Select all peers to delete
*/
$("#select_all_delete_bulk_peers").on("click", function() {
$(".delete-bulk-peer-item").each(function() {
if (!$(this).hasClass("active")) {
configurations.toggleDeleteByBulkIP($(this));
}
});
});
/**
* When delete peers by bulk window is hidden
*/
$(configurations.deleteBulkModal()._element).on("hidden.bs.modal", function() {
$(".delete-bulk-peer-item").each(function() {
if ($(this).hasClass("active")) {
configurations.toggleDeleteByBulkIP($(this));
}
});
});
/**
* ==============
* Download Peers
* ==============
*/
/**
* When the download peers button got clicked
*/
$body.on("click", ".btn-download-peer", function(e) {
e.preventDefault();
let link = $(this).attr("href");
$.ajax({
"url": link,
"method": "GET",
success: function(res) {
configurations.downloadOneConfig(res);
}
});
});
/**
* When the download all peers got clicked
*/
$("#download_all_peers").on("click", function() {
$.ajax({
"url": `/download_all/${configurations.getConfigurationName()}`,
"method": "GET",
success: function(res) {
if (res.peers.length > 0) {
window.wireguard.generateZipFiles(res);
showToast("Peers' zip file download successful!");
} else {
showToast("Oops! There are no peer can be download.");
}
}
});
});

File diff suppressed because one or more lines are too long

View File

@ -1,243 +0,0 @@
let emptyInputFeedback = "Can't leave empty";
$('[data-toggle="tooltip"]').tooltip()
let $add_configuration = $("#add_configuration");
let addConfigurationModal = $("#addConfigurationModal");
$(".bottomNavHome").addClass("active");
addConfigurationModal.modal({
keyboard: false,
backdrop: 'static',
show: false
});
addConfigurationModal.on("hidden.bs.modal", function(){
$("#add_configuration_form").trigger("reset");
$("#add_configuration_form input").removeClass("is-valid").removeClass("is-invalid");
$(".addConfigurationAvailableIPs").text("N/A");
});
$(".toggle--switch").on("change", function(){
$(this).addClass("waiting").attr("disabled", "disabled");
let id = $(this).data("conf-id");
let status = $(this).prop("checked");
let ele = $(this);
let label = $(this).siblings("label");
$.ajax({
url: `/switch/${id}`
}).done(function(res){
let dot = $(`div[data-conf-id="${id}"] .dot`);
if (res.status){
if (status){
dot.removeClass("dot-stopped").addClass("dot-running");
dot.siblings().text("Running");
showToast(`${id} is running.`);
}else{
dot.removeClass("dot-running").addClass("dot-stopped");
showToast(`${id} is stopped.`);
}
}else{
ele.parents().children(".card-message").html(`<pre class="index-alert">Configuration toggle failed. Please check the following error message:<br><code>${res.message}</code></pre>`)
showToast(`${id} toggled failed.`, true);
if (status){
ele.prop("checked", false)
}else{
ele.prop("checked", true)
}
}
ele.removeClass("waiting").removeAttr("disabled");
})
});
$(".sb-home-url").addClass("active");
$(".card-body").on("click", function(handle){
if ($(handle.target).attr("class") !== "toggleLabel" && $(handle.target).attr("class") !== "toggle--switch") {
let c = $(".card");
for (let i of c){
if (i != $(this).parent()[0]){
$(i).css("transition", "ease-in-out 0.3s").css("opacity", "0.5")
}
}
window.open($(this).find("a").attr("href"), "_self");
}
});
function genKeyPair(){
let keyPair = window.wireguard.generateKeypair();
$("#addConfigurationPrivateKey").val(keyPair.privateKey).data("checked", true);
}
$("#reGeneratePrivateKey").on("click", function() {
genKeyPair();
});
$("#toggleAddConfiguration").on("click", function(){
addConfigurationModal.modal('toggle');
genKeyPair()
});
$("#addConfigurationPrivateKey").on("change", function() {
$privateKey = $(this);
$privateKeyFeedback = $("#addConfigurationPrivateKeyFeedback");
if ($privateKey.val().length != 44){
invalidInput($privateKey, $privateKeyFeedback, "Invalid length");
}else{
validInput($privateKey);
}
});
function ajaxPostJSON(url, data, doneFunc){
$.ajax({
url: url,
method: "POST",
data: JSON.stringify(data),
headers: {"Content-Type": "application/json"}
}).done(function (res) {
doneFunc(res);
});
}
function validInput(input){
input.removeClass("is-invalid").addClass("is-valid").removeAttr("disabled").data("checked", true);
}
function invalidInput(input, feedback, text){
input.removeClass("is-valid").addClass("is-invalid").removeAttr("disabled").data("checked", false);
feedback.addClass("invalid-feedback").text(text);
}
function checkPort($this){
let port = $this;
port.attr("disabled", "disabled");
let portFeedback = $("#addConfigurationListenPortFeedback");
if (port.val().length == 0){
invalidInput(port, portFeedback, emptyInputFeedback)
}else{
function done(res){
if(res.status){
validInput(port);
}else{
invalidInput(port, portFeedback, res.reason)
}
}
ajaxPostJSON('/api/addConfigurationPortCheck', {"port": port.val()}, done);
}
}
$("#addConfigurationListenPort").on("change", function(){
checkPort($(this));
})
function checkAddress($this){
let address = $this;
address.attr("disabled", "disabled");
let availableIPs = $(".addConfigurationAvailableIPs");
let addressFeedback = $("#addConfigurationAddressFeedback");
if (address.val().length == 0){
invalidInput(address, addressFeedback, emptyInputFeedback);
availableIPs.html(`N/A`);
}else{
function done(res){
if (res.status){
availableIPs.html(`<strong>${res.data}</strong>`);
validInput(address);
}else{
invalidInput(address, addressFeedback, res.reason);
availableIPs.html(`N/A`);
}
}
ajaxPostJSON("/api/addConfigurationAddressCheck", {"address": address.val()}, done)
}
}
$("#addConfigurationAddress").on("change", function(){
checkAddress($(this));
});
function checkName($this){
let name = $this;
let nameFeedback = $("#addConfigurationNameFeedback");
name.val(name.val().replace(/\s/g,'')).attr("disabled", "disabled");
if (name.val().length === 0){
invalidInput(name, nameFeedback, emptyInputFeedback)
}else{
function done(res){
if (res.status){
validInput(name);
}else{
invalidInput(name, nameFeedback, res.reason);
}
}
ajaxPostJSON("/api/addConfigurationNameCheck", {"name": name.val()}, done);
}
}
$("#addConfigurationName").on("change", function(){
checkName($(this));
});
$("#addConfigurationBtn").on("click", function(){
let btn = $(this);
let input = $("#add_configuration_form input");
let filled = true;
for (let i = 0; i < input.length; i++){
let $i = $(input[i]);
if ($i.attr("required") != undefined){
if ($i.val().length == 0 && $i.attr("name") !== "addConfigurationPrivateKey"){
invalidInput($i, $i.siblings(".input-feedback"), emptyInputFeedback);
filled = false;
}
if ($i.val().length != 44 && $i.attr("name") == "addConfigurationPrivateKey"){
invalidInput($i, $i.siblings(".input-feedback"), "Invalid length");
filled = false;
}
if (!$i.data("checked")){
filled = false;
}
}
}
if (filled){
$("#addConfigurationModal .modal-footer .btn").hide();
$(".addConfigurationStatus").removeClass("d-none");
let data = {};
let q = [];
for (let i = 0; i < input.length; i++){
let $i = $(input[i]);
data[$i.attr("name")] = $i.val();
q.push($i.attr("name"));
}
let done = (res) => {
let name = res.data;
$(".addConfigurationAddStatus").removeClass("text-primary").addClass("text-success").html(`<i class="bi bi-check-circle-fill"></i> ${name} added successfully.`);
if (res.status){
setTimeout(() => {
$(".addConfigurationToggleStatus").removeClass("waiting").html(`<div class="spinner-border spinner-border-sm" role="status"></div> Toggle Configuration`)
$.ajax({
url: `/switch/${name}`
}).done(function(res){
if (res.status){
$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-success").html(`<i class="bi bi-check-circle-fill"></i> Toggle Successfully. Refresh in 5 seconds.`);
setTimeout(() => {
$(".addConfigurationToggleStatus").text("Refeshing...")
location.reload();
}, 5000);
}else{
$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-danger").html(`<i class="bi bi-x-circle-fill"></i> ${name} toggle failed.`)
$("#addCconfigurationAlertMessage").removeClass("d-none").html(`${name} toggle failed. Please check the following error message:<br>${res.message}`);
}
});
}, 500);
}else{
$(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(`<i class="bi bi-x-circle-fill"></i> ${name} adding failed.`)
$("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason);
}
};
ajaxPostJSON("/api/addConfiguration", data, done);
}
});

File diff suppressed because one or more lines are too long

View File

@ -1,38 +0,0 @@
let wrapper = $(".bottomNavWrapper");
$(".bottomNavConfigs").on("click", function(){
let subNav = $(this).children(".subNav");
subNav.removeClass("animate__fadeOutDown").addClass("active animate__fadeInUp");
wrapper.fadeIn();
});
$(".bottomNavHome").on("click", function(){
window.location.replace('/')
});
$(".bottomNavSettings").on("click", function(){
window.location.replace('/settings')
})
function hideBottomSubNav(){
$(".bottomNavButton .subNav").removeClass("animate__fadeInUp").addClass("animate__fadeOutDown");
wrapper.fadeOut();
setTimeout(function(){
$(".bottomNavButton .subNav").removeClass("active");
},350)
}
wrapper.on("click", function(){
hideBottomSubNav();
});
$(".bottomNavMore").on("click", function(){
let subNav = $(this).children(".subNav");
subNav.removeClass("animate__fadeOutDown").addClass("active animate__fadeInUp");
wrapper.fadeIn();
});
// $(".bottomNavButton .nav-conf-link").on("click", function(){
// hideBottomSubNav();
// })

View File

@ -1,60 +0,0 @@
$(".sb-settings-url").addClass("active")
$(".confirm_modal").click(function () {
$(".app_new_ip").html($("#app_ip")[0].value)
$(".app_new_port").html($("#app_port")[0].value)
})
$(".confirm_restart").click(function () {
$(".cancel_restart").remove()
countdown = 7;
$.post('/update_app_ip_port', $('.update_app_ip_port').serialize())
url = $("#app_ip")[0].value + ":" + $("#app_port")[0].value;
$(".confirm_restart").attr("disabled", "disabled")
setInterval(function () {
if (countdown === 0) {
window.location.replace("http://" + url);
}
$(".confirm_restart").html("Redirecting you in " + countdown + " seconds.")
countdown--;
}, 1000)
});
$(".change_path").click(function () {
$(this).attr("disabled", "disabled");
countdown = 5;
setInterval(function () {
if (countdown === 0) {
location.reload()
}
$(".change_path").html("Redirecting you in " + countdown + " seconds.")
countdown--;
}, 1000)
$.post('/update_wg_conf_path', $('.update_wg_conf_path').serialize())
});
$(".bottomNavSettings").addClass("active");
$(".theme-switch-btn").on("click", function(){
if (!$(this).hasClass("active")){
let theme = $(this).data("theme");
$(".theme-switch-btn").removeClass("active");
$(this).addClass("active");
$.ajax({
method: "POST",
url: "/api/settings/setTheme",
headers: {"Content-Type": "application/json"},
data: JSON.stringify({"theme": theme})
}).done(function(res){
if (res.status == true){
if (theme == "light"){
$("#darkThemeCSS").remove();
showToast("Switched to light theme");
}else{
$("head").append('<link rel="stylesheet" type="text/css" href="/static/css/theme/dark.min.css" id="darkThemeCSS">');
showToast("Switched to dark theme");
}
}
});
}
});

View File

@ -1 +0,0 @@
$(".sb-settings-url").addClass("active");$(".confirm_modal").click(function(){$(".app_new_ip").html($("#app_ip")[0].value);$(".app_new_port").html($("#app_port")[0].value)});$(".confirm_restart").click(function(){$(".cancel_restart").remove();countdown=7;$.post("/update_app_ip_port",$(".update_app_ip_port").serialize());url=$("#app_ip")[0].value+":"+$("#app_port")[0].value;$(".confirm_restart").attr("disabled","disabled");setInterval(function(){if(countdown===0){window.location.replace("http://"+url)}$(".confirm_restart").html("Redirecting you in "+countdown+" seconds.");countdown--},1e3)});$(".change_path").click(function(){$(this).attr("disabled","disabled");countdown=5;setInterval(function(){if(countdown===0){location.reload()}$(".change_path").html("Redirecting you in "+countdown+" seconds.");countdown--},1e3);$.post("/update_wg_conf_path",$(".update_wg_conf_path").serialize())});$(".bottomNavSettings").addClass("active");$(".theme-switch-btn").on("click",function(){if(!$(this).hasClass("active")){let theme=$(this).data("theme");$(".theme-switch-btn").removeClass("active");$(this).addClass("active");$.ajax({method:"POST",url:"/api/settings/setTheme",headers:{"Content-Type":"application/json"},data:JSON.stringify({theme:theme})}).done(function(res){if(res.status==true){if(theme=="light"){$("#darkThemeCSS").remove();showToast("Switched to light theme")}else{$("head").append('<link rel="stylesheet" type="text/css" href="/static/css/theme/dark.min.css" id="darkThemeCSS">');showToast("Switched to dark theme")}}})}});

View File

@ -1,90 +0,0 @@
/**
* tools.js - Copyright(C) 2021 Donald Zou [https://github.com/donaldzou]
*/
$(".ip_dropdown").on("change",function (){
$(".modal.show .btn").removeAttr("disabled");
});
$(".conf_dropdown").on("change", function (){
$(".modal.show .ip_dropdown").html('<option value="none" selected="selected" disabled>Loading...');
$.ajax({
url: "/get_ping_ip",
method: "POST",
data: "config=" + $(this).children("option:selected").val(),
success: function (res){
$(".modal.show .ip_dropdown").html("");
$(".modal.show .ip_dropdown").append('<option value="none" selected="selected" disabled>Choose an IP');
$(".modal.show .ip_dropdown").append(res);
}
});
});
// Ping Tools
$(".send_ping").on("click", function (){
$(this).attr("disabled","disabled");
$(this).html("Pinging...");
$("#ping_modal .form-control").attr("disabled","disabled");
$.ajax({
method:"POST",
data: "ip="+ $(':selected', $("#ping_modal .ip_dropdown")).val() +
"&count=" + $("#ping_modal .ping_count").val(),
url: "/ping_ip",
success: function (res){
$(".ping_result tbody").html("");
let html = '<tr><th scope="row">Address</th><td>'+res.address+'</td></tr>' +
'<tr><th scope="row">Is Alive</th><td>'+res.is_alive+'</td></tr>' +
'<tr><th scope="row">Min RTT</th><td>'+res.min_rtt+'ms</td></tr>' +
'<tr><th scope="row">Average RTT </th><td>'+res.avg_rtt+'ms</td></tr>' +
'<tr><th scope="row">Max RTT</th><td>'+res.max_rtt+'ms</td></tr>' +
'<tr><th scope="row">Package Sent</th><td>'+res.package_sent+'</td></tr>' +
'<tr><th scope="row">Package Received</th><td>'+res.package_received+'</td></tr>' +
'<tr><th scope="row">Package Loss</th><td>'+res.package_loss+'</td></tr>';
$(".ping_result tbody").html(html);
$(".send_ping").removeAttr("disabled");
$(".send_ping").html("Ping");
$("#ping_modal .form-control").removeAttr("disabled");
}
});
});
// Traceroute Tools
$(".send_traceroute").on("click", function (){
$(this).attr("disabled","disabled");
$(this).html("Tracing...");
$("#traceroute_modal .form-control").attr("disabled","disabled");
$.ajax({
url: "/traceroute_ip",
method: "POST",
data: "ip=" + $(':selected', $("#traceroute_modal .ip_dropdown")).val(),
success: function (res){
$(".traceroute_result tbody").html("");
res.forEach((ele) =>
$(".traceroute_result tbody").append('<tr><th scope="row">'+ele.hop+'</th><td>'+ele.ip+'</td><td>'+ele.avg_rtt+'</td><td>'+ele.min_rtt+'</td><td>'+ele.max_rtt+'</td></tr>'));
$(".send_traceroute").removeAttr("disabled").html("Traceroute");
$("#traceroute_modal .form-control").removeAttr("disabled");
}
});
});
let numberToast = 0;
function showToast(msg, isDanger = false) {
$(".toastContainer").append(
`<div id="${numberToast}-toast" class="toast hide animate__animated animate__fadeInUp" role="alert" data-delay="5000">
<div class="toast-header">
<strong class="mr-auto">WGDashboard</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="toast-body ${isDanger ? 'text-danger':''}">${msg}</div>
<div class="toast-progressbar ${isDanger ? 'bg-danger':''}"></div>
</div>` )
$(`#${numberToast}-toast`).toast('show');
$(`#${numberToast}-toast .toast-body`).html(msg);
$(`#${numberToast}-toast .toast-progressbar`).css("transition", `width ${$(`#${numberToast}-toast .toast-progressbar`).parent().data('delay')}ms cubic-bezier(0, 0, 0, 0)`);
$(`#${numberToast}-toast .toast-progressbar`).css("width", "0px");
let i = numberToast;
setTimeout(function(){
$(`#${i}-toast`).removeClass("animate__fadeInUp").addClass("animate__fadeOutRight")
}, 4500)
numberToast++;
}

View File

@ -1,10 +0,0 @@
$(".ip_dropdown").on("change",function(){$(".modal.show .btn").removeAttr("disabled")});$(".conf_dropdown").on("change",function(){$(".modal.show .ip_dropdown").html('<option value="none" selected="selected" disabled>Loading...');$.ajax({url:"/get_ping_ip",method:"POST",data:"config="+$(this).children("option:selected").val(),success:function(res){$(".modal.show .ip_dropdown").html("");$(".modal.show .ip_dropdown").append('<option value="none" selected="selected" disabled>Choose an IP');$(".modal.show .ip_dropdown").append(res)}})});$(".send_ping").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Pinging...");$("#ping_modal .form-control").attr("disabled","disabled");$.ajax({method:"POST",data:"ip="+$(":selected",$("#ping_modal .ip_dropdown")).val()+"&count="+$("#ping_modal .ping_count").val(),url:"/ping_ip",success:function(res){$(".ping_result tbody").html("");let html='<tr><th scope="row">Address</th><td>'+res.address+"</td></tr>"+'<tr><th scope="row">Is Alive</th><td>'+res.is_alive+"</td></tr>"+'<tr><th scope="row">Min RTT</th><td>'+res.min_rtt+"ms</td></tr>"+'<tr><th scope="row">Average RTT </th><td>'+res.avg_rtt+"ms</td></tr>"+'<tr><th scope="row">Max RTT</th><td>'+res.max_rtt+"ms</td></tr>"+'<tr><th scope="row">Package Sent</th><td>'+res.package_sent+"</td></tr>"+'<tr><th scope="row">Package Received</th><td>'+res.package_received+"</td></tr>"+'<tr><th scope="row">Package Loss</th><td>'+res.package_loss+"</td></tr>";$(".ping_result tbody").html(html);$(".send_ping").removeAttr("disabled");$(".send_ping").html("Ping");$("#ping_modal .form-control").removeAttr("disabled")}})});$(".send_traceroute").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Tracing...");$("#traceroute_modal .form-control").attr("disabled","disabled");$.ajax({url:"/traceroute_ip",method:"POST",data:"ip="+$(":selected",$("#traceroute_modal .ip_dropdown")).val(),success:function(res){$(".traceroute_result tbody").html("");res.forEach(ele=>$(".traceroute_result tbody").append('<tr><th scope="row">'+ele.hop+"</th><td>"+ele.ip+"</td><td>"+ele.avg_rtt+"</td><td>"+ele.min_rtt+"</td><td>"+ele.max_rtt+"</td></tr>"));$(".send_traceroute").removeAttr("disabled").html("Traceroute");$("#traceroute_modal .form-control").removeAttr("disabled")}})});let numberToast=0;function showToast(msg,isDanger=false){$(".toastContainer").append(`<div id="${numberToast}-toast" class="toast hide animate__animated animate__fadeInUp" role="alert" data-delay="5000">
<div class="toast-header">
<strong class="mr-auto">WGDashboard</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="toast-body ${isDanger?"text-danger":""}">${msg}</div>
<div class="toast-progressbar ${isDanger?"bg-danger":""}"></div>
</div>`);$(`#${numberToast}-toast`).toast("show");$(`#${numberToast}-toast .toast-body`).html(msg);$(`#${numberToast}-toast .toast-progressbar`).css("transition",`width ${$(`#${numberToast}-toast .toast-progressbar`).parent().data("delay")}ms cubic-bezier(0, 0, 0, 0)`);$(`#${numberToast}-toast .toast-progressbar`).css("width","0px");let i=numberToast;setTimeout(function(){$(`#${i}-toast`).removeClass("animate__fadeInUp").addClass("animate__fadeOutRight")},4500);numberToast++}

View File

@ -1,313 +0,0 @@
/*! SPDX-License-Identifier: GPL-2.0
*
* Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
*/
(function() {
function gf(init) {
var r = new Float64Array(16);
if (init) {
for (var i = 0; i < init.length; ++i)
r[i] = init[i];
}
return r;
}
function pack(o, n) {
var b, m = gf(), t = gf();
for (var i = 0; i < 16; ++i)
t[i] = n[i];
carry(t);
carry(t);
carry(t);
for (var j = 0; j < 2; ++j) {
m[0] = t[0] - 0xffed;
for (var i = 1; i < 15; ++i) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
cswap(t, m, 1 - b);
}
for (var i = 0; i < 16; ++i) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function carry(o) {
var c;
for (var i = 0; i < 16; ++i) {
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
o[i] &= 0xffff;
}
}
function cswap(p, q, b) {
var t, c = ~(b - 1);
for (var i = 0; i < 16; ++i) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function add(o, a, b) {
for (var i = 0; i < 16; ++i)
o[i] = (a[i] + b[i]) | 0;
}
function subtract(o, a, b) {
for (var i = 0; i < 16; ++i)
o[i] = (a[i] - b[i]) | 0;
}
function multmod(o, a, b) {
var t = new Float64Array(31);
for (var i = 0; i < 16; ++i) {
for (var j = 0; j < 16; ++j)
t[i + j] += a[i] * b[j];
}
for (var i = 0; i < 15; ++i)
t[i] += 38 * t[i + 16];
for (var i = 0; i < 16; ++i)
o[i] = t[i];
carry(o);
carry(o);
}
function invert(o, i) {
var c = gf();
for (var a = 0; a < 16; ++a)
c[a] = i[a];
for (var a = 253; a >= 0; --a) {
multmod(c, c, c);
if (a !== 2 && a !== 4)
multmod(c, c, i);
}
for (var a = 0; a < 16; ++a)
o[a] = c[a];
}
function clamp(z) {
z[31] = (z[31] & 127) | 64;
z[0] &= 248;
}
function generatePublicKey(privateKey) {
var r, z = new Uint8Array(32);
var a = gf([1]),
b = gf([9]),
c = gf(),
d = gf([1]),
e = gf(),
f = gf(),
_121665 = gf([0xdb41, 1]),
_9 = gf([9]);
for (var i = 0; i < 32; ++i)
z[i] = privateKey[i];
clamp(z);
for (var i = 254; i >= 0; --i) {
r = (z[i >>> 3] >>> (i & 7)) & 1;
cswap(a, b, r);
cswap(c, d, r);
add(e, a, c);
subtract(a, a, c);
add(c, b, d);
subtract(b, b, d);
multmod(d, e, e);
multmod(f, a, a);
multmod(a, c, a);
multmod(c, b, e);
add(e, a, c);
subtract(a, a, c);
multmod(b, a, a);
subtract(c, d, f);
multmod(a, c, _121665);
add(a, a, d);
multmod(c, c, a);
multmod(a, d, f);
multmod(d, b, _9);
multmod(b, e, e);
cswap(a, b, r);
cswap(c, d, r);
}
invert(c, c);
multmod(a, a, c);
pack(z, a);
return z;
}
function generatePresharedKey() {
var privateKey = new Uint8Array(32);
window.crypto.getRandomValues(privateKey);
return privateKey;
}
function generatePrivateKey() {
var privateKey = generatePresharedKey();
clamp(privateKey);
return privateKey;
}
function encodeBase64(dest, src) {
var input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
for (var i = 0; i < 4; ++i)
dest[i] = input[i] + 65 +
(((25 - input[i]) >> 8) & 6) -
(((51 - input[i]) >> 8) & 75) -
(((61 - input[i]) >> 8) & 15) +
(((62 - input[i]) >> 8) & 3);
}
function keyToBase64(key) {
var i, base64 = new Uint8Array(44);
for (i = 0; i < 32 / 3; ++i)
encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
base64[43] = 61;
return String.fromCharCode.apply(null, base64);
}
function base64ToKey(base64) {
let binary_string = window.atob(base64);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
let uint8 = new Uint8Array(bytes.buffer);
return uint8;
}
function putU32(b, n)
{
b.push(n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, (n >>> 24) & 0xff);
}
function putU16(b, n)
{
b.push(n & 0xff, (n >>> 8) & 0xff);
}
function putBytes(b, a)
{
for (var i = 0; i < a.length; ++i)
b.push(a[i] & 0xff);
}
function encodeString(s)
{
var utf8 = unescape(encodeURIComponent(s));
var b = new Uint8Array(utf8.length);
for (var i = 0; i < utf8.length; ++i)
b[i] = utf8.charCodeAt(i);
return b;
}
function crc32(b)
{
if (!crc32.table) {
crc32.table = [];
for (var c = 0, n = 0; n < 256; c = ++n) {
for (var k = 0; k < 8; ++k)
c = ((c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1));
crc32.table[n] = c;
}
}
var crc = -1;
for (var i = 0; i < b.length; ++i)
crc = (crc >>> 8) ^ crc32.table[(crc ^ b[i]) & 0xff];
return (crc ^ (-1)) >>> 0;
}
function createZipFile(files)
{
var b = [];
var cd = [];
var offset = 0;
for (var i = 0; i < files.length; ++i) {
var name = encodeString(files[i].filename);
var contents = encodeString(files[i].content);
var crc = crc32(contents);
putU32(b, 0x04034b50); /* signature */
putU16(b, 20); /* version needed */
putU16(b, 0); /* flags */
putU16(b, 0); /* compression method */
putU16(b, 0); /* mtime */
putU16(b, 0); /* mdate */
putU32(b, crc); /* crc32 */
putU32(b, contents.length); /* compressed size */
putU32(b, contents.length); /* uncompressed size */
putU16(b, name.length); /* file name length */
putU16(b, 0); /* extra field length */
putBytes(b, name);
putBytes(b, contents);
putU32(cd, 0x02014b50); /* signature */
putU16(cd, 0); /* version made */
putU16(cd, 20); /* version needed */
putU16(cd, 0); /* flags */
putU16(cd, 0); /* compression method */
putU16(cd, 0); /* mtime */
putU16(cd, 0); /* mdate */
putU32(cd, crc); /* crc32 */
putU32(cd, contents.length); /* compressed size */
putU32(cd, contents.length); /* uncompressed size */
putU16(cd, name.length); /* file name length */
putU16(cd, 0); /* extra field length */
putU16(cd, 0); /* file comment length */
putU16(cd, 0); /* disk number start */
putU16(cd, 0); /* internal file attributes */
putU32(cd, 32); /* external file attributes - 'archive' bit set (32) */
putU32(cd, offset); /* relative offset of local header */
putBytes(cd, name); /* file name */
offset += 30 + contents.length + name.length
}
putBytes(b, cd); /* central directory */
putU32(b, 0x06054b50); /* end of central directory signature */
putU16(b, 0); /* number of this disk */
putU16(b, 0); /* number of disk with central directory start */
putU16(b, files.length); /* number of entries on disk */
putU16(b, files.length); /* number of entries */
putU32(b, cd.length); /* length of central directory */
putU32(b, offset); /* offset to start of central directory */
putU16(b, 0); /* zip comment size */
return Uint8Array.from(b);
}
window.wireguard = {
generateKeypair: function() {
var privateKey = generatePrivateKey();
var publicKey = generatePublicKey(privateKey);
var presharedKey = generatePresharedKey();
return {
publicKey: keyToBase64(publicKey),
privateKey: keyToBase64(privateKey),
presharedKey: keyToBase64(presharedKey)
};
},
generatePublicKey: function (privateKey){
privateKey = base64ToKey(privateKey);
return keyToBase64(generatePublicKey(privateKey));
},
generateZipFiles: function(res){
var files = res.peers;
var zipFile = createZipFile(files);
var blob = new Blob([zipFile], { type: "application/zip" });
var a = document.createElement("a");
a.download = res.filename;
a.href = URL.createObjectURL(blob);
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
})();