From 84c9846f7be795fea1f46d1fd74c60cfafafa7bd Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Wed, 19 Jan 2022 10:27:17 -0500 Subject: [PATCH 001/214] Hmmmm... What about SocketIO? --- src/dashboard.py | 25 ++++++++--- src/static/js/configuration.js | 71 +++++++++++++++++++++--------- src/static/js/configuration.min.js | 2 +- src/templates/configuration.html | 12 ++++- 4 files changed, 79 insertions(+), 31 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index 5fdcd204..934abf23 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -25,6 +25,8 @@ import ifcfg from flask import Flask, request, render_template, redirect, url_for, session, jsonify from flask_qrcode import QRcode from icmplib import ping, traceroute +# TESTING +from flask_socketio import SocketIO # Import other python files from util import regex_match, check_DNS, check_Allowed_IPs, check_remote_endpoint, \ @@ -49,7 +51,7 @@ app.secret_key = secrets.token_urlsafe(16) app.config['TEMPLATES_AUTO_RELOAD'] = True # Enable QR Code Generator QRcode(app) - +socketio = SocketIO(app) # TODO: use class and object oriented programming @@ -1001,17 +1003,26 @@ def configuration(config_name): # Get configuration details -@app.route('/get_config/', methods=['GET']) -def get_conf(config_name): +@socketio.on("get_config") +# @app.route('/get_config/', methods=['GET']) +def get_conf(data): """ Get configuration setting of wireguard interface. @param config_name: Name of WG interface @type config_name: str @return: TODO """ + if getattr(g, 'db', None) is None: + g.db = connect_db() + g.cur = g.db.cursor() + print(data) + config_name = data['config'] + print(config_name) config_interface = read_conf_file_interface(config_name) - search = request.args.get('search') + search = data['search'] + print(search) + # search = request.args.get('search') if len(search) == 0: search = "" search = urllib.parse.unquote(search) @@ -1042,7 +1053,8 @@ def get_conf(config_name): else: conf_data['checked'] = "checked" config.clear() - return jsonify(conf_data) + socketio.emit("get_config", conf_data, json=True) + # return jsonify(conf_data) # Turn on / off a configuration @@ -1714,4 +1726,5 @@ if __name__ == "__main__": app_port = config.get("Server", "app_port") WG_CONF_PATH = config.get("Server", "wg_conf_path") config.clear() - app.run(host=app_ip, debug=False, port=app_port) + socketio.run(app, host=app_ip, debug=False, port=app_port) + # app.run(host=app_ip, debug=False, port=app_port) diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 6976e3e0..9a613f81 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -338,29 +338,56 @@ * Load Peers from server to configuration page * @param searchString */ + let time = 0; + let count = 0; + + let d1 = new Date(); function loadPeers(searchString){ + d1 = new Date(); startProgressBar(); - let d1 = new Date(); - $.ajax({ - method: "GET", - url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`, - headers:{"Content-Type": "application/json"} - }).done(function(response){ - removeNoResponding(); - peers = response.peer_data; - configurationAlert(response); - configurationHeader(response); - configurationPeers(response); - $(".dot.dot-running").attr("title","Peer Connected").tooltip(); - $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); - $("i[data-toggle='tooltip']").tooltip(); - endProgressBar(); - let d2 = new Date(); - let seconds = (d2 - d1); - $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); - }).fail(function(){ - noResponding(); - }); + socket.emit('get_config', {"config": conf_name, "search": searchString}); + + // let d1 = new Date(); + // $.ajax({ + // method: "GET", + // url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`, + // headers:{"Content-Type": "application/json"} + // }).done(function(response){ + // removeNoResponding(); + // peers = response.peer_data; + // configurationAlert(response); + // configurationHeader(response); + // configurationPeers(response); + // $(".dot.dot-running").attr("title","Peer Connected").tooltip(); + // $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); + // $("i[data-toggle='tooltip']").tooltip(); + // endProgressBar(); + // let d2 = new Date(); + // let seconds = (d2 - d1); + // $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); + // }).fail(function(){ + // noResponding(); + // }); + } + + function parsePeers(response){ + let d2 = new Date(); + let seconds = (d2 - d1); + time += seconds + count += 1 + window.console.log(`Average time: ${time/count}ms`); + $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); + removeNoResponding(); + peers = response.peer_data; + configurationAlert(response); + configurationHeader(response); + configurationPeers(response); + $(".dot.dot-running").attr("title","Peer Connected").tooltip(); + $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); + $("i[data-toggle='tooltip']").tooltip(); + endProgressBar(); + + } /** @@ -502,7 +529,7 @@ loadPeers: (searchString) => { loadPeers(searchString); }, addPeersByBulk: () => { addPeersByBulk(); }, deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); }, - + parsePeers: (response) => { parsePeers(response); }, getAvailableIps: () => { getAvailableIps(); }, generateKeyPair: () => { generate_key(); }, diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index 4a63dd13..66aec898 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1 +1 @@ -(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name='
'+'
'+(peer.name===""?"Untitled":peer.name)+"
"+'
'+"
";let peer_transfer='

'+roundN(peer.total_receive+total_r,4)+' GB

'+roundN(peer.total_sent+total_s,4)+" GB

";let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}function loadPeers(searchString){startProgressBar();let d1=new Date;$.ajax({method:"GET",url:`/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar();let d2=new Date;let seconds=d2-d1;$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`)}).fail(function(){noResponding()})}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=$add_peer.getAttribute("conf_id");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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file +(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name='
'+'
'+(peer.name===""?"Untitled":peer.name)+"
"+'
'+"
";let peer_transfer='

'+roundN(peer.total_receive+total_r,4)+' GB

'+roundN(peer.total_sent+total_s,4)+" GB

";let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;startProgressBar();socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=$add_peer.getAttribute("conf_id");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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index a7f2ce06..aad85b48 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -410,7 +410,7 @@ {% include "tools.html" %} {% include "footer.html" %} - + \ No newline at end of file From 264a050360fe24f83e1e807a6bfcb7bfea7c1875 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Mon, 28 Feb 2022 13:34:46 -0500 Subject: [PATCH 002/214] Temp fix --- src/static/css/dashboard.css | 30 ++++++++++++++++++++++++++---- src/static/css/dashboard.min.css | 2 +- src/static/js/configuration.js | 18 +++++++++++++----- src/static/js/configuration.min.js | 12 +++++++++++- src/templates/index.html | 2 +- 5 files changed, 52 insertions(+), 12 deletions(-) diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 9352423b..aa9993e7 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -122,7 +122,7 @@ body { height: 10px; border-radius: 50px; display: inline-block; - margin-left: 10px; + margin-left: auto !important; } .dot-running{ @@ -231,9 +231,17 @@ body { background: white; } -/*.peer_data_group{*/ -/* text-align: right;*/ -/*}*/ +.peer_data_group{ + text-align: right; + display: flex; + margin-bottom: 0.5rem +} + +.peer_data_group p{ + text-transform: uppercase; + margin-bottom: 0; + margin-right: 1rem +} @media (max-width: 768px) { .peer_data_group{ @@ -548,4 +556,18 @@ pre.index-alert{ border-radius: .25rem; margin-top: 1rem; color: white; +} + +.peerNameCol{ + display: flex; + align-items: center; + margin-bottom: 0.2rem +} + +.peerName{ + margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} + +.peerLightContainer{ + text-transform: uppercase; margin: 0; margin-left: auto !important; } \ No newline at end of file diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index ed64c6fb..597483fc 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:10px}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff} \ No newline at end of file +@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 9a613f81..6943337b 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -96,11 +96,19 @@ total_s += peer.cumu_sent; let spliter = '
'; let peer_name = - '
' + - '
'+ (peer.name === "" ? "Untitled" : peer.name) +'
' + - '
' + - '
'; - let peer_transfer = '

'+ roundN(peer.total_receive + total_r, 4) +' GB

'+ roundN(peer.total_sent + total_s, 4) +' GB

'; + `
+
${peer.name === "" ? "Untitled" : peer.name}
+
+
`; + let peer_transfer = + `
+

+ ${roundN(peer.total_receive + total_r, 4)} GB +

+

+ ${roundN(peer.total_sent + total_s, 4)} GB +

+
`; let peer_key = '
PEERCLICK TO COPY
'+peer.id+'
'; let peer_allowed_ip = '
ALLOWED IP
'+peer.allowed_ip+'
'; let peer_latest_handshake = '
LATEST HANDSHAKE
'+peer.latest_handshake+'
'; diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index e8c0123e..3cfa7cd0 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1 +1,11 @@ -(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name='
'+'
'+(peer.name===""?"Untitled":peer.name)+"
"+'
'+"
";let peer_transfer='

'+roundN(peer.total_receive+total_r,4)+' GB

'+roundN(peer.total_sent+total_s,4)+" GB

";let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;startProgressBar();socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=$add_peer.getAttribute("conf_id");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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); +(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+
${peer.name===""?"Untitled":peer.name}
+
+
`;let peer_transfer=`
+

+ ${roundN(peer.total_receive+total_r,4)} GB +

+

+ ${roundN(peer.total_sent+total_s,4)} GB +

+
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;startProgressBar();socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=$add_peer.getAttribute("conf_id");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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/templates/index.html b/src/templates/index.html index 3d643af5..a9e0d64c 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -73,6 +73,6 @@ if ($(handle.target).attr("class") !== "bi bi-toggle2-off" && $(handle.target).attr("class") !== "bi bi-toggle2-on") { window.open($(this).find("a").attr("href"), "_self"); } - }) + }); \ No newline at end of file From 8fe82095802ea187e2256cffb92c6611acb5a325 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Thu, 3 Mar 2022 08:46:23 -0500 Subject: [PATCH 003/214] Added line graph using chart.js & Improving websocket. Added line graph to show total receive & total sent changes per refresh interval, using chart.js line chart to show the changes. Switching configuration don't need to refresh anymore, by using websocket. --- src/dashboard.py | 115 +++++++++++-------- src/static/css/dashboard.css | 41 +++++-- src/static/css/dashboard.min.css | 2 +- src/static/js/configuration.js | 175 +++++++++++++++++++---------- src/static/js/configuration.min.js | 4 +- src/templates/configuration.html | 144 ++++++++++++++++++++---- src/templates/header.html | 1 + src/templates/sidebar.html | 2 +- 8 files changed, 342 insertions(+), 142 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index 63ae9171..267131bc 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -120,7 +120,7 @@ def get_conf_running_peer_number(config_name): data_usage = subprocess.check_output(f"wg show {config_name} latest-handshakes", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: - return "stopped" + return 0 data_usage = data_usage.decode("UTF-8").split() count = 0 now = datetime.now() @@ -143,16 +143,19 @@ def read_conf_file_interface(config_name): """ conf_location = WG_CONF_PATH + "/" + config_name + ".conf" - with open(conf_location, 'r', encoding='utf-8') as file_object: - file = file_object.read().split("\n") - data = {} - for i in file: - if not regex_match("#(.*)", i): - if len(i) > 0: - if i != "[Interface]": - tmp = re.split(r'\s*=\s*', i, 1) - if len(tmp) == 2: - data[tmp[0]] = tmp[1] + try: + with open(conf_location, 'r', encoding='utf-8') as file_object: + file = file_object.read().split("\n") + data = {} + for i in file: + if not regex_match("#(.*)", i): + if len(i) > 0: + if i != "[Interface]": + tmp = re.split(r'\s*=\s*', i, 1) + if len(tmp) == 2: + data[tmp[0]] = tmp[1] + except FileNotFoundError as e: + return {} return data @@ -1013,49 +1016,59 @@ def get_conf(data): @type config_name: str @return: TODO """ + result = { + "status": True, + "message": "", + "data": {} + } + if not session: + result["status"] = False + result["message"] = "Oops!
You're not signed in. Please refresh your page." + socketio.emit("get_config", result, json=True) + return + if getattr(g, 'db', None) is None: g.db = connect_db() g.cur = g.db.cursor() - print(data) config_name = data['config'] - print(config_name) - config_interface = read_conf_file_interface(config_name) - search = data['search'] - print(search) - # search = request.args.get('search') - if len(search) == 0: - search = "" - search = urllib.parse.unquote(search) - config = get_dashboard_conf() - sort = config.get("Server", "dashboard_sort") - peer_display_mode = config.get("Peers", "peer_display_mode") - wg_ip = config.get("Peers", "remote_endpoint") - if "Address" not in config_interface: - conf_address = "N/A" + + if config_interface != {}: + search = data['search'] + if len(search) == 0: + search = "" + search = urllib.parse.unquote(search) + config = get_dashboard_conf() + sort = config.get("Server", "dashboard_sort") + peer_display_mode = config.get("Peers", "peer_display_mode") + wg_ip = config.get("Peers", "remote_endpoint") + if "Address" not in config_interface: + conf_address = "N/A" + else: + conf_address = config_interface['Address'] + result['data'] = { + "peer_data": get_peers(config_name, search, sort), + "name": config_name, + "status": get_conf_status(config_name), + "total_data_usage": get_conf_total_data(config_name), + "public_key": get_conf_pub_key(config_name), + "listen_port": get_conf_listen_port(config_name), + "running_peer": get_conf_running_peer_number(config_name), + "conf_address": conf_address, + "wg_ip": wg_ip, + "sort_tag": sort, + "dashboard_refresh_interval": int(config.get("Server", "dashboard_refresh_interval")), + "peer_display_mode": peer_display_mode + } + if result['data']['status'] == "stopped": + result['data']['checked'] = "nope" + else: + result['data']['checked'] = "checked" + config.clear() else: - conf_address = config_interface['Address'] - conf_data = { - "peer_data": get_peers(config_name, search, sort), - "name": config_name, - "status": get_conf_status(config_name), - "total_data_usage": get_conf_total_data(config_name), - "public_key": get_conf_pub_key(config_name), - "listen_port": get_conf_listen_port(config_name), - "running_peer": get_conf_running_peer_number(config_name), - "conf_address": conf_address, - "wg_ip": wg_ip, - "sort_tag": sort, - "dashboard_refresh_interval": int(config.get("Server", "dashboard_refresh_interval")), - "peer_display_mode": peer_display_mode - } - if conf_data['status'] == "stopped": - conf_data['checked'] = "nope" - else: - conf_data['checked'] = "checked" - config.clear() - socketio.emit("get_config", conf_data, json=True) - # return jsonify(conf_data) + result['status'] = False + result['message'] = "I cannot find this configuration.
Please refresh and try again" + socketio.emit("get_config", result, json=True) # Turn on / off a configuration @@ -1334,7 +1347,11 @@ def get_peer_name(config_name): # Return available IPs @app.route('/available_ips/', methods=['GET']) def available_ips(config_name): - return jsonify(f_available_ips(config_name)) + result = {"status": True, "message":"", "data": f_available_ips(config_name)} + if len(result["data"]) == 0: + result['status'] = False + result['message'] = f"No more available IP for {config_name}." + return jsonify(result) # Check if both key match diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index aa9993e7..af9b5a85 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -9,6 +9,10 @@ body { vertical-align: text-bottom; } +.btn-primary{ + font-weight: bold; +} + /* * Sidebar */ @@ -23,12 +27,6 @@ body { box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1); } -/*@media (max-width: 767.98px) {*/ -/* .sidebar {*/ -/* top: 5rem;*/ -/* }*/ -/*}*/ - .sidebar-sticky { position: relative; top: 0; @@ -369,6 +367,7 @@ main{ transform: rotate(360deg); } } + .rotating::before { -webkit-animation: rotating 0.75s linear infinite; -moz-animation: rotating 0.75s linear infinite; @@ -385,7 +384,7 @@ main{ cursor: pointer; } -#peer_private_key_textbox, #private_key, #public_key{ +#peer_private_key_textbox, #private_key, #public_key, #peer_preshared_key_textbox{ font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; } @@ -570,4 +569,32 @@ pre.index-alert{ .peerLightContainer{ text-transform: uppercase; margin: 0; margin-left: auto !important; +} + +.conf_card .dot, .info .dot { + transform: translateX(10px); +} + +#config_body{ + transition: 0.3s ease-in-out; +} + +#config_body.firstLoading{ + opacity: 0.2; +} + +.chartTitle{ + display: flex; +} + +.chartControl{ + margin-bottom: 1rem; + display: flex; + align-items: center; +} + +.chartTitle h6{ + margin-bottom: 0; + line-height: 1; + margin-right: 0.5rem; } \ No newline at end of file diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index 597483fc..be9e748c 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important} \ No newline at end of file +@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 6943337b..62c186ab 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -50,6 +50,29 @@ } } + let firstLoading = true; + $(".nav-conf-link").on("click", function(e){ + if(socket.connected){ + e.preventDefault(); + firstLoading = true; + $("#config_body").addClass("firstLoading"); + + conf_name = $(this).data("conf-id"); + configurations.loadPeers($('#search_peer_textbox').val()); + + $(".nav-conf-link").removeClass("active"); + $(`.sb-${conf_name}-url`).addClass("active"); + + window.history.pushState(null,null,`/configuration/${conf_name}`); + $("title").text(`${conf_name} | WGDashboard`); + + totalDataUsageChartObj.data.labels = []; + totalDataUsageChartObj.data.datasets[0].data = []; + totalDataUsageChartObj.data.datasets[1].data = []; + totalDataUsageChartObj.update(); + } + }); + /** * Parse all responded information onto the configuration header * @param response @@ -61,6 +84,45 @@ }else{ $conf_status_btn.innerHTML = ` OFF`; } + + if (response.running_peer > 0){ + let d = new Date(); + let time = d.toLocaleString("en-us", + {hour: '2-digit', minute: '2-digit', second: "2-digit", hourCycle: 'h23'}); + totalDataUsageChartObj.data.labels.push(`${time}`); + + if (totalDataUsageChartObj.data.datasets[0].data.length === 0){ + totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; + totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; + totalDataUsageChartObj.data.datasets[0].data.push(0); + totalDataUsageChartObj.data.datasets[1].data.push(0); + }else{ + if (totalDataUsageChartObj.data.datasets[0].data.length === 50 && totalDataUsageChartObj.data.datasets[1].data.length === 50){ + totalDataUsageChartObj.data.labels.shift(); + totalDataUsageChartObj.data.datasets[0].data.shift(); + totalDataUsageChartObj.data.datasets[1].data.shift(); + } + + let newTotalReceive = response.total_data_usage[2] - totalDataUsageChartObj.data.datasets[1].lastData; + let newTotalSent = response.total_data_usage[1] - totalDataUsageChartObj.data.datasets[0].lastData; + let k = 0; + if (chartUnit === "MB"){ + k = 1024; + } + else if (chartUnit === "KB"){ + k = 1048576; + }else{ + k = 1; + } + totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k); + totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k); + totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; + totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; + } + + totalDataUsageChartObj.update(); + } + $conf_status_btn.classList.remove("info_loading"); document.querySelectorAll("#sort_by_dropdown option").forEach(ele => ele.removeAttribute("selected")); document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected", "selected"); @@ -164,7 +226,7 @@ let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip,$new_add_MTU, $new_add_keep_alive]; if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")){ if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ - let conf = $add_peer.getAttribute('conf_id'); + let conf = conf_name; let keys = []; for (let i = 0; i < $new_add_amount.val(); i++) { keys.push(window.wireguard.generateKeypair()); @@ -262,12 +324,13 @@ /** * Handle when the server is not responding */ - function noResponding(){ + function noResponding(message = "Opps!
I can't connect to the server."){ document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("active")); setTimeout(function (){ document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("show")); document.querySelector("#right_body").classList.add("no-responding"); document.querySelector(".navbar").classList.add("no-responding"); + document.querySelector(".no-response .container h4").innerHTML = message; },10); } @@ -349,53 +412,38 @@ let time = 0; let count = 0; + let d1 = new Date(); function loadPeers(searchString){ d1 = new Date(); - startProgressBar(); socket.emit('get_config', {"config": conf_name, "search": searchString}); - - // let d1 = new Date(); - // $.ajax({ - // method: "GET", - // url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`, - // headers:{"Content-Type": "application/json"} - // }).done(function(response){ - // removeNoResponding(); - // peers = response.peer_data; - // configurationAlert(response); - // configurationHeader(response); - // configurationPeers(response); - // $(".dot.dot-running").attr("title","Peer Connected").tooltip(); - // $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); - // $("i[data-toggle='tooltip']").tooltip(); - // endProgressBar(); - // let d2 = new Date(); - // let seconds = (d2 - d1); - // $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); - // }).fail(function(){ - // noResponding(); - // }); } function parsePeers(response){ - let d2 = new Date(); - let seconds = (d2 - d1); - time += seconds - count += 1 - window.console.log(`Average time: ${time/count}ms`); - $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); - removeNoResponding(); - peers = response.peer_data; - configurationAlert(response); - configurationHeader(response); - configurationPeers(response); - $(".dot.dot-running").attr("title","Peer Connected").tooltip(); - $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); - $("i[data-toggle='tooltip']").tooltip(); - endProgressBar(); - - + if (response.status){ + let d2 = new Date(); + let seconds = (d2 - d1); + time += seconds; + count += 1; + window.console.log(`Average time: ${time/count}ms`); + $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); + removeNoResponding(); + peers = response.data.peer_data; + configurationAlert(response.data); + configurationHeader(response.data); + configurationPeers(response.data); + $(".dot.dot-running").attr("title","Peer Connected").tooltip(); + $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); + $("i[data-toggle='tooltip']").tooltip(); + $("#conf_name").text(conf_name); + if (firstLoading){ + firstLoading = false; + $("#config_body").removeClass("firstLoading"); + } + }else{ + noResponding(response.message); + removeConfigurationInterval(); + } } /** @@ -513,16 +561,21 @@ */ function getAvailableIps(){ $.ajax({ - "url": `/available_ips/${$add_peer.getAttribute("conf_id")}`, + "url": `/available_ips/${conf_name}`, "method": "GET", }).done(function (res) { - available_ips = res; - let $list_group = document.querySelector("#available_ip_modal .modal-body .list-group"); - $list_group.innerHTML = ""; - document.querySelector("#allowed_ips").value = available_ips[0]; - available_ips.forEach((ip) => - $list_group.innerHTML += - `${ip}`); + if (res.status === true){ + available_ips = res.data; + let $list_group = document.querySelector("#available_ip_modal .modal-body .list-group"); + $list_group.innerHTML = ""; + document.querySelector("#allowed_ips").value = available_ips[0]; + available_ips.forEach((ip) => + $list_group.innerHTML += + `${ip}`); + }else{ + document.querySelector("#allowed_ips").value = res.message; + document.querySelector("#search_available_ip").setAttribute("disabled", "disabled"); + } }); } @@ -533,6 +586,7 @@ ipModal: () => { return ipModal; }, qrcodeModal: () => { return qrcodeModal; }, settingModal: () => { return settingModal; }, + configurationTimeout: () => { return configuration_timeout;}, loadPeers: (searchString) => { loadPeers(searchString); }, addPeersByBulk: () => { addPeersByBulk(); }, @@ -663,7 +717,7 @@ $add_peer.addEventListener("click",function(){ $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 = $add_peer.getAttribute('conf_id'); + let conf = conf_name; 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({ @@ -739,7 +793,7 @@ $("#new_add_amount").on("keyup", function(){ * Handle when user toggled add peers by bulk */ $("#bulk_add").on("change", function (){ - let hide = $(".non-bulk").find("input"); + let hide = $(".non-bulk"); let amount = $("#new_add_amount"); if ($(this).prop("checked") === true){ for(let i = 0; i < hide.length; i++){ @@ -854,7 +908,7 @@ $body.on("click", ".btn-qrcode-peer", function (){ */ $body.on("click", ".btn-delete-peer", function(){ let peer_id = $(this).attr("id"); - $("#delete_peer").attr("peer_id", peer_id); + $("#delete_peer").data("peer-id", peer_id); window.configurations.deleteModal().toggle(); }); @@ -864,9 +918,8 @@ $body.on("click", ".btn-delete-peer", function(){ $("#delete_peer").on("click",function(){ $(this).attr("disabled","disabled"); $(this).html("Deleting..."); - let peer_id = $(this).attr("peer_id"); - let config = $(this).attr("conf_id"); - let peer_ids = [peer_id]; + let config = conf_name; + let peer_ids = [$(this).data("peer-id")]; window.configurations.deletePeers(config, peer_ids); }); @@ -880,12 +933,12 @@ $("#delete_peer").on("click",function(){ * Handle when setting button got clicked for each peer */ $body.on("click", ".btn-setting-peer", function(){ - window.configurations.startProgressBar(); + // window.configurations.startProgressBar(); let peer_id = $(this).attr("id"); $("#save_peer_setting").attr("peer_id", peer_id); $.ajax({ method: "POST", - url: "/get_peer_data/"+$("#setting_modal").attr("conf_id"), + url: "/get_peer_data/"+conf_name, headers:{ "Content-Type": "application/json" }, @@ -921,7 +974,7 @@ $("#peer_private_key_textbox").on("change",function(){ let $save_peer_setting = $("#save_peer_setting"); if ($(this).val().length > 0){ $.ajax({ - "url": "/check_key_match/"+$save_peer_setting.attr("conf_id"), + "url": "/check_key_match/"+conf_name, "method": "POST", "headers":{"Content-Type": "application/json"}, "data": JSON.stringify({ @@ -1233,7 +1286,7 @@ $("#confirm_delete_bulk_peers").on("click", function(){ btn.attr("disabled", "disabled"); let ips = []; $selected_peer_list.childNodes.forEach((ele) => ips.push(ele.dataset.id)); - window.configurations.deletePeers(btn.data("conf"), ips); + window.configurations.deletePeers(conf_name, ips); clearInterval(confirm_delete_bulk_peers_interval); confirm_delete_bulk_peers_interval = undefined; } @@ -1289,7 +1342,7 @@ $body.on("click", ".btn-download-peer", function(e){ */ $("#download_all_peers").on("click", function(){ $.ajax({ - "url": $(this).data("url"), + "url": `/download_all/${conf_name}`, "method": "GET", success: function(res){ if (res.peers.length > 0){ diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index 3cfa7cd0..9b6c59cf 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1,4 +1,4 @@ -(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}let firstLoading=true;$(".nav-conf-link").on("click",function(e){if(socket.connected){e.preventDefault();firstLoading=true;$("#config_body").addClass("firstLoading");conf_name=$(this).data("conf-id");configurations.loadPeers($("#search_peer_textbox").val());$(".nav-conf-link").removeClass("active");$(`.sb-${conf_name}-url`).addClass("active");window.history.pushState(null,null,`/configuration/${conf_name}`);$("title").text(`${conf_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
${peer.name===""?"Untitled":peer.name}
`;let peer_transfer=`
@@ -8,4 +8,4 @@

${roundN(peer.total_sent+total_s,4)} GB

-
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;startProgressBar();socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=$add_peer.getAttribute("conf_id");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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file +
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=conf_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#conf_name").text(conf_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${conf_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=conf_name;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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=conf_name;let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+conf_name,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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+conf_name,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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(conf_name,ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${conf_name}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index aad85b48..af51d74c 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -74,6 +74,24 @@
+
+
+
+
Data Usage / Refresh Interval
+
+
+ + + +
+
+
+
+ +
+
+
+
@@ -154,35 +172,35 @@
-
+
- +
- +
-
+
- +
-
+
- +
-
+
- +
-
@@ -281,7 +299,6 @@

-
@@ -418,17 +435,102 @@ let load_interval = 0; let conf_name = "{{ conf_data['name'] }}" let peers = []; - $(".sb-"+conf_name+"-url").addClass("active"); + $(`.sb-${conf_name}-url`).addClass("active"); let socket = io(); - $(function(){ - socket.on('connect', function() { - configurations.loadPeers($('#search_peer_textbox').val()); - }); - socket.on('get_config', function(res){ - window.console.log(res); - configurations.parsePeers(res); - }); + socket.on('connect', function() { + configurations.loadPeers($('#search_peer_textbox').val()); + }); + socket.on('get_config', function(res){ + window.console.log(res); + configurations.parsePeers(res); + }); - }); + let chartUnit = $(".switchUnit.active").data('unit'); + const totalDataUsageChart = document.getElementById('myChart').getContext('2d'); + const totalDataUsageChartObj = new Chart(totalDataUsageChart, { + type: 'line', + data: { + labels: [], + datasets: [ + { + label: 'Total Sent', + data: [], + fill: false, + borderColor: '#28a745', + tension: 0.1, + borderWidth: 1 + },{ + label: 'Total Received', + data: [], + fill: false, + borderColor: '#007bff', + tension: 0.1, + borderWidth: 1 + }] + }, + options: { + responsive:false, + scales: { + y: { + ticks: { + callback: function(value, index, ticks) { + return `${value} ${chartUnit}` + } + } + } + } + } + }); + $("#myChart").css("width", "100%"); + totalDataUsageChartObj.width = $("#myChart").parent().width(); + totalDataUsageChartObj.resize(); + $(window).on("resize", function() { + totalDataUsageChartObj.width = $("#myChart").parent().width(); + totalDataUsageChartObj.resize(); + }); + + + + let mul = 1; + $(".switchUnit").on("click", function(){ + $(".switchUnit").removeClass("active"); + $(this).addClass("active"); + if ($(this).data('unit') !== chartUnit){ + switch ($(this).data('unit')) { + case "GB": + if (chartUnit === "MB"){ + mul = 1/1024; + } + if (chartUnit === "KB"){ + mul = 1/1048576; + } + break; + case "MB": + if (chartUnit === "GB"){ + mul = 1024 + } + if (chartUnit === "KB"){ + mul = 1/1024 + } + break; + case "KB": + if (chartUnit === "GB"){ + mul = 1048576 + } + if (chartUnit === "MB"){ + mul = 1024 + } + break; + default: + break; + } + chartUnit = $(this).data('unit'); + totalDataUsageChartObj.data.datasets[0].data = totalDataUsageChartObj.data.datasets[0].data.map(x => x * mul); + totalDataUsageChartObj.data.datasets[1].data = totalDataUsageChartObj.data.datasets[1].data.map(x => x * mul); + + totalDataUsageChartObj.update(); + } + + }) \ No newline at end of file diff --git a/src/templates/header.html b/src/templates/header.html index 27f0675c..c58ebdb5 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -15,4 +15,5 @@ + \ No newline at end of file diff --git a/src/templates/sidebar.html b/src/templates/sidebar.html index 1275e1d6..0967abb7 100644 --- a/src/templates/sidebar.html +++ b/src/templates/sidebar.html @@ -19,7 +19,7 @@
From 7e1fd99c3743a83c7ea522b66aa7808cc0d84079 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Fri, 4 Mar 2022 08:28:54 -0500 Subject: [PATCH 004/214] Fixed chart and updated requirement.txt --- src/requirements.txt | 3 +- src/static/css/dashboard.css | 24 +++++++++++++- src/static/css/dashboard.min.css | 2 +- src/templates/configuration.html | 54 +++++++++++++++++++++----------- 4 files changed, 62 insertions(+), 21 deletions(-) diff --git a/src/requirements.txt b/src/requirements.txt index 5d3b3476..eadb354e 100644 --- a/src/requirements.txt +++ b/src/requirements.txt @@ -3,4 +3,5 @@ ifcfg icmplib flask-qrcode gunicorn -certbot \ No newline at end of file +certbot +flask-socketio \ No newline at end of file diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index af9b5a85..d04a9f2d 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -597,4 +597,26 @@ pre.index-alert{ margin-bottom: 0; line-height: 1; margin-right: 0.5rem; -} \ No newline at end of file +} + +.chartContainer.fullScreen{ + position: fixed; + z-index: 9999; + background-color: white; + top: 0; + left: 0; + width: calc( 100% + 15px ); + height: 100%; + padding: 32px; +} + +.chartContainer.fullScreen .col-sm{ + padding-right: 0; + height: 100%; +} + +.chartContainer.fullScreen .chartCanvasContainer{ + width: 100%; + height: calc( 100% - 47px ) !important; + max-height: calc( 100% - 47px ) !important; +} diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index be9e748c..24f41f9d 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem} \ No newline at end of file +@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important} \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index af51d74c..abf720f4 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -74,7 +74,7 @@

-
+
Data Usage / Refresh Interval
@@ -83,10 +83,11 @@ +
-
+
@@ -453,31 +454,46 @@ labels: [], datasets: [ { - label: 'Total Sent', - data: [], - fill: false, - borderColor: '#28a745', - tension: 0.1, - borderWidth: 1 - },{ - label: 'Total Received', - data: [], - fill: false, - borderColor: '#007bff', - tension: 0.1, - borderWidth: 1 - }] + label: 'Data Sent', + data: [], + stroke: '#FFFFFF', + borderColor: '#28a745', + tension: 0.1, + borderWidth: 2 + }, + { + label: 'Data Received', + data: [], + stroke: '#FFFFFF', + borderColor: '#007bff', + tension: 0.1, + borderWidth: 2 + } + ] }, options: { + maintainAspectRatio: false, + showScale: false, responsive:false, scales: { y: { + min: 0, ticks: { + min: 0, callback: function(value, index, ticks) { return `${value} ${chartUnit}` } } } + }, + plugins: { + tooltip: { + callbacks: { + label: function(context) { + return `${context.dataset.label}: ${context.parsed.y} ${chartUnit}` + } + } + } } } }); @@ -485,10 +501,13 @@ totalDataUsageChartObj.width = $("#myChart").parent().width(); totalDataUsageChartObj.resize(); $(window).on("resize", function() { - totalDataUsageChartObj.width = $("#myChart").parent().width(); totalDataUsageChartObj.resize(); }); + $(".fullScreen").on("click", function(){ + $(".chartContainer").addClass("fullScreen"); + totalDataUsageChartObj.resize(); + }); let mul = 1; @@ -527,7 +546,6 @@ chartUnit = $(this).data('unit'); totalDataUsageChartObj.data.datasets[0].data = totalDataUsageChartObj.data.datasets[0].data.map(x => x * mul); totalDataUsageChartObj.data.datasets[1].data = totalDataUsageChartObj.data.datasets[1].data.map(x => x * mul); - totalDataUsageChartObj.update(); } From 4a1a6c59339e37ce5e87ae91b7caa3113ea7d42b Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Fri, 4 Mar 2022 10:06:14 -0500 Subject: [PATCH 005/214] Testing --- src/dashboard.py | 2 +- src/gunicorn.conf.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index 267131bc..a2003614 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -1744,5 +1744,5 @@ if __name__ == "__main__": app_port = config.get("Server", "app_port") WG_CONF_PATH = config.get("Server", "wg_conf_path") config.clear() - socketio.run(app, host=app_ip, debug=False, port=app_port) + socketio.run(app, host=app_ip, debug=False, port=int(app_port)) # app.run(host=app_ip, debug=False, port=app_port) diff --git a/src/gunicorn.conf.py b/src/gunicorn.conf.py index 56b82ce6..0123b4c2 100644 --- a/src/gunicorn.conf.py +++ b/src/gunicorn.conf.py @@ -4,7 +4,8 @@ import dashboard app_host, app_port = dashboard.get_host_bind() worker_class = 'gthread' -workers = multiprocessing.cpu_count() * 2 + 1 +# workers = multiprocessing.cpu_count() * 2 + 1 +workers = 1 threads = 4 bind = f"{app_host}:{app_port}" daemon = True From 65f31a0b385a09d23e8ae250e4fe7e9dfd64c9f7 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Fri, 4 Mar 2022 22:09:01 -0500 Subject: [PATCH 006/214] Gave up using WebSocket Flask-SocketIO does not fully compatible with Gunicorn, and it limited to 1 worker, which it will takes forever to finish loading the webpage. Switched back to using ajax. --- src/dashboard.py | 16 +-- src/gunicorn.conf.py | 3 +- src/static/css/dashboard.css | 4 + src/static/css/dashboard.min.css | 2 +- src/static/js/configuration.js | 221 +++++++++++++++++++++++++---- src/static/js/configuration.min.js | 16 ++- src/templates/configuration.html | 158 ++++----------------- src/templates/header.html | 2 +- 8 files changed, 245 insertions(+), 177 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index a2003614..ad6e1f92 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -1007,9 +1007,9 @@ def configuration(config_name): # Get configuration details -@socketio.on("get_config") -# @app.route('/get_config/', methods=['GET']) -def get_conf(data): +# @socketio.on("get_config") +@app.route('/get_config/', methods=['GET']) +def get_conf(config_name): """ Get configuration setting of wireguard interface. @param config_name: Name of WG interface @@ -1024,17 +1024,15 @@ def get_conf(data): if not session: result["status"] = False result["message"] = "Oops!
You're not signed in. Please refresh your page." - socketio.emit("get_config", result, json=True) - return + return jsonify(result) if getattr(g, 'db', None) is None: g.db = connect_db() g.cur = g.db.cursor() - config_name = data['config'] config_interface = read_conf_file_interface(config_name) if config_interface != {}: - search = data['search'] + search = request.args.get('search') if len(search) == 0: search = "" search = urllib.parse.unquote(search) @@ -1068,7 +1066,8 @@ def get_conf(data): else: result['status'] = False result['message'] = "I cannot find this configuration.
Please refresh and try again" - socketio.emit("get_config", result, json=True) + config.clear() + return jsonify(result) # Turn on / off a configuration @@ -1716,6 +1715,7 @@ def run_dashboard(): global WG_CONF_PATH WG_CONF_PATH = config.get("Server", "wg_conf_path") config.clear() + return app diff --git a/src/gunicorn.conf.py b/src/gunicorn.conf.py index 0123b4c2..56b82ce6 100644 --- a/src/gunicorn.conf.py +++ b/src/gunicorn.conf.py @@ -4,8 +4,7 @@ import dashboard app_host, app_port = dashboard.get_host_bind() worker_class = 'gthread' -# workers = multiprocessing.cpu_count() * 2 + 1 -workers = 1 +workers = multiprocessing.cpu_count() * 2 + 1 threads = 4 bind = f"{app_host}:{app_port}" daemon = True diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index d04a9f2d..71b78315 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -198,6 +198,10 @@ body { color: #dc3545; } +.btn-lock-peer:hover{ + color: #6c757d; +} + .btn-setting-peer:hover{ color:#007bff } diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index 24f41f9d..7a8b84c1 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important} \ No newline at end of file +@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 62c186ab..7c2127c9 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -3,13 +3,14 @@ * Under Apache-2.0 License */ -(function(){ - /* global peers */ - /* global conf_name */ + +(function(){ /** * Definitions */ + let peers = []; + let configuration_name; let configuration_interval; let configuration_timeout = 0; let $progress_bar = $(".progress-bar"); @@ -26,6 +27,123 @@ $("[data-toggle='tooltip']").tooltip(); $("[data-toggle='popover']").popover(); + /** + * Chart!!!!!! + * @type {any} + */ + + let chartUnit = $(".switchUnit.active").data('unit'); + const totalDataUsageChart = document.getElementById('totalDataUsageChartObj').getContext('2d'); + const totalDataUsageChartObj = new Chart(totalDataUsageChart, { + type: 'line', + data: { + labels: [], + datasets: [ + { + label: 'Data Sent', + data: [], + stroke: '#FFFFFF', + borderColor: '#28a745', + tension: 0.1, + borderWidth: 2 + }, + { + label: 'Data Received', + data: [], + stroke: '#FFFFFF', + borderColor: '#007bff', + tension: 0.1, + borderWidth: 2 + } + ] + }, + options: { + maintainAspectRatio: false, + showScale: false, + responsive:false, + scales: { + y: { + min: 0, + ticks: { + min: 0, + callback: function(value, index, ticks) { + return `${value} ${chartUnit}`; + } + } + } + }, + plugins: { + tooltip: { + callbacks: { + label: function(context) { + return `${context.dataset.label}: ${context.parsed.y} ${chartUnit}`; + } + } + } + } + } + }); + + let $totalDataUsageChartObj = $("#totalDataUsageChartObj"); + $totalDataUsageChartObj.css("width", "100%"); + totalDataUsageChartObj.width = $totalDataUsageChartObj.parent().width(); + totalDataUsageChartObj.resize(); + $(window).on("resize", function() { + totalDataUsageChartObj.resize(); + }); + + $(".fullScreen").on("click", function(){ + let $chartContainer = $(".chartContainer"); + if ($chartContainer.hasClass("fullScreen")){ + $(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"); + $chartContainer.removeClass("fullScreen"); + }else{ + $(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit"); + $chartContainer.addClass("fullScreen"); + } + totalDataUsageChartObj.resize(); + }); + + let mul = 1; + $(".switchUnit").on("click", function(){ + $(".switchUnit").removeClass("active"); + $(this).addClass("active"); + if ($(this).data('unit') !== chartUnit){ + switch ($(this).data('unit')) { + case "GB": + if (chartUnit === "MB"){ + mul = 1/1024; + } + if (chartUnit === "KB"){ + mul = 1/1048576; + } + break; + case "MB": + if (chartUnit === "GB"){ + mul = 1024 + } + if (chartUnit === "KB"){ + mul = 1/1024 + } + break; + case "KB": + if (chartUnit === "GB"){ + mul = 1048576 + } + if (chartUnit === "MB"){ + mul = 1024 + } + break; + default: + break; + } + chartUnit = $(this).data('unit'); + totalDataUsageChartObj.data.datasets[0].data = totalDataUsageChartObj.data.datasets[0].data.map(x => x * mul); + totalDataUsageChartObj.data.datasets[1].data = totalDataUsageChartObj.data.datasets[1].data.map(x => x * mul); + totalDataUsageChartObj.update(); + } + }); + /** * To show alert on the configuration page @@ -50,26 +168,28 @@ } } + function setActiveConfigurationName(){ + $(".nav-conf-link").removeClass("active"); + $(`.sb-${configuration_name}-url`).addClass("active"); + } + let firstLoading = true; $(".nav-conf-link").on("click", function(e){ - if(socket.connected){ - e.preventDefault(); + e.preventDefault(); + if (configuration_name !== $(this).data("conf-id")){ firstLoading = true; $("#config_body").addClass("firstLoading"); + configuration_name = $(this).data("conf-id"); + if(loadPeers($('#search_peer_textbox').val())){ + setActiveConfigurationName(); + window.history.pushState(null,null,`/configuration/${configuration_name}`); + $("title").text(`${configuration_name} | WGDashboard`); - conf_name = $(this).data("conf-id"); - configurations.loadPeers($('#search_peer_textbox').val()); - - $(".nav-conf-link").removeClass("active"); - $(`.sb-${conf_name}-url`).addClass("active"); - - window.history.pushState(null,null,`/configuration/${conf_name}`); - $("title").text(`${conf_name} | WGDashboard`); - - totalDataUsageChartObj.data.labels = []; - totalDataUsageChartObj.data.datasets[0].data = []; - totalDataUsageChartObj.data.datasets[1].data = []; - totalDataUsageChartObj.update(); + totalDataUsageChartObj.data.labels = []; + totalDataUsageChartObj.data.datasets[0].data = []; + totalDataUsageChartObj.data.datasets[1].data = []; + totalDataUsageChartObj.update(); + } } }); @@ -123,6 +243,7 @@ totalDataUsageChartObj.update(); } + document.querySelector("#conf_name").textContent = configuration_name; $conf_status_btn.classList.remove("info_loading"); document.querySelectorAll("#sort_by_dropdown option").forEach(ele => ele.removeAttribute("selected")); document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected", "selected"); @@ -175,7 +296,19 @@ let peer_allowed_ip = '
ALLOWED IP
'+peer.allowed_ip+'
'; let peer_latest_handshake = '
LATEST HANDSHAKE
'+peer.latest_handshake+'
'; let peer_endpoint = '
END POINT
'+peer.endpoint+'
'; - let peer_control = '

'; + let peer_control = ` +
+
+
+ + + `; if (peer.private_key !== ""){ peer_control += ''; } @@ -226,7 +359,7 @@ let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip,$new_add_MTU, $new_add_keep_alive]; if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")){ if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ - let conf = conf_name; + let conf = configuration_name; let keys = []; for (let i = 0; i < $new_add_amount.val(); i++) { keys.push(window.wireguard.generateKeypair()); @@ -411,12 +544,22 @@ */ let time = 0; let count = 0; - - let d1 = new Date(); function loadPeers(searchString){ d1 = new Date(); - socket.emit('get_config', {"config": conf_name, "search": searchString}); + let good = true; + $.ajax({ + method: "GET", + url: `/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`, + headers:{"Content-Type": "application/json"} + }).done(function(response){ + console.log(response); + parsePeers(response); + }).fail(function(){ + noResponding(); + good = false + }); + return good; } function parsePeers(response){ @@ -435,7 +578,7 @@ $(".dot.dot-running").attr("title","Peer Connected").tooltip(); $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); $("i[data-toggle='tooltip']").tooltip(); - $("#conf_name").text(conf_name); + $("#configuration_name").text(configuration_name); if (firstLoading){ firstLoading = false; $("#config_body").removeClass("firstLoading"); @@ -561,7 +704,7 @@ */ function getAvailableIps(){ $.ajax({ - "url": `/available_ips/${conf_name}`, + "url": `/available_ips/${configuration_name}`, "method": "GET", }).done(function (res) { if (res.status === true){ @@ -593,6 +736,9 @@ deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); }, parsePeers: (response) => { parsePeers(response); }, + setConfigurationName: (confName) => { configuration_name = confName;}, + getConfigurationName: () => { return configuration_name; }, + setActiveConfigurationName: () => { setActiveConfigurationName(); }, getAvailableIps: () => { getAvailableIps(); }, generateKeyPair: () => { generate_key(); }, showToast: (message) => { showToast(message); }, @@ -717,7 +863,7 @@ $add_peer.addEventListener("click",function(){ $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 = conf_name; + let conf = window.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({ @@ -912,13 +1058,26 @@ $body.on("click", ".btn-delete-peer", function(){ window.configurations.deleteModal().toggle(); }); +$body.on("click", ".btn-lock-peer", function(){ + let $lockGlyph = "bi-lock-fill"; + let $unlockGlyph = "bi-unlock-fill"; + + if ($(this).children().hasClass($lockGlyph)){ + $(this).children().removeClass($lockGlyph).addClass($unlockGlyph); + $(this).children().tooltip('hide').attr('data-original-title', 'Lock Peer').tooltip('show'); + }else{ + $(this).children().removeClass($unlockGlyph).addClass($lockGlyph); + $(this).children().tooltip('hide').attr('data-original-title', 'Unlock Peer').tooltip('show'); + } +}); + /** * When the confirm delete button clicked */ $("#delete_peer").on("click",function(){ $(this).attr("disabled","disabled"); $(this).html("Deleting..."); - let config = conf_name; + let config = window.configurations.getConfigurationName(); let peer_ids = [$(this).data("peer-id")]; window.configurations.deletePeers(config, peer_ids); }); @@ -938,7 +1097,7 @@ $body.on("click", ".btn-setting-peer", function(){ $("#save_peer_setting").attr("peer_id", peer_id); $.ajax({ method: "POST", - url: "/get_peer_data/"+conf_name, + url: "/get_peer_data/"+window.configurations.getConfigurationName(), headers:{ "Content-Type": "application/json" }, @@ -974,7 +1133,7 @@ $("#peer_private_key_textbox").on("change",function(){ let $save_peer_setting = $("#save_peer_setting"); if ($(this).val().length > 0){ $.ajax({ - "url": "/check_key_match/"+conf_name, + "url": "/check_key_match/"+window.configurations.getConfigurationName(), "method": "POST", "headers":{"Content-Type": "application/json"}, "data": JSON.stringify({ @@ -1286,7 +1445,7 @@ $("#confirm_delete_bulk_peers").on("click", function(){ btn.attr("disabled", "disabled"); let ips = []; $selected_peer_list.childNodes.forEach((ele) => ips.push(ele.dataset.id)); - window.configurations.deletePeers(conf_name, ips); + window.configurations.deletePeers(window.configurations.getConfigurationName(), ips); clearInterval(confirm_delete_bulk_peers_interval); confirm_delete_bulk_peers_interval = undefined; } @@ -1342,7 +1501,7 @@ $body.on("click", ".btn-download-peer", function(e){ */ $("#download_all_peers").on("click", function(){ $.ajax({ - "url": `/download_all/${conf_name}`, + "url": `/download_all/${window.configurations.getConfigurationName()}`, "method": "GET", success: function(res){ if (res.peers.length > 0){ diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index 9b6c59cf..af94ae63 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1,4 +1,4 @@ -(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}let firstLoading=true;$(".nav-conf-link").on("click",function(e){if(socket.connected){e.preventDefault();firstLoading=true;$("#config_body").addClass("firstLoading");conf_name=$(this).data("conf-id");configurations.loadPeers($("#search_peer_textbox").val());$(".nav-conf-link").removeClass("active");$(`.sb-${conf_name}-url`).addClass("active");window.history.pushState(null,null,`/configuration/${conf_name}`);$("title").text(`${conf_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+(function(){let peers=[];let configuration_name;let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let chartUnit=$(".switchUnit.active").data("unit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d");const totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:false,showScale:false,responsive:false,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%");totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width();totalDataUsageChartObj.resize();$(window).on("resize",function(){totalDataUsageChartObj.resize()});$(".fullScreen").on("click",function(){let $chartContainer=$(".chartContainer");if($chartContainer.hasClass("fullScreen")){$(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen");$chartContainer.removeClass("fullScreen")}else{$(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit");$chartContainer.addClass("fullScreen")}totalDataUsageChartObj.resize()});let mul=1;$(".switchUnit").on("click",function(){$(".switchUnit").removeClass("active");$(this).addClass("active");if($(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":if(chartUnit==="MB"){mul=1/1024}if(chartUnit==="KB"){mul=1/1048576}break;case"MB":if(chartUnit==="GB"){mul=1024}if(chartUnit==="KB"){mul=1/1024}break;case"KB":if(chartUnit==="GB"){mul=1048576}if(chartUnit==="MB"){mul=1024}break;default:break}chartUnit=$(this).data("unit");totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul);totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul);totalDataUsageChartObj.update()}});function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active");$(`.sb-${configuration_name}-url`).addClass("active")}let firstLoading=true;$(".nav-conf-link").on("click",function(e){e.preventDefault();if(configuration_name!==$(this).data("conf-id")){firstLoading=true;$("#config_body").addClass("firstLoading");configuration_name=$(this).data("conf-id");if(loadPeers($("#search_peer_textbox").val())){setActiveConfigurationName();window.history.pushState(null,null,`/configuration/${configuration_name}`);$("title").text(`${configuration_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name;$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
${peer.name===""?"Untitled":peer.name}
`;let peer_transfer=`
@@ -8,4 +8,16 @@

${roundN(peer.total_sent+total_s,4)} GB

-
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=conf_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;socket.emit("get_config",{config:conf_name,search:searchString})}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#conf_name").text(conf_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${conf_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=conf_name;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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=conf_name;let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+conf_name,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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+conf_name,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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(conf_name,ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${conf_name}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file +
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` +
+
+
+ + + `;if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){let $lockGlyph="bi-lock-fill";let $unlockGlyph="bi-unlock-fill";if($(this).children().hasClass($lockGlyph)){$(this).children().removeClass($lockGlyph).addClass($unlockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")}else{$(this).children().removeClass($unlockGlyph).addClass($lockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index abf720f4..7baa3cdb 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -14,9 +14,7 @@
{% include "sidebar.html" %}
-
- -
+
@@ -88,7 +86,7 @@
- +
@@ -96,14 +94,27 @@
-
- - +
+
+
+ + +
+
+
+
+ + +
+
+ + +
@@ -428,127 +439,10 @@ {% include "tools.html" %} {% include "footer.html" %} - - + \ No newline at end of file diff --git a/src/templates/header.html b/src/templates/header.html index c58ebdb5..12fed9ad 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -14,6 +14,6 @@ - + \ No newline at end of file From 2d3dffe5fc2054cc672c21a94419dc8649b10940 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Mon, 7 Mar 2022 09:29:47 -0500 Subject: [PATCH 007/214] Moved refresh interval and display mode to localStorage --- src/requirements.txt | 3 +- src/static/js/configuration.js | 130 ++++++++++++++++------------- src/static/js/configuration.min.js | 4 +- src/templates/configuration.html | 2 +- 4 files changed, 78 insertions(+), 61 deletions(-) diff --git a/src/requirements.txt b/src/requirements.txt index eadb354e..5d3b3476 100644 --- a/src/requirements.txt +++ b/src/requirements.txt @@ -3,5 +3,4 @@ ifcfg icmplib flask-qrcode gunicorn -certbot -flask-socketio \ No newline at end of file +certbot \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 7c2127c9..021d851b 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -9,10 +9,25 @@ /** * Definitions */ + let peers = []; let configuration_name; let configuration_interval; - let configuration_timeout = 0; + let configuration_timeout = window.localStorage.getItem("configurationTimeout"); + if (configuration_timeout === null || !["5000", "10000", "30000", "60000"].includes(configuration_timeout)){ + window.localStorage.setItem("configurationTimeout", "10000"); + configuration_timeout = window.localStorage.getItem("configurationTimeout"); + } + document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active"); + + let display_mode = window.localStorage.getItem("displayMode"); + if (display_mode === null || !["grid", "list"].includes(display_mode)){ + window.localStorage.setItem("displayMode", "grid"); + display_mode = "grid"; + } + document.querySelectorAll(".display-btn-group button").forEach(ele => ele.classList.remove("active")); + document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active"); + let $progress_bar = $(".progress-bar"); let bootstrapModalConfig = { keyboard: false, @@ -31,8 +46,18 @@ * Chart!!!!!! * @type {any} */ + let chartUnit = window.localStorage.chartUnit; + let chartUnitAvailable = ["GB", "MB", "KB"]; + + if (chartUnit === null || !chartUnitAvailable.includes(chartUnit)){ + window.localStorage.setItem("chartUnit", "GB"); + $('.switchUnit[data-unit="GB"]').addClass("active"); + }else{ + $(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active"); + } + chartUnit = window.localStorage.getItem("chartUnit"); + - let chartUnit = $(".switchUnit.active").data('unit'); const totalDataUsageChart = document.getElementById('totalDataUsageChartObj').getContext('2d'); const totalDataUsageChartObj = new Chart(totalDataUsageChart, { type: 'line', @@ -120,23 +145,24 @@ break; case "MB": if (chartUnit === "GB"){ - mul = 1024 + mul = 1024; } if (chartUnit === "KB"){ - mul = 1/1024 + mul = 1/1024; } break; case "KB": if (chartUnit === "GB"){ - mul = 1048576 + mul = 1048576; } if (chartUnit === "MB"){ - mul = 1024 + mul = 1024; } break; default: break; } + window.localStorage.setItem("chartUnit", $(this).data('unit')); chartUnit = $(this).data('unit'); totalDataUsageChartObj.data.datasets[0].data = totalDataUsageChartObj.data.datasets[0].data.map(x => x * mul); totalDataUsageChartObj.data.datasets[1].data = totalDataUsageChartObj.data.datasets[1].data.map(x => x * mul); @@ -247,10 +273,8 @@ $conf_status_btn.classList.remove("info_loading"); document.querySelectorAll("#sort_by_dropdown option").forEach(ele => ele.removeAttribute("selected")); document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected", "selected"); - document.querySelectorAll(".interval-btn-group button").forEach(ele => ele.classList.remove("active")); - document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active"); - document.querySelectorAll(".display-btn-group button").forEach(ele => ele.classList.remove("active")); - document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active"); + // document.querySelectorAll(".interval-btn-group button").forEach(ele => ele.classList.remove("active")); + // document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active"); document.querySelector("#conf_status").innerHTML = `${response.status}`; document.querySelector("#conf_connected_peers").innerHTML = response.running_peer; document.querySelector("#conf_total_data_usage").innerHTML = `${response.total_data_usage[0]} GB`; @@ -271,7 +295,7 @@ if (response.peer_data.length === 0){ document.querySelector(".peer_list").innerHTML = `

Oops! No peers found ‘︿’

`; }else{ - let display_mode = response.peer_display_mode === "list" ? "col-12" : "col-sm-6 col-lg-4"; + let mode = display_mode === "list" ? "col-12" : "col-sm-6 col-lg-4"; response.peer_data.forEach(function(peer){ let total_r = 0; let total_s = 0; @@ -313,7 +337,7 @@ peer_control += ''; } peer_control += '
'; - let html = '
' + + let html = '
' + '
' + '
' + '
' + @@ -334,9 +358,7 @@ result += html; }); document.querySelector(".peer_list").innerHTML = result; - if (response.dashboard_refresh_interval !== configuration_timeout){ - configuration_timeout = response.dashboard_refresh_interval; - removeConfigurationInterval(); + if (configuration_interval === undefined){ setConfigurationInterval(); } } @@ -557,7 +579,7 @@ parsePeers(response); }).fail(function(){ noResponding(); - good = false + good = false; }); return good; } @@ -575,6 +597,7 @@ configurationAlert(response.data); configurationHeader(response.data); configurationPeers(response.data); + $(".dot.dot-running").attr("title","Peer Connected").tooltip(); $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); $("i[data-toggle='tooltip']").tooltip(); @@ -615,17 +638,12 @@ * @param res * @param interval */ - function updateRefreshInterval(res, interval) { - if (res === "true"){ - configuration_timeout = interval; - removeConfigurationInterval(); - setConfigurationInterval(); - showToast("Refresh Interval set to "+Math.round(interval/1000)+" seconds"); - }else{ - $(".interval-btn-group button").removeClass("active"); - $('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active"); - showToast("Refresh Interval set unsuccessful"); - } + function updateRefreshInterval(interval) { + configuration_timeout = interval; + window.localStorage.setItem("configurationTimeout", configuration_timeout.toString()); + removeConfigurationInterval(); + setConfigurationInterval(); + showToast("Refresh Interval set to "+Math.round(interval/1000)+" seconds"); } /** @@ -730,6 +748,7 @@ qrcodeModal: () => { return qrcodeModal; }, settingModal: () => { return settingModal; }, configurationTimeout: () => { return configuration_timeout;}, + updateDisplayMode: () => { display_mode = window.localStorage.getItem("displayMode")}, loadPeers: (searchString) => { loadPeers(searchString); }, addPeersByBulk: () => { addPeersByBulk(); }, @@ -742,7 +761,7 @@ getAvailableIps: () => { getAvailableIps(); }, generateKeyPair: () => { generate_key(); }, showToast: (message) => { showToast(message); }, - updateRefreshInterval: (res, interval) => { updateRefreshInterval(res, interval); }, + updateRefreshInterval: (interval) => { updateRefreshInterval(interval); }, copyToClipboard: (element) => { copyToClipboard(element); }, toggleDeleteByBulkIP: (element) => { toggleBulkIP(element); }, downloadOneConfig: (conf) => { download_one_config(conf); }, @@ -1284,14 +1303,20 @@ $body.on("click", ".update_interval", function(){ let _new = $(this); _new.addClass("active"); let interval = $(this).data("refresh-interval"); - $.ajax({ - method:"POST", - data: "interval="+$(this).data("refresh-interval"), - url: "/update_dashboard_refresh_interval", - success: function (res){ - window.configurations.updateRefreshInterval(res, interval); - } - }); + if ([5000, 10000, 30000, 60000].includes(interval)){ + window.configurations.updateRefreshInterval(interval); + } + + + + // $.ajax({ + // method:"POST", + // data: "interval="+$(this).data("refresh-interval"), + // url: "/update_dashboard_refresh_interval", + // success: function (res){ + // window.configurations.updateRefreshInterval(res, interval); + // } + // }); }); /** @@ -1307,26 +1332,19 @@ $body.on("click", ".refresh", function (){ $body.on("click", ".display_mode", function(){ $(".display-btn-group button").removeClass("active"); $(this).addClass("active"); - let display_mode = $(this).data("display-mode"); - $.ajax({ - method:"GET", - url: "/switch_display_mode/"+$(this).data("display-mode"), - success: function (res){ - if (res === "true"){ - if (display_mode === "list"){ - Array($(".peer_list").children()).forEach(function(child){ - $(child).removeClass().addClass("col-12"); - }); - window.configurations.showToast("Displaying as List"); - }else{ - Array($(".peer_list").children()).forEach(function(child){ - $(child).removeClass().addClass("col-sm-6 col-lg-4"); - }); - window.configurations.showToast("Displaying as Grids"); - } - } - } - }); + window.localStorage.setItem("displayMode", $(this).data("display-mode")); + window.configurations.updateDisplayMode(); + if ($(this).data("display-mode") === "list"){ + Array($(".peer_list").children()).forEach(function(child){ + $(child).removeClass().addClass("col-12"); + }); + window.configurations.showToast("Displaying as List"); + }else{ + Array($(".peer_list").children()).forEach(function(child){ + $(child).removeClass().addClass("col-sm-6 col-lg-4"); + }); + window.configurations.showToast("Displaying as Grids"); + } }); diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index af94ae63..02e8a5e8 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1,4 +1,4 @@ -(function(){let peers=[];let configuration_name;let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let chartUnit=$(".switchUnit.active").data("unit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d");const totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:false,showScale:false,responsive:false,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%");totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width();totalDataUsageChartObj.resize();$(window).on("resize",function(){totalDataUsageChartObj.resize()});$(".fullScreen").on("click",function(){let $chartContainer=$(".chartContainer");if($chartContainer.hasClass("fullScreen")){$(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen");$chartContainer.removeClass("fullScreen")}else{$(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit");$chartContainer.addClass("fullScreen")}totalDataUsageChartObj.resize()});let mul=1;$(".switchUnit").on("click",function(){$(".switchUnit").removeClass("active");$(this).addClass("active");if($(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":if(chartUnit==="MB"){mul=1/1024}if(chartUnit==="KB"){mul=1/1048576}break;case"MB":if(chartUnit==="GB"){mul=1024}if(chartUnit==="KB"){mul=1/1024}break;case"KB":if(chartUnit==="GB"){mul=1048576}if(chartUnit==="MB"){mul=1024}break;default:break}chartUnit=$(this).data("unit");totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul);totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul);totalDataUsageChartObj.update()}});function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active");$(`.sb-${configuration_name}-url`).addClass("active")}let firstLoading=true;$(".nav-conf-link").on("click",function(e){e.preventDefault();if(configuration_name!==$(this).data("conf-id")){firstLoading=true;$("#config_body").addClass("firstLoading");configuration_name=$(this).data("conf-id");if(loadPeers($("#search_peer_textbox").val())){setActiveConfigurationName();window.history.pushState(null,null,`/configuration/${configuration_name}`);$("title").text(`${configuration_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name;$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+(function(){let peers=[];let configuration_name;let configuration_interval;let configuration_timeout=window.localStorage.getItem("configurationTimeout");if(configuration_timeout===null||!["5000","10000","30000","60000"].includes(configuration_timeout)){window.localStorage.setItem("configurationTimeout","10000");configuration_timeout=window.localStorage.getItem("configurationTimeout")}document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active");let display_mode=window.localStorage.getItem("displayMode");if(display_mode===null||!["grid","list"].includes(display_mode)){window.localStorage.setItem("displayMode","grid");display_mode="grid"}document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active");let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let chartUnit=window.localStorage.chartUnit;let chartUnitAvailable=["GB","MB","KB"];if(chartUnit===null||!chartUnitAvailable.includes(chartUnit)){window.localStorage.setItem("chartUnit","GB");$('.switchUnit[data-unit="GB"]').addClass("active")}else{$(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active")}chartUnit=window.localStorage.getItem("chartUnit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d");const totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:false,showScale:false,responsive:false,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%");totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width();totalDataUsageChartObj.resize();$(window).on("resize",function(){totalDataUsageChartObj.resize()});$(".fullScreen").on("click",function(){let $chartContainer=$(".chartContainer");if($chartContainer.hasClass("fullScreen")){$(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen");$chartContainer.removeClass("fullScreen")}else{$(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit");$chartContainer.addClass("fullScreen")}totalDataUsageChartObj.resize()});let mul=1;$(".switchUnit").on("click",function(){$(".switchUnit").removeClass("active");$(this).addClass("active");if($(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":if(chartUnit==="MB"){mul=1/1024}if(chartUnit==="KB"){mul=1/1048576}break;case"MB":if(chartUnit==="GB"){mul=1024}if(chartUnit==="KB"){mul=1/1024}break;case"KB":if(chartUnit==="GB"){mul=1048576}if(chartUnit==="MB"){mul=1024}break;default:break}window.localStorage.setItem("chartUnit",$(this).data("unit"));chartUnit=$(this).data("unit");totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul);totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul);totalDataUsageChartObj.update()}});function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active");$(`.sb-${configuration_name}-url`).addClass("active")}let firstLoading=true;$(".nav-conf-link").on("click",function(e){e.preventDefault();if(configuration_name!==$(this).data("conf-id")){firstLoading=true;$("#config_body").addClass("firstLoading");configuration_name=$(this).data("conf-id");if(loadPeers($("#search_peer_textbox").val())){setActiveConfigurationName();window.history.pushState(null,null,`/configuration/${configuration_name}`);$("title").text(`${configuration_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name;$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let mode=display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
${peer.name===""?"Untitled":peer.name}
`;let peer_transfer=`
@@ -20,4 +20,4 @@ `;if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){let $lockGlyph="bi-lock-fill";let $unlockGlyph="bi-unlock-fill";if($(this).children().hasClass($lockGlyph)){$(this).children().removeClass($lockGlyph).addClass($unlockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")}else{$(this).children().removeClass($unlockGlyph).addClass($lockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file + `;if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(configuration_interval===undefined){setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(interval){configuration_timeout=interval;window.localStorage.setItem("configurationTimeout",configuration_timeout.toString());removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){let $lockGlyph="bi-lock-fill";let $unlockGlyph="bi-unlock-fill";if($(this).children().hasClass($lockGlyph)){$(this).children().removeClass($lockGlyph).addClass($unlockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")}else{$(this).children().removeClass($unlockGlyph).addClass($lockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$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([5e3,1e4,3e4,6e4].includes(interval)){window.configurations.updateRefreshInterval(interval)}});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");window.localStorage.setItem("displayMode",$(this).data("display-mode"));window.configurations.updateDisplayMode();if($(this).data("display-mode")==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index 7baa3cdb..2f659a47 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -78,7 +78,7 @@
Data Usage / Refresh Interval
- + From bdd984a8873657a587846bbc5040395534d94aa5 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Mon, 21 Mar 2022 22:33:19 -0400 Subject: [PATCH 008/214] Brand new switch button and toast UI --- README.md | 3 +- src/api.py | 2 + src/dashboard.py | 99 +++- src/static/css/dashboard.css | 389 +++++++++----- src/static/css/dashboard.min.css | 2 +- src/static/js/configuration.js | 804 ++++++++++++++++------------- src/static/js/configuration.min.js | 24 +- src/templates/configuration.html | 14 +- src/templates/index.html | 85 ++- src/util.py | 33 +- 10 files changed, 912 insertions(+), 543 deletions(-) create mode 100644 src/api.py diff --git a/README.md b/README.md index b83bfac2..44ca4dd1 100644 --- a/README.md +++ b/README.md @@ -536,5 +536,4 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! - +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! \ No newline at end of file diff --git a/src/api.py b/src/api.py new file mode 100644 index 00000000..22696d77 --- /dev/null +++ b/src/api.py @@ -0,0 +1,2 @@ +from dashboard import request, jsonify, app + diff --git a/src/dashboard.py b/src/dashboard.py index ad6e1f92..7380c35d 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -28,8 +28,7 @@ from icmplib import ping, traceroute from flask_socketio import SocketIO # Import other python files -from util import regex_match, check_DNS, check_Allowed_IPs, check_remote_endpoint, \ - check_IP_with_range, clean_IP_with_range +from util import * # Dashboard Version DASHBOARD_VERSION = 'v3.0.5' @@ -375,6 +374,12 @@ def get_all_peers_data(config_name): get_endpoint(config_name) get_allowed_ip(conf_peer_data, config_name) +def getLockAccessPeers(config_name): + col = g.cur.execute(f"PRAGMA table_info({config_name}_restrict_access)").fetchall() + col = [a[1] for a in col] + data = g.cur.execute(f"SELECT * FROM {config_name}_restrict_access").fetchall() + result = [{col[i]: data[k][i] for i in range(len(col))} for k in range(len(data))] + return result def get_peers(config_name, search, sort_t): """ @@ -499,7 +504,19 @@ def get_conf_list(): total_sent FLOAT NULL, total_data FLOAT NULL, endpoint VARCHAR NULL, status VARCHAR NULL, latest_handshake VARCHAR NULL, allowed_ip VARCHAR NULL, cumu_receive FLOAT NULL, cumu_sent FLOAT NULL, cumu_data FLOAT NULL, mtu INT NULL, - keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, + keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, + PRIMARY KEY (id) + ) + """ + g.cur.execute(create_table) + create_table = f""" + CREATE TABLE IF NOT EXISTS {i}_restrict_access ( + id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, + endpoint_allowed_ip VARCHAR NULL, name VARCHAR NULL, total_receive FLOAT NULL, + total_sent FLOAT NULL, total_data FLOAT NULL, endpoint VARCHAR NULL, + status VARCHAR NULL, latest_handshake VARCHAR NULL, allowed_ip VARCHAR NULL, + cumu_receive FLOAT NULL, cumu_sent FLOAT NULL, cumu_data FLOAT NULL, mtu INT NULL, + keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, PRIMARY KEY (id) ) """ @@ -620,7 +637,6 @@ def f_available_ips(config_name): Flask Functions """ - @app.teardown_request def close_DB(exception): """ @@ -1056,7 +1072,8 @@ def get_conf(config_name): "wg_ip": wg_ip, "sort_tag": sort, "dashboard_refresh_interval": int(config.get("Server", "dashboard_refresh_interval")), - "peer_display_mode": peer_display_mode + "peer_display_mode": peer_display_mode, + "lock_access_peers": getLockAccessPeers(config_name) } if result['data']['status'] == "stopped": result['data']['checked'] = "nope" @@ -1087,16 +1104,15 @@ def switch(config_name): shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: session["switch_msg"] = exc.output.strip().decode("utf-8") - return redirect('/') + return jsonify({"status": False, "reason":"Can't stop peer"}) elif status == "stopped": try: subprocess.check_output("wg-quick up " + config_name, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: session["switch_msg"] = exc.output.strip().decode("utf-8") - return redirect('/') - return redirect(request.referrer) - + return jsonify({"status": False, "reason":"Can't turn on peer"}) + return jsonify({"status": True, "reason":""}) @app.route('/add_peer_bulk/', methods=['POST']) def add_peer_bulk(config_name): @@ -1240,24 +1256,7 @@ def remove_peer(config_name): if not isinstance(keys, list): return config_name + " is not running." else: - sql_command = [] - wg_command = ["wg", "set", config_name] - for delete_key in delete_keys: - if delete_key not in keys: - return "This key does not exist" - sql_command.append("DELETE FROM " + config_name + " WHERE id = '" + delete_key + "';") - wg_command.append("peer") - wg_command.append(delete_key) - wg_command.append("remove") - try: - remove_wg = subprocess.check_output(" ".join(wg_command), - shell=True, stderr=subprocess.STDOUT) - save_wg = subprocess.check_output(f"wg-quick save {config_name}", shell=True, stderr=subprocess.STDOUT) - g.cur.executescript(' '.join(sql_command)) - g.db.commit() - except subprocess.CalledProcessError as exc: - return exc.output.strip() - return "true" + return deletePeers(config_name, delete_keys, g.cur, g.db) @app.route('/save_peer_setting/', methods=['POST']) @@ -1530,6 +1529,51 @@ def switch_display_mode(mode): return "false" +# APIs +@app.route('/api/togglePeerAccess', methods=['POST']) +def togglePeerAccess(): + data = request.get_json() + print(data['peerID']) + returnData = {"status": True, "reason": ""} + required = ['peerID', 'config'] + if checkJSONAllParameter(required, data): + checkUnlock = g.cur.execute(f"SELECT * FROM {data['config']} WHERE id='{data['peerID']}'").fetchone() + if checkUnlock: + moveUnlockToLock = g.cur.execute(f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + print(g.cur.rowcount) + print(deletePeers(data['config'], [data['peerID']], g.cur, g.db)) + else: + moveLockToUnlock = g.cur.execute(f"SELECT * FROM {data['config']}_restrict_access WHERE id='{data['peerID']}'").fetchone() + try: + if len(moveLockToUnlock[-1]) == 0: + status = subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", + shell=True, stderr=subprocess.STDOUT) + else: + now = str(datetime.now().strftime("%m%d%Y%H%M%S")) + f_name = now + "_tmp_psk.txt" + f = open(f_name, "w+") + f.write(moveLockToUnlock[-1]) + f.close() + subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", + shell=True, stderr=subprocess.STDOUT) + os.remove(f_name) + status = subprocess.check_output(f"wg-quick save {data['config']}", shell=True, stderr=subprocess.STDOUT) + g.cur.execute(f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + g.cur.execute(f"DELETE FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + + except subprocess.CalledProcessError as exc: + returnData["status"] = False + returnData["reason"] = exc.output.strip() + else: + returnData["status"] = False + returnData["reason"] = "Please provide all required parameters." + + return jsonify(returnData) + + + """ Dashboard Tools Related """ @@ -1624,6 +1668,7 @@ def init_dashboard(): """ Create dashboard default configuration. """ + # Set Default INI File if not os.path.isfile(DASHBOARD_CONF): diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 71b78315..0c425e0f 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -9,7 +9,7 @@ body { vertical-align: text-bottom; } -.btn-primary{ +.btn-primary { font-weight: bold; } @@ -22,8 +22,10 @@ body { top: 0; bottom: 0; left: 0; - z-index: 100; /* Behind the navbar */ - padding: 48px 0 0; /* Height of navbar */ + z-index: 100; + /* Behind the navbar */ + padding: 48px 0 0; + /* Height of navbar */ box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1); } @@ -33,7 +35,8 @@ body { height: calc(100vh - 48px); padding-top: .5rem; overflow-x: hidden; - overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */ + overflow-y: auto; + /* Scrollable contents if viewport is shorter than content. */ } @supports ((position: -webkit-sticky) or (position: sticky)) { @@ -73,6 +76,7 @@ body { text-transform: uppercase; } + /* * Navbar */ @@ -90,11 +94,11 @@ body { right: 1rem; } -.form-control{ +.form-control { transition: all 0.2s ease-in-out; } -.form-control:disabled{ +.form-control:disabled { cursor: not-allowed; } @@ -115,7 +119,7 @@ body { box-shadow: 0 0 0 3px rgba(255, 255, 255, .25); } -.dot{ +.dot { width: 10px; height: 10px; border-radius: 50px; @@ -123,157 +127,171 @@ body { margin-left: auto !important; } -.dot-running{ +.dot-running { background-color: #28a745!important; box-shadow: 0 0 0 0.2rem #28a74545; } -.h6-dot-running{ +.h6-dot-running { margin-left: 0.3rem; } -.dot-stopped{ +.dot-stopped { background-color: #6c757d!important; } -.card-running{ +.card-running { border-color: #28a745; } -.info h6{ +.info h6 { line-break: anywhere; - transition: 0.2s ease-in-out; + transition: all 0.4s cubic-bezier(0.96, -0.07, 0.34, 1.01); + opacity: 1; } -.info .row .col-sm{ +.info .row .col-sm { display: flex; flex-direction: column; } -.info .row .col-sm small{ +.info .row .col-sm small { display: flex; - } -.info .row .col-sm small strong:last-child(1){ +.info .row .col-sm small strong:last-child(1) { margin-left: auto !important; } -.btn-control{ +.btn-control { border: none !important; padding: 0 1rem 0 0; } -.btn-control:active, .btn-control:focus{ +.btn-control:active, +.btn-control:focus { background-color: transparent !important; border: none !important; box-shadow: none; } -.btn-qrcode-peer{ +.btn-qrcode-peer { padding: 0 !important; } -.btn-qrcode-peer:active, .btn-qrcode-peer:hover{ +.btn-qrcode-peer:active, +.btn-qrcode-peer:hover { transform: scale(0.9) rotate(180deg); border: 0 !important; } -.btn-download-peer:active, .btn-download-peer:hover{ +.btn-download-peer:active, +.btn-download-peer:hover { color: #17a2b8 !important; transform: translateY(5px); } -.share_peer_btn_group .btn-control{ +.share_peer_btn_group .btn-control { margin: 0 0 0 1rem; padding: 0 !important; transition: all 0.4s cubic-bezier(1, -0.43, 0, 1.37); } -.btn-control:hover{ +.btn-control:hover { background: white; } -.btn-delete-peer:hover{ +.btn-delete-peer:hover { color: #dc3545; } -.btn-lock-peer:hover{ - color: #6c757d; +.btn-lock-peer:hover { + color: #28a745; } -.btn-setting-peer:hover{ - color:#007bff +.btn-lock-peer.lock{ + color: #6c757d } -.btn-download-peer:hover{ +.btn-lock-peer.lock:hover{ + color: #6c757d +} + +.btn-setting-peer:hover { + color: #007bff +} + +.btn-download-peer:hover { color: #17a2b8; } -.login-container{ +.login-container { padding: 2rem; } -@media (max-width: 992px){ - .card-col{ +@media (max-width: 992px) { + .card-col { margin-bottom: 1rem; } } -.switch{ +.switch { font-size: 2rem; } -.switch:hover{ + +.switch:hover { text-decoration: none } -.btn-group-label:hover{ +.btn-group-label:hover { color: #007bff; border-color: #007bff; background: white; } -.peer_data_group{ +.peer_data_group { text-align: right; display: flex; margin-bottom: 0.5rem } -.peer_data_group p{ +.peer_data_group p { text-transform: uppercase; margin-bottom: 0; margin-right: 1rem } @media (max-width: 768px) { - .peer_data_group{ + .peer_data_group { text-align: left; } } -.index-switch{ +.index-switch { text-align: right; + display: flex; + align-items: center; + justify-content: flex-end; } -main{ +main { margin-bottom: 3rem; } -.peer_list{ +.peer_list { margin-bottom: 7rem } @media (max-width: 768px) { - .add_btn{ + .add_btn { bottom: 1.5rem !important; } - - .peer_list{ + .peer_list { margin-bottom: 7rem !important; } } -.btn-manage-group{ +.btn-manage-group { z-index: 99; position: fixed; bottom: 3rem; @@ -281,7 +299,7 @@ main{ display: flex; } -.btn-manage-group .setting_btn_menu{ +.btn-manage-group .setting_btn_menu { position: absolute; top: -124px; background-color: white; @@ -296,16 +314,16 @@ main{ transition: all 0.3s cubic-bezier(0.58, 0.03, 0.05, 1.28); } -.btn-manage-group .setting_btn_menu.show{ +.btn-manage-group .setting_btn_menu.show { display: block; } -.setting_btn_menu.showing{ +.setting_btn_menu.showing { transform: translateY(0px); opacity: 1; } -.setting_btn_menu a{ +.setting_btn_menu a { display: flex; padding: 0.5rem 1rem; transition: all 0.1s ease-in-out; @@ -314,36 +332,38 @@ main{ cursor: pointer; } -.setting_btn_menu a:hover{ +.setting_btn_menu a:hover { background-color: #efefef; text-decoration: none; } -.setting_btn_menu a i{ +.setting_btn_menu a i { margin-right: auto !important; } -.add_btn{ +.add_btn { height: 54px; z-index: 99; border-radius: 100px !important; padding: 0 14px; - box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); margin-right: 1rem; font-size: 1.5rem; } -.setting_btn{ +.setting_btn { height: 54px; z-index: 99; border-radius: 100px !important; padding: 0 14px; - box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); font-size: 1.5rem; } +@-webkit-keyframes rotating +/* Safari and Chrome */ -@-webkit-keyframes rotating /* Safari and Chrome */ { +{ from { -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); @@ -355,6 +375,7 @@ main{ transform: rotate(360deg); } } + @keyframes rotating { from { -ms-transform: rotate(0deg); @@ -380,7 +401,7 @@ main{ animation: rotating 0.75s linear infinite; } -.peer_private_key_textbox_switch{ +.peer_private_key_textbox_switch { position: absolute; right: 2rem; transform: translateY(-28px); @@ -388,139 +409,153 @@ main{ cursor: pointer; } -#peer_private_key_textbox, #private_key, #public_key, #peer_preshared_key_textbox{ - font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; +#peer_private_key_textbox, +#private_key, +#public_key, +#peer_preshared_key_textbox { + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } -.progress-bar{ +.progress-bar { transition: 0.3s ease-in-out; } -.key{ +.key { transition: 0.2s ease-in-out; cursor: pointer; } -.key:hover{ +.key:hover { color: #007bff; } -.card{ +.card { border-radius: 10px; } -.peer_list .card .button-group{ +.peer_list .card .button-group { height: 22px; } -.form-control{ +.form-control { border-radius: 10px; } -.btn{ +.btn { border-radius: 8px; /*padding: 0.6rem 0.9em;*/ } -#username, #password{ - padding: 0.6rem calc( 0.9rem + 32px ); +#username, +#password { + padding: 0.6rem calc( 0.9rem + 32px); height: inherit; } -label[for="username"], label[for="password"]{ +label[for="username"], +label[for="password"] { font-size: 1rem; margin: 0 !important; transform: translateY(30px) translateX(16px); padding: 0; } + /*label[for="password"]{*/ + + /* transform: translateY(32px) translateX(16px);*/ + + /*}*/ - -.modal-content{ +.modal-content { border-radius: 10px; } -.tooltip-inner{ +.tooltip-inner { font-size: 0.8rem; } @-webkit-keyframes loading { - 0%{ + 0% { background-color: #dfdfdf; } - 50%{ + 50% { background-color: #adadad; } - 100%{ - background-color: #dfdfdf; - } -} -@-moz-keyframes loading { - 0%{ - background-color: #dfdfdf; - } - 50%{ - background-color: #adadad; - } - 100%{ + 100% { background-color: #dfdfdf; } } -.conf_card{ +@-moz-keyframes loading { + 0% { + background-color: #dfdfdf; + } + 50% { + background-color: #adadad; + } + 100% { + background-color: #dfdfdf; + } +} + +.conf_card { transition: 0.2s ease-in-out; } -.conf_card:hover{ +.conf_card:hover { border-color: #007bff; cursor: pointer; } -.info_loading{ - animation: loading 2s infinite ease-in-out; - border-radius: 5px; - height: 19px; - transition: 0.3s ease-in-out; +.info_loading { + /* animation: loading 2s infinite ease-in-out; + /* border-radius: 5px; */ + height: 19.19px; + /* transition: 0.3s ease-in-out; */ + + /* transform: translateX(40px); */ + opacity: 0 !important; } -#conf_status_btn{ +#conf_status_btn { transition: 0.2s ease-in-out; } -#conf_status_btn.info_loading{ +#conf_status_btn.info_loading { height: 38px; border-radius: 5px; animation: loading 3s infinite ease-in-out; } -#qrcode_img img{ +#qrcode_img img { width: 100%; } -#selected_ip_list .badge, #selected_peer_list .badge{ +#selected_ip_list .badge, +#selected_peer_list .badge { margin: 0.1rem } -#add_modal.ip_modal_open{ +#add_modal.ip_modal_open { transition: filter 0.2s ease-in-out; filter: brightness(0.5); } -#delete_bulk_modal .list-group a.active{ +#delete_bulk_modal .list-group a.active { background-color: #dc3545; border-color: #dc3545; } -#selected_peer_list{ +#selected_peer_list { max-height: 80px; overflow-y: scroll; overflow-x: hidden; } -.no-response{ +.no-response { width: 100%; height: 100%; position: fixed; @@ -534,93 +569,195 @@ label[for="username"], label[for="password"]{ transition: all 1s ease-in-out; } -.no-response.active{ +.no-response.active { display: flex; } -.no-response.active.show{ +.no-response.active.show { opacity: 100; } -.no-response .container > *{ +.no-response .container>* { text-align: center; } -.no-responding{ +.no-responding { transition: all 1s ease-in-out; filter: blur(10px); } -pre.index-alert{ +pre.index-alert { margin-bottom: 0; padding: 1rem; background-color: #343a40; - border: 1px solid rgba(0,0,0,.125); + border: 1px solid rgba(0, 0, 0, .125); border-radius: .25rem; margin-top: 1rem; color: white; } -.peerNameCol{ +.peerNameCol { display: flex; align-items: center; margin-bottom: 0.2rem } -.peerName{ - margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +.peerName { + margin: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } -.peerLightContainer{ - text-transform: uppercase; margin: 0; margin-left: auto !important; +.peerLightContainer { + text-transform: uppercase; + margin: 0; + margin-left: auto !important; } -.conf_card .dot, .info .dot { +.conf_card .dot, +.info .dot { transform: translateX(10px); } -#config_body{ +#config_body { transition: 0.3s ease-in-out; } -#config_body.firstLoading{ +#config_body.firstLoading { opacity: 0.2; } -.chartTitle{ +.chartTitle { display: flex; } -.chartControl{ - margin-bottom: 1rem; +.chartControl { + margin-bottom: 1rem; display: flex; align-items: center; } -.chartTitle h6{ +.chartTitle h6 { margin-bottom: 0; line-height: 1; margin-right: 0.5rem; } -.chartContainer.fullScreen{ +.chartContainer.fullScreen { position: fixed; z-index: 9999; background-color: white; top: 0; left: 0; - width: calc( 100% + 15px ); + width: calc( 100% + 15px); height: 100%; padding: 32px; } -.chartContainer.fullScreen .col-sm{ +.chartContainer.fullScreen .col-sm { padding-right: 0; height: 100%; } -.chartContainer.fullScreen .chartCanvasContainer{ +.chartContainer.fullScreen .chartCanvasContainer { width: 100%; - height: calc( 100% - 47px ) !important; - max-height: calc( 100% - 47px ) !important; + height: calc( 100% - 47px) !important; + max-height: calc( 100% - 47px) !important; } + +#switch{ + transition: all 350ms ease-in; +} + +.toggle--switch{ + display: none; +} + +.toggleLabel{ + width: 64px; + height: 32px; + background-color: #6c757d17; + display: flex; + position: relative; + border: 2px solid #6c757d8c; + border-radius: 100px; + transition: all 350ms ease-in; + cursor: pointer; + margin: 0; +} + +.toggle--switch.waiting + .toggleLabel{ + opacity: 0.5; +} + +.toggleLabel::before{ + background-color: #6c757d; + height: 26px; + width: 26px; + content: ""; + border-radius: 100px; + margin: 1px; + position: absolute; + animation-name: off; + animation-duration: 350ms; + animation-fill-mode: forwards; + transition: all 350ms ease-in; + cursor: pointer; +} + +.toggle--switch:checked + .toggleLabel{ + background-color: #007bff17 !important; + border: 2px solid #007bff8c; +} + +.toggle--switch:checked + .toggleLabel::before{ + background-color: #007bff; + animation-name: on; + animation-duration: 350ms; + animation-fill-mode: forwards; +} + +@keyframes on { + 0%{ + left: 0px; + } + 60%{ + left: 0px; + width: 40px; + } + 100%{ + left: 32px; + width: 26px; + } +} + +@keyframes off { + 0%{ + left: 32px; + } + 60%{ + left: 18px; + width: 40px; + } + 100%{ + left: 0px; + width: 26px; + } +} + +.toast{ + min-width: 300px; + background-color: rgba(255,255,255,1); +} + +.toast-header{ + background-color: rgba(255,255,255); +} + +.toast-progressbar{ + width: 100%; + height: 4px; + background-color: #007bff; + border-bottom-left-radius: .25rem; +} \ No newline at end of file diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index 7a8b84c1..6459c8b9 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important} \ No newline at end of file +body{font-size:.875rem}.feather{height:16px;vertical-align:text-bottom;width:16px}.btn-primary{font-weight:700}.sidebar{bottom:0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1);left:0;padding:48px 0 0;position:fixed;top:0;z-index:100}.sidebar-sticky{height:calc(100vh - 48px);overflow-x:hidden;overflow-y:auto;padding-top:.5rem;position:relative;top:0}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{color:#333;font-weight:500;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{background-color:#dfdfdf;padding-left:30px}.sidebar .nav-link .feather{color:#999;margin-right:4px}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25);font-size:1rem;padding-bottom:.75rem;padding-top:.75rem}.navbar .navbar-toggler{right:1rem;top:.25rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{border-radius:0;border-width:0;padding:.75rem 1rem}.form-control-dark{background-color:hsla(0,0%,100%,.1);border-color:hsla(0,0%,100%,.1);color:#fff}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px hsla(0,0%,100%,.25)}.dot{border-radius:50px;display:inline-block;height:10px;margin-left:auto!important;width:10px}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;opacity:1;transition:all .4s cubic-bezier(.96,-.07,.34,1.01)}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:none!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:none!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{border:0!important;transform:scale(.9) rotate(180deg)}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#28a745}.btn-lock-peer.lock,.btn-lock-peer.lock:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{color:#17a2b8}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{background:#fff;border-color:#007bff;color:#007bff}.peer_data_group{display:flex;margin-bottom:.5rem;text-align:right}.peer_data_group p{margin-bottom:0;margin-right:1rem;text-transform:uppercase}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{align-items:center;display:flex;justify-content:flex-end;text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{bottom:3rem;display:flex;position:fixed;right:2rem;z-index:99}.btn-manage-group .setting_btn_menu{background-color:#fff;border-radius:10px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);display:none;min-width:200px;opacity:0;padding:1rem 0;position:absolute;right:0;top:-124px;transform:translateY(-30px);transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{opacity:1;transform:translateY(0)}.setting_btn_menu a{align-items:center;cursor:pointer;display:flex;font-size:1rem;padding:.5rem 1rem;transition:all .1s ease-in-out}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{border-radius:100px!important;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem;height:54px;padding:0 14px;z-index:99}@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(1turn);-moz-transform:rotate(1turn);-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}.rotating:before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{cursor:pointer;font-size:1.2rem;position:absolute;right:2rem;transform:translateY(-28px)}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.progress-bar{transition:.3s ease-in-out}.key{cursor:pointer;transition:.2s ease-in-out}.key:hover{color:#007bff}.card{border-radius:10px}.peer_list .card .button-group{height:22px}.form-control{border-radius:10px}.btn{border-radius:8px}#password,#username{height:inherit;padding:.6rem calc(.9rem + 32px)}label[for=password],label[for=username]{font-size:1rem;margin:0!important;padding:0;transform:translateY(30px) translateX(16px)}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}@-webkit-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}@-moz-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{height:19.19px;opacity:0!important}#conf_status_btn{transition:.2s ease-in-out}#conf_status_btn.info_loading{animation:loading 3s ease-in-out infinite;border-radius:5px;height:38px}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{filter:brightness(.5);transition:filter .2s ease-in-out}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-x:hidden;overflow-y:scroll}.no-response{align-items:center;background:#000000ba;display:none;flex-direction:column;height:100%;justify-content:center;opacity:0;position:fixed;transition:all 1s ease-in-out;width:100%;z-index:10000}.no-response.active{display:flex}.no-response.active.show{opacity:1}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px);transition:all 1s ease-in-out}pre.index-alert{background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;color:#fff;margin-bottom:0;margin-top:1rem;padding:1rem}.peerNameCol{align-items:center;display:flex;margin-bottom:.2rem}.peerName{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.peerLightContainer{margin:0;margin-left:auto!important;text-transform:uppercase}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{align-items:center;display:flex;margin-bottom:1rem}.chartTitle h6{line-height:1;margin-bottom:0;margin-right:.5rem}.chartContainer.fullScreen{background-color:#fff;height:100%;left:0;padding:32px;position:fixed;top:0;width:calc(100% + 15px);z-index:9999}.chartContainer.fullScreen .col-sm{height:100%;padding-right:0}.chartContainer.fullScreen .chartCanvasContainer{height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important;width:100%}#switch{transition:all .35s ease-in}.toggle--switch{display:none}.toggleLabel{background-color:#6c757d17;border:2px solid #6c757d8c;border-radius:100px;cursor:pointer;display:flex;height:32px;margin:0;position:relative;transition:all .35s ease-in;width:64px}.toggle--switch.waiting+.toggleLabel{opacity:.5}.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:off;background-color:#6c757d;border-radius:100px;content:"";cursor:pointer;height:26px;margin:1px;position:absolute;transition:all .35s ease-in;width:26px}.toggle--switch:checked+.toggleLabel{background-color:#007bff17!important;border:2px solid #007bff8c}.toggle--switch:checked+.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:on;background-color:#007bff}@keyframes on{0%{left:0}60%{left:0;width:40px}to{left:32px;width:26px}}@keyframes off{0%{left:32px}60%{left:18px;width:40px}to{left:0;width:26px}}.toast{min-width:300px}.toast,.toast-header{background-color:#fff}.toast-progressbar{background-color:#007bff;border-bottom-left-radius:.25rem;height:4px;width:100%} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 021d851b..09ff7a66 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -5,23 +5,22 @@ -(function(){ +(function() { /** * Definitions */ - let peers = []; let configuration_name; let configuration_interval; let configuration_timeout = window.localStorage.getItem("configurationTimeout"); - if (configuration_timeout === null || !["5000", "10000", "30000", "60000"].includes(configuration_timeout)){ + if (configuration_timeout === null || !["5000", "10000", "30000", "60000"].includes(configuration_timeout)) { window.localStorage.setItem("configurationTimeout", "10000"); configuration_timeout = window.localStorage.getItem("configurationTimeout"); } document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active"); let display_mode = window.localStorage.getItem("displayMode"); - if (display_mode === null || !["grid", "list"].includes(display_mode)){ + if (display_mode === null || !["grid", "list"].includes(display_mode)) { window.localStorage.setItem("displayMode", "grid"); display_mode = "grid"; } @@ -48,11 +47,11 @@ */ let chartUnit = window.localStorage.chartUnit; let chartUnitAvailable = ["GB", "MB", "KB"]; - - if (chartUnit === null || !chartUnitAvailable.includes(chartUnit)){ + + if (chartUnit === null || !chartUnitAvailable.includes(chartUnit)) { window.localStorage.setItem("chartUnit", "GB"); $('.switchUnit[data-unit="GB"]').addClass("active"); - }else{ + } else { $(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active"); } chartUnit = window.localStorage.getItem("chartUnit"); @@ -63,8 +62,7 @@ type: 'line', data: { labels: [], - datasets: [ - { + datasets: [{ label: 'Data Sent', data: [], stroke: '#FFFFFF', @@ -85,7 +83,7 @@ options: { maintainAspectRatio: false, showScale: false, - responsive:false, + responsive: false, scales: { y: { min: 0, @@ -108,21 +106,21 @@ } } }); - + let $totalDataUsageChartObj = $("#totalDataUsageChartObj"); $totalDataUsageChartObj.css("width", "100%"); totalDataUsageChartObj.width = $totalDataUsageChartObj.parent().width(); totalDataUsageChartObj.resize(); $(window).on("resize", function() { - totalDataUsageChartObj.resize(); + totalDataUsageChartObj.resize(); }); - $(".fullScreen").on("click", function(){ + $(".fullScreen").on("click", function() { let $chartContainer = $(".chartContainer"); - if ($chartContainer.hasClass("fullScreen")){ + if ($chartContainer.hasClass("fullScreen")) { $(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"); $chartContainer.removeClass("fullScreen"); - }else{ + } else { $(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit"); $chartContainer.addClass("fullScreen"); } @@ -130,32 +128,32 @@ }); let mul = 1; - $(".switchUnit").on("click", function(){ + $(".switchUnit").on("click", function() { $(".switchUnit").removeClass("active"); $(this).addClass("active"); - if ($(this).data('unit') !== chartUnit){ + if ($(this).data('unit') !== chartUnit) { switch ($(this).data('unit')) { case "GB": - if (chartUnit === "MB"){ - mul = 1/1024; + if (chartUnit === "MB") { + mul = 1 / 1024; } - if (chartUnit === "KB"){ - mul = 1/1048576; + if (chartUnit === "KB") { + mul = 1 / 1048576; } break; case "MB": - if (chartUnit === "GB"){ + if (chartUnit === "GB") { mul = 1024; } - if (chartUnit === "KB"){ - mul = 1/1024; + if (chartUnit === "KB") { + mul = 1 / 1024; } break; case "KB": - if (chartUnit === "GB"){ + if (chartUnit === "GB") { mul = 1048576; } - if (chartUnit === "MB"){ + if (chartUnit === "MB") { mul = 1024; } break; @@ -176,7 +174,7 @@ * @param response */ function configurationAlert(response) { - if (response.listen_port === "" && response.status === "stopped"){ + if (response.listen_port === "" && response.status === "stopped") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -184,7 +182,7 @@ configAlert.innerHTML = 'Peer QR Code and configuration file download required a specified Listen Port.'; document.querySelector("#config_info_alert").appendChild(configAlert); } - if (response.conf_address === "N/A"){ + if (response.conf_address === "N/A") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -194,21 +192,21 @@ } } - function setActiveConfigurationName(){ + function setActiveConfigurationName() { $(".nav-conf-link").removeClass("active"); $(`.sb-${configuration_name}-url`).addClass("active"); } let firstLoading = true; - $(".nav-conf-link").on("click", function(e){ + $(".nav-conf-link").on("click", function(e) { e.preventDefault(); - if (configuration_name !== $(this).data("conf-id")){ + if (configuration_name !== $(this).data("conf-id")) { firstLoading = true; $("#config_body").addClass("firstLoading"); configuration_name = $(this).data("conf-id"); - if(loadPeers($('#search_peer_textbox').val())){ + if (loadPeers($('#search_peer_textbox').val())) { setActiveConfigurationName(); - window.history.pushState(null,null,`/configuration/${configuration_name}`); + window.history.pushState(null, null, `/configuration/${configuration_name}`); $("title").text(`${configuration_name} | WGDashboard`); totalDataUsageChartObj.data.labels = []; @@ -224,26 +222,28 @@ * @param response */ function configurationHeader(response) { - let $conf_status_btn = document.getElementById("conf_status_btn"); - if (response.checked === "checked"){ - $conf_status_btn.innerHTML = ` ON`; - }else{ - $conf_status_btn.innerHTML = ` OFF`; - } + let $conf_status_btn = $(".toggle--switch"); - if (response.running_peer > 0){ + if (response.checked === "checked") { + $conf_status_btn.prop("checked", true) + }else{ + $conf_status_btn.prop("checked", false) + } + $conf_status_btn.data("conf-id", configuration_name) + + + if (response.running_peer > 0) { let d = new Date(); - let time = d.toLocaleString("en-us", - {hour: '2-digit', minute: '2-digit', second: "2-digit", hourCycle: 'h23'}); + let time = d.toLocaleString("en-us", { hour: '2-digit', minute: '2-digit', second: "2-digit", hourCycle: 'h23' }); totalDataUsageChartObj.data.labels.push(`${time}`); - if (totalDataUsageChartObj.data.datasets[0].data.length === 0){ + if (totalDataUsageChartObj.data.datasets[0].data.length === 0) { totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; totalDataUsageChartObj.data.datasets[0].data.push(0); totalDataUsageChartObj.data.datasets[1].data.push(0); - }else{ - if (totalDataUsageChartObj.data.datasets[0].data.length === 50 && totalDataUsageChartObj.data.datasets[1].data.length === 50){ + } else { + if (totalDataUsageChartObj.data.datasets[0].data.length === 50 && totalDataUsageChartObj.data.datasets[1].data.length === 50) { totalDataUsageChartObj.data.labels.shift(); totalDataUsageChartObj.data.datasets[0].data.shift(); totalDataUsageChartObj.data.datasets[1].data.shift(); @@ -252,16 +252,15 @@ let newTotalReceive = response.total_data_usage[2] - totalDataUsageChartObj.data.datasets[1].lastData; let newTotalSent = response.total_data_usage[1] - totalDataUsageChartObj.data.datasets[0].lastData; let k = 0; - if (chartUnit === "MB"){ + if (chartUnit === "MB") { k = 1024; - } - else if (chartUnit === "KB"){ + } else if (chartUnit === "KB") { k = 1048576; - }else{ + } else { k = 1; } - totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k); - totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k); + totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive * k); + totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent * k); totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; } @@ -270,11 +269,9 @@ } document.querySelector("#conf_name").textContent = configuration_name; - $conf_status_btn.classList.remove("info_loading"); + $("#switch").removeClass("info_loading"); document.querySelectorAll("#sort_by_dropdown option").forEach(ele => ele.removeAttribute("selected")); document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected", "selected"); - // document.querySelectorAll(".interval-btn-group button").forEach(ele => ele.classList.remove("active")); - // document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active"); document.querySelector("#conf_status").innerHTML = `${response.status}`; document.querySelector("#conf_connected_peers").innerHTML = response.running_peer; document.querySelector("#conf_total_data_usage").innerHTML = `${response.total_data_usage[0]} GB`; @@ -283,20 +280,26 @@ document.querySelector("#conf_public_key").innerHTML = response.public_key; document.querySelector("#conf_listen_port").innerHTML = response.listen_port === "" ? "N/A" : response.listen_port; document.querySelector("#conf_address").innerHTML = response.conf_address; - document.querySelectorAll(".info h6").forEach(ele => ele.classList.remove("info_loading")); + let delay = 0; + let h6 = $(".info h6"); + for (let i = 0; i < h6.length; i++){ + setTimeout(function(){ + $(h6[i]).removeClass("info_loading"); + }, delay) + delay += 40 + } } - /** * Parse all responded information onto the peers list * @param response */ function configurationPeers(response) { let result = ""; - if (response.peer_data.length === 0){ + if (response.peer_data.length === 0) { document.querySelector(".peer_list").innerHTML = `

Oops! No peers found ‘︿’

`; - }else{ + } else { let mode = display_mode === "list" ? "col-12" : "col-sm-6 col-lg-4"; - response.peer_data.forEach(function(peer){ + response.peer_data.forEach(function(peer) { let total_r = 0; let total_s = 0; total_r += peer.cumu_receive; @@ -316,49 +319,102 @@ ${roundN(peer.total_sent + total_s, 4)} GB

`; - let peer_key = '
PEERCLICK TO COPY
'+peer.id+'
'; - let peer_allowed_ip = '
ALLOWED IP
'+peer.allowed_ip+'
'; - let peer_latest_handshake = '
LATEST HANDSHAKE
'+peer.latest_handshake+'
'; - let peer_endpoint = '
END POINT
'+peer.endpoint+'
'; + let peer_key = '
PEERCLICK TO COPY
' + peer.id + '
'; + let peer_allowed_ip = '
ALLOWED IP
' + peer.allowed_ip + '
'; + let peer_latest_handshake = '
LATEST HANDSHAKE
' + peer.latest_handshake + '
'; + let peer_endpoint = '
END POINT
' + peer.endpoint + '
'; let peer_control = `

- - - `; - if (peer.private_key !== ""){ - peer_control += ''; + if (peer.private_key !== "") { + peer_control += ''; } peer_control += '
'; - let html = '
' + - '
' + - '
' + - '
' + - peer_name + - spliter + - peer_transfer + - peer_key + - peer_allowed_ip + - peer_latest_handshake + - spliter + - peer_endpoint + - spliter + - peer_control + - '
' + - '
' + - '
' + - '
'; + let html = '
' + + '
' + + '
' + + '
' + + peer_name + + spliter + + peer_transfer + + peer_key + + peer_allowed_ip + + peer_latest_handshake + + spliter + + peer_endpoint + + spliter + + peer_control + + '
' + + '
' + + '
' + + '
'; + result += html; + }); + response.lock_access_peers.forEach(function(peer) { + let total_r = 0; + let total_s = 0; + total_r += peer.cumu_receive; + total_s += peer.cumu_sent; + let spliter = '
'; + let peer_name = + `
+
${peer.name === "" ? "Untitled" : peer.name}
+
+
`; + let peer_transfer = + `
+

+ ${roundN(peer.total_receive + total_r, 4)} GB +

+

+ ${roundN(peer.total_sent + total_s, 4)} GB +

+
`; + let peer_key = '
PEERCLICK TO COPY
' + peer.id + '
'; + let peer_allowed_ip = '
ALLOWED IP
' + peer.allowed_ip + '
'; + let peer_latest_handshake = '
LATEST HANDSHAKE
' + peer.latest_handshake + '
'; + let peer_endpoint = '
END POINT
' + peer.endpoint + '
'; + let peer_control = ` +
+
+
+ + Peer Disabled +
`; + let html = '
' + + '
' + + '
' + + '
' + + peer_name + + spliter + + peer_transfer + + peer_key + + peer_allowed_ip + + peer_latest_handshake + + spliter + + peer_endpoint + + spliter + + peer_control + + '
' + + '
' + + '
' + + '
'; result += html; }); document.querySelector(".peer_list").innerHTML = result; - if (configuration_interval === undefined){ + if (configuration_interval === undefined) { setConfigurationInterval(); } } @@ -369,18 +425,18 @@ */ function addPeersByBulk() { let $new_add_amount = $("#new_add_amount"); - $add_peer.setAttribute("disabled","disabled"); + $add_peer.setAttribute("disabled", "disabled"); $add_peer.innerHTML = `Adding ${$new_add_amount.val()} peers...`; let $new_add_DNS = $("#new_add_DNS"); $new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val())); let $new_add_endpoint_allowed_ip = $("#new_add_endpoint_allowed_ip"); - $new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val())); + $new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val())); let $new_add_MTU = $("#new_add_MTU"); let $new_add_keep_alive = $("#new_add_keep_alive"); let $enable_preshare_key = $("#enable_preshare_key"); - let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip,$new_add_MTU, $new_add_keep_alive]; - if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")){ - if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ + let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip, $new_add_MTU, $new_add_keep_alive]; + if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")) { + if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== "") { let conf = configuration_name; let keys = []; for (let i = 0; i < $new_add_amount.val(); i++) { @@ -388,8 +444,8 @@ } $.ajax({ method: "POST", - url: "/add_peer_bulk/"+conf, - headers:{ + url: "/add_peer_bulk/" + conf, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ @@ -401,30 +457,29 @@ "keys": keys, "amount": $new_add_amount.val() }), - success: function (response){ - if(response !== "true"){ + 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{ + } else { window.configurations.loadPeers(""); data_list.forEach((ele) => ele.removeAttr("disabled")); $("#add_peer_form").trigger("reset"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; - window.configurations.showToast($new_add_amount.val()+" peers added successful!"); + window.configurations.showToast($new_add_amount.val() + " peers added successful!"); window.configurations.addModal().toggle(); } } }); - }else{ + } else { $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; } - }else{ + } else { $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; } @@ -435,41 +490,39 @@ * @param config * @param peer_ids */ - function deletePeers(config, peer_ids){ + function deletePeers(config, peer_ids) { $.ajax({ method: "POST", - url: "/remove_peer/"+config, - headers:{ + url: "/remove_peer/" + config, + headers: { "Content-Type": "application/json" }, - data: JSON.stringify({"action": "delete", "peer_ids": peer_ids}), - success: function (response){ - if(response !== "true"){ + data: JSON.stringify({ "action": "delete", "peer_ids": peer_ids }), + success: function(response) { + if (response !== "true") { if (window.configurations.deleteModal()._isShown) { - $("#remove_peer_alert").html(response+$("#add_peer_alert").html()) - .removeClass("d-none"); + $("#remove_peer_alert").html(response + $("#add_peer_alert").html()) + .removeClass("d-none"); $("#delete_peer").removeAttr("disabled").html("Delete"); } - if (window.configurations.deleteBulkModal()._isShown){ + if (window.configurations.deleteBulkModal()._isShown) { let $bulk_remove_peer_alert = $("#bulk_remove_peer_alert"); - $bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()) - .removeClass("d-none"); + $bulk_remove_peer_alert.html(response + $bulk_remove_peer_alert.html()) + .removeClass("d-none"); $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); } - } - else{ + } else { if (window.configurations.deleteModal()._isShown) { window.configurations.deleteModal().toggle(); } - if (window.configurations.deleteBulkModal()._isShown){ + if (window.configurations.deleteBulkModal()._isShown) { $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); $("#selected_peer_list").html(''); $(".delete-bulk-peer-item.active").removeClass('active'); window.configurations.deleteBulkModal().toggle(); } window.configurations.loadPeers($('#search_peer_textbox').val()); - $('#alertToast').toast('show'); - $('#alertToast .toast-body').html("Peer deleted!"); + window.configurations.showToast(`Deleted ${peer_ids.length} peers`) $("#delete_peer").removeAttr("disabled").html("Delete"); } } @@ -479,74 +532,74 @@ /** * Handle when the server is not responding */ - function noResponding(message = "Opps!
I can't connect to the server."){ + function noResponding(message = "Opps!
I can't connect to the server.") { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("active")); - setTimeout(function (){ + setTimeout(function() { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("show")); document.querySelector("#right_body").classList.add("no-responding"); document.querySelector(".navbar").classList.add("no-responding"); document.querySelector(".no-response .container h4").innerHTML = message; - },10); + }, 10); } /** * Remove no responding */ - function removeNoResponding(){ + function removeNoResponding() { document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("show")); document.querySelector("#right_body").classList.remove("no-responding"); document.querySelector(".navbar").classList.remove("no-responding"); - setTimeout(function (){ + setTimeout(function() { document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("active")); - },1010); + }, 1010); } /** * Set configuration refresh Interval */ - function setConfigurationInterval(){ - configuration_interval = setInterval(function (){ + function setConfigurationInterval() { + configuration_interval = setInterval(function() { loadPeers($('#search_peer_textbox').val()); - }, configuration_timeout); + }, configuration_timeout); } /** * Remove configuration refresh interval */ - function removeConfigurationInterval(){ + function removeConfigurationInterval() { clearInterval(configuration_interval); } /** * Start Progress Bar */ - function startProgressBar(){ - $progress_bar.css("width","0%") + function startProgressBar() { + $progress_bar.css("width", "0%") .css("opacity", "100") .css("background", "rgb(255,69,69)") .css("background", "linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)") - .css("width","25%"); - setTimeout(function(){ + .css("width", "25%"); + setTimeout(function() { stillLoadingProgressBar(); - },300); + }, 300); } /** * Still Loading Progress Bar */ - function stillLoadingProgressBar(){ + function stillLoadingProgressBar() { $progress_bar.css("transition", "3s ease-in-out").css("width", "75%"); } /** * End Progress Bar */ - function endProgressBar(){ - $progress_bar.css("transition", "0.3s ease-in-out").css("width","100%"); - setTimeout(function(){ + function endProgressBar() { + $progress_bar.css("transition", "0.3s ease-in-out").css("width", "100%"); + setTimeout(function() { $progress_bar.css("opacity", "0"); - },250); + }, 250); } /** @@ -556,8 +609,8 @@ * @returns {number} */ function roundN(value, digits) { - let tenToN = 10 ** digits; - return (Math.round(value * tenToN)) / tenToN; + let tenToN = 10 ** digits; + return (Math.round(value * tenToN)) / tenToN; } /** @@ -567,25 +620,27 @@ let time = 0; let count = 0; let d1 = new Date(); - function loadPeers(searchString){ + + function loadPeers(searchString) { d1 = new Date(); let good = true; $.ajax({ method: "GET", url: `/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`, - headers:{"Content-Type": "application/json"} - }).done(function(response){ + headers: { "Content-Type": "application/json" } + }).done(function(response) { console.log(response); parsePeers(response); - }).fail(function(){ + }).fail(function() { noResponding(); good = false; }); return good; } - function parsePeers(response){ - if (response.status){ + function parsePeers(response) { + if (response.status) { + removeAllTooltips(); let d2 = new Date(); let seconds = (d2 - d1); time += seconds; @@ -597,25 +652,44 @@ configurationAlert(response.data); configurationHeader(response.data); configurationPeers(response.data); - - $(".dot.dot-running").attr("title","Peer Connected").tooltip(); - $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); + + $(".dot.dot-running").attr("title", "Peer Connected").tooltip(); + $(".dot.dot-stopped").attr("title", "Peer Disconnected").tooltip(); $("i[data-toggle='tooltip']").tooltip(); $("#configuration_name").text(configuration_name); - if (firstLoading){ + if (firstLoading) { firstLoading = false; $("#config_body").removeClass("firstLoading"); } - }else{ + } else { noResponding(response.message); removeConfigurationInterval(); } } + function removeAllTooltips(){ + $(".tooltip").remove() + } + + function toggleAccess(peerID){ + $.ajax({ + url: "/api/togglePeerAccess", + method: "POST", + headers: {"Content-Type": "application/json"}, + data: JSON.stringify({"peerID": peerID, "config": configuration_name}) + }).done(function(res){ + if(res.status){ + loadPeers($('#search_peer_textbox').val()); + }else{ + showToast(res.reason); + } + }); + } + /** * Generate Private and Public key for a new peer */ - function generate_key(){ + function generate_key() { let keys = window.wireguard.generateKeypair(); document.querySelector("#private_key").value = keys.privateKey; document.querySelector("#public_key").value = keys.publicKey; @@ -628,9 +702,24 @@ * Show toast * @param msg */ + let numberToast = 0; function showToast(msg) { - $('#alertToast').toast('show'); - $('#alertToast .toast-body').html(msg); + $(".toastContainer").append( + `` ) + $(`#${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"); + numberToast++; } /** @@ -643,7 +732,7 @@ window.localStorage.setItem("configurationTimeout", configuration_timeout.toString()); removeConfigurationInterval(); setConfigurationInterval(); - showToast("Refresh Interval set to "+Math.round(interval/1000)+" seconds"); + showToast("Refresh Interval set to " + Math.round(interval / 1000) + " seconds"); } /** @@ -651,7 +740,7 @@ * @param val * @returns {string} */ - function cleanIp(val){ + function cleanIp(val) { let clean_ip = val.split(','); for (let i = 0; i < clean_ip.length; i++) { clean_ip[i] = clean_ip[i].trim(' '); @@ -663,13 +752,13 @@ * Trigger IP badge and item * @param ip */ - function trigger_ip(ip){ + function trigger_ip(ip) { let $ip_ele = document.querySelector(`.available-ip-item[data-ip='${ip}']`); - if ($ip_ele){ - if ($ip_ele.classList.contains("active")){ + if ($ip_ele) { + if ($ip_ele.classList.contains("active")) { $ip_ele.classList.remove("active"); document.querySelector(`#selected_ip_list .badge[data-ip='${ip}']`).remove(); - }else{ + } else { $ip_ele.classList.add("active"); document.querySelector("#selected_ip_list").innerHTML += `${ip}`; } @@ -680,10 +769,10 @@ * Download single configuration file * @param conf */ - function download_one_config(conf){ + function download_one_config(conf) { let link = document.createElement('a'); link.download = conf.filename; - let blob = new Blob([conf.content], {type: 'text/conf'}); + let blob = new Blob([conf.content], { type: 'text/conf' }); link.href = window.URL.createObjectURL(blob); link.click(); } @@ -692,16 +781,16 @@ * Toggle delete by bulk IP * @param element */ - function toggleBulkIP(element){ + function toggleBulkIP(element) { let $selected_peer_list = $("#selected_peer_list"); let id = element.data("id"); let name = element.data("name") === "" ? "Untitled Peer" : element.data("name"); - if (element.hasClass("active")){ + if (element.hasClass("active")) { element.removeClass("active"); - $("#selected_peer_list .badge[data-id='"+id+"']").remove(); - }else{ + $("#selected_peer_list .badge[data-id='" + id + "']").remove(); + } else { element.addClass("active"); - $selected_peer_list.append(''+name+' - '+id+''); + $selected_peer_list.append('' + name + ' - ' + id + ''); } } @@ -712,7 +801,7 @@ function copyToClipboard(element) { let $temp = $(""); $body.append($temp); - $temp.val($(element).text()).trigger( "select" ); + $temp.val($(element).text()).trigger("select"); document.execCommand("copy"); $temp.remove(); } @@ -720,20 +809,20 @@ /** * Get all available IP for this configuration */ - function getAvailableIps(){ + function getAvailableIps() { $.ajax({ "url": `/available_ips/${configuration_name}`, "method": "GET", - }).done(function (res) { - if (res.status === true){ + }).done(function(res) { + if (res.status === true) { available_ips = res.data; let $list_group = document.querySelector("#available_ip_modal .modal-body .list-group"); $list_group.innerHTML = ""; document.querySelector("#allowed_ips").value = available_ips[0]; available_ips.forEach((ip) => $list_group.innerHTML += - `${ip}`); - }else{ + `${ip}`); + } else { document.querySelector("#allowed_ips").value = res.message; document.querySelector("#search_available_ip").setAttribute("disabled", "disabled"); } @@ -747,15 +836,17 @@ ipModal: () => { return ipModal; }, qrcodeModal: () => { return qrcodeModal; }, settingModal: () => { return settingModal; }, - configurationTimeout: () => { return configuration_timeout;}, - updateDisplayMode: () => { display_mode = window.localStorage.getItem("displayMode")}, + configurationTimeout: () => { return configuration_timeout; }, + updateDisplayMode: () => { display_mode = window.localStorage.getItem("displayMode") }, loadPeers: (searchString) => { loadPeers(searchString); }, addPeersByBulk: () => { addPeersByBulk(); }, deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); }, parsePeers: (response) => { parsePeers(response); }, + toggleAccess: (peerID) => { toggleAccess(peerID) }, - setConfigurationName: (confName) => { configuration_name = confName;}, + + setConfigurationName: (confName) => { configuration_name = confName; }, getConfigurationName: () => { return configuration_name; }, setActiveConfigurationName: () => { setActiveConfigurationName(); }, getAvailableIps: () => { getAvailableIps(); }, @@ -793,13 +884,33 @@ document.querySelector(".add_btn").addEventListener("click", () => { /** * When configuration switch got click */ -document.querySelector(".info").addEventListener("click", (event) => { - let selector = document.querySelector(".switch"); - if (selector.contains(event.target)){ - selector.style.display = "none"; - document.querySelector('div[role=status]').style.display = "inline-block"; - location.replace(`/switch/${selector.getAttribute("id")}`); - } +$(".toggle--switch").on("click", function(){ + $(this).addClass("waiting").attr("disabled", "disabled"); + let id = window.configurations.getConfigurationName(); + let status = $(this).prop("checked"); + let ele = $(this); + $.ajax({ + url: `/switch/${id}` + }).done(function(res){ + console.log(); + if (res){ + if (status){ + window.configurations.showToast(`${id} is running.`) + }else{ + window.configurations.showToast(`${id} is stopped.`) + } + ele.removeClass("waiting"); + ele.removeAttr("disabled"); + }else{ + if (status){ + $(this).prop("checked", false) + }else{ + $(this).prop("checked", true) + } + } + window.configurations.loadPeers($('#search_peer_textbox').val()) + }); + }); /** @@ -807,10 +918,10 @@ document.querySelector(".info").addEventListener("click", (event) => { */ document.querySelector("#private_key").addEventListener("change", (event) => { let publicKey = document.querySelector("#public_key"); - if (event.target.value.length === 44){ + if (event.target.value.length === 44) { publicKey.value = window.wireguard.generatePublicKey(event.target.value); publicKey.setAttribute("disabled", "disabled"); - }else{ + } else { publicKey.attributes.removeNamedItem("disabled"); publicKey.value = ""; } @@ -819,18 +930,18 @@ document.querySelector("#private_key").addEventListener("change", (event) => { /** * Handle when add modal is show and hide */ -$('#add_modal').on('show.bs.modal', function () { +$('#add_modal').on('show.bs.modal', function() { window.configurations.generateKeyPair(); window.configurations.getAvailableIps(); -}).on('hide.bs.modal', function(){ +}).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").on("click", function() { + $("#public_key").attr("disabled", "disabled"); $("#re_generate_key i").addClass("rotating"); window.configurations.generateKeyPair(); }); @@ -838,13 +949,13 @@ $("#re_generate_key").on("click",function (){ /** * Handle when user is editing in allowed ips textbox */ -$("#allowed_ips").on("keyup", function(){ +$("#allowed_ips").on("keyup", function() { let s = window.configurations.cleanIp($(this).val()); s = s.split(","); - if (available_ips.includes(s[s.length - 1])){ + if (available_ips.includes(s[s.length - 1])) { $("#allowed_ips_indicator").removeClass().addClass("text-success") .html(''); - }else{ + } else { $("#allowed_ips_indicator").removeClass().addClass("text-warning") .html(''); } @@ -853,18 +964,18 @@ $("#allowed_ips").on("keyup", function(){ /** * Change peer name when user typing in peer name textbox */ -$("#peer_name_textbox").on("keyup", function(){ +$("#peer_name_textbox").on("keyup", function() { $(".peer_name").html($(this).val()); }); /** * When Add Peer button got clicked */ -$add_peer.addEventListener("click",function(){ +$add_peer.addEventListener("click", function() { let $bulk_add = $("#bulk_add"); - if ($bulk_add.prop("checked")){ - if (!$("#new_add_amount").hasClass("is-invalid")){ - window.configurations.addPeersByBulk(); + if ($bulk_add.prop("checked")) { + if (!$("#new_add_amount").hasClass("is-invalid")) { + window.configurations.addPeersByBulk(); } } else { let $public_key = $("#public_key"); @@ -879,23 +990,23 @@ $add_peer.addEventListener("click",function(){ 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.setAttribute("disabled", "disabled"); $add_peer.innerHTML = "Adding..."; - if ($allowed_ips.val() !== "" && $public_key.val() !== "" && $new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ + if ($allowed_ips.val() !== "" && $public_key.val() !== "" && $new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== "") { let conf = window.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]; + 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:{ + url: "/add_peer/" + conf, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ - "private_key":$private_key.val(), - "public_key":$public_key.val(), + "private_key": $private_key.val(), + "public_key": $public_key.val(), "allowed_ips": $allowed_ips.val(), - "name":$new_add_name.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(), @@ -903,14 +1014,13 @@ $add_peer.addEventListener("click",function(){ "enable_preshared_key": $enable_preshare_key.prop("checked"), "preshared_key": $enable_preshare_key.val() }), - success: function (response){ - if(response !== "true"){ + 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{ + } else { window.configurations.loadPeers(""); data_list.forEach((ele) => ele.removeAttr("disabled")); $("#add_peer_form").trigger("reset"); @@ -921,7 +1031,7 @@ $add_peer.addEventListener("click",function(){ } } }); - }else{ + } else { $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; @@ -933,23 +1043,23 @@ $add_peer.addEventListener("click",function(){ * 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(){ +$("#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())){ + 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){ + } 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){ + } else if ($(this).val() < 1) { $(this).removeClass("is-valid").addClass("is-invalid"); $bulk_amount_validation.html("Please enter at least 1 or more."); - }else{ + } else { $(this).removeClass("is-invalid").addClass("is-valid"); } - }else{ + } else { $(this).removeClass("is-invalid").removeClass("is-valid"); } }); @@ -957,18 +1067,17 @@ $("#new_add_amount").on("keyup", function(){ /** * Handle when user toggled add peers by bulk */ -$("#bulk_add").on("change", function (){ +$("#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++){ + 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"){ + } else { + for (let i = 0; i < hide.length; i++) { + if ($(hide[i]).attr('id') !== "public_key") { $(hide[i]).removeAttr("disabled"); } } @@ -992,7 +1101,7 @@ $("#available_ip_modal").on("show.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++){ + for (let i = 0; i < $selected_ip_list.childElementCount; i++) { ips.push($selected_ip_list.children[i].dataset.ip); } ips.forEach((ele) => window.configurations.triggerIp(ele)); @@ -1001,27 +1110,27 @@ $("#available_ip_modal").on("show.bs.modal", () => { /** * When IP Badge got click */ -$body.on("click", ".available-ip-badge", function(){ - $(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active"); +$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 () { +$body.on("click", ".available-ip-item", function() { window.configurations.triggerIp($(this).data("ip")); }); /** * When search IP button got clicked */ -$("#search_available_ip").on("click", function () { +$("#search_available_ip").on("click", function() { window.configurations.ipModal().toggle(); let $allowed_ips = document.querySelector("#allowed_ips"); - if ($allowed_ips.value.length > 0){ + if ($allowed_ips.value.length > 0) { let s = $allowed_ips.value.split(","); - for (let i = 0; i < s.length; i++){ + for (let i = 0; i < s.length; i++) { s[i] = s[i].trim(); window.configurations.triggerIp(s[i]); } @@ -1035,7 +1144,7 @@ $("#confirm_ip").on("click", () => { window.configurations.ipModal().toggle(); let ips = []; let $selected_ip_list = $("#selected_ip_list"); - $selected_ip_list.children().each(function(){ + $selected_ip_list.children().each(function() { ips.push($(this).data("ip")); }); $("#allowed_ips").val(ips.join(", ")); @@ -1051,12 +1160,12 @@ $("#confirm_ip").on("click", () => { /** * When the QR-code button got clicked on each peer */ -$body.on("click", ".btn-qrcode-peer", function (){ +$body.on("click", ".btn-qrcode-peer", function() { let src = $(this).data('imgsrc'); $.ajax({ "url": src, "method": "GET" - }).done(function(res){ + }).done(function(res) { $("#qrcode_img").attr('src', res); window.configurations.qrcodeModal().toggle(); }); @@ -1071,30 +1180,32 @@ $body.on("click", ".btn-qrcode-peer", function (){ /** * When the delete button got clicked on each peer */ -$body.on("click", ".btn-delete-peer", function(){ - let peer_id = $(this).attr("id"); +$body.on("click", ".btn-delete-peer", function() { + let peer_id = $(this).data('peer-id') $("#delete_peer").data("peer-id", peer_id); window.configurations.deleteModal().toggle(); }); -$body.on("click", ".btn-lock-peer", function(){ - let $lockGlyph = "bi-lock-fill"; - let $unlockGlyph = "bi-unlock-fill"; - - if ($(this).children().hasClass($lockGlyph)){ - $(this).children().removeClass($lockGlyph).addClass($unlockGlyph); - $(this).children().tooltip('hide').attr('data-original-title', 'Lock Peer').tooltip('show'); - }else{ - $(this).children().removeClass($unlockGlyph).addClass($lockGlyph); - $(this).children().tooltip('hide').attr('data-original-title', 'Unlock Peer').tooltip('show'); +$body.on("click", ".btn-lock-peer", function() { + window.configurations.toggleAccess($(this).data('peer-id'), window.configurations.getConfigurationName()); + if ($(this).hasClass("lock")) { + console.log($(this).data("peer-name")) + window.configurations.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 + window.configurations.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"); +$("#delete_peer").on("click", function() { + $(this).attr("disabled", "disabled"); $(this).html("Deleting..."); let config = window.configurations.getConfigurationName(); let peer_ids = [$(this).data("peer-id")]; @@ -1110,18 +1221,18 @@ $("#delete_peer").on("click",function(){ /** * Handle when setting button got clicked for each peer */ -$body.on("click", ".btn-setting-peer", function(){ +$body.on("click", ".btn-setting-peer", function() { // window.configurations.startProgressBar(); - let peer_id = $(this).attr("id"); + let peer_id = $(this).data("peer-id"); $("#save_peer_setting").attr("peer_id", peer_id); $.ajax({ method: "POST", - url: "/get_peer_data/"+window.configurations.getConfigurationName(), - headers:{ + url: "/get_peer_data/" + window.configurations.getConfigurationName(), + headers: { "Content-Type": "application/json" }, - data: JSON.stringify({"id": peer_id}), - success: function(response){ + 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); @@ -1141,28 +1252,28 @@ $body.on("click", ".btn-setting-peer", function(){ /** * Handle when setting modal is closing */ -$('#setting_modal').on('hidden.bs.modal', function () { - $("#setting_peer_alert").addClass("d-none"); +$('#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(){ +$("#peer_private_key_textbox").on("change", function() { let $save_peer_setting = $("#save_peer_setting"); - if ($(this).val().length > 0){ + if ($(this).val().length > 0) { $.ajax({ - "url": "/check_key_match/"+window.configurations.getConfigurationName(), + "url": "/check_key_match/" + window.configurations.getConfigurationName(), "method": "POST", - "headers":{"Content-Type": "application/json"}, + "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"){ + }).done(function(res) { + if (res.status === "failed") { $("#setting_peer_alert").html(res.status).removeClass("d-none"); - }else{ + } else { $("#setting_peer_alert").addClass("d-none"); } }); @@ -1172,8 +1283,8 @@ $("#peer_private_key_textbox").on("change",function(){ /** * When save peer setting button got clicked */ -$("#save_peer_setting").on("click",function (){ - $(this).attr("disabled","disabled"); +$("#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"); @@ -1185,15 +1296,15 @@ $("#save_peer_setting").on("click",function (){ let $peer_keep_alive = $("#peer_keep_alive"); if ($peer_DNS_textbox.val() !== "" && - $peer_allowed_ip_textbox.val() !== "" && $peer_endpoint_allowed_ips.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")); + data_list.forEach((ele) => ele.attr("disabled", "disabled")); $.ajax({ method: "POST", - url: "/save_peer_setting/"+conf_id, - headers:{ + url: "/save_peer_setting/" + conf_id, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ @@ -1207,10 +1318,10 @@ $("#save_peer_setting").on("click",function (){ keep_alive: $peer_keep_alive.val(), preshared_key: $peer_preshared_key_textbox.val() }), - success: function (response){ - if (response.status === "failed"){ + success: function(response) { + if (response.status === "failed") { $("#setting_peer_alert").html(response.msg).removeClass("d-none"); - }else{ + } else { window.configurations.settingModal().toggle(); window.configurations.loadPeers($('#search_peer_textbox').val()); $('#alertToast').toast('show'); @@ -1220,7 +1331,7 @@ $("#save_peer_setting").on("click",function (){ data_list.forEach((ele) => ele.removeAttr("disabled")); } }); - }else{ + } else { $("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $("#save_peer_setting").removeAttr("disabled").html("Save"); } @@ -1229,11 +1340,11 @@ $("#save_peer_setting").on("click",function (){ /** * Toggle show or hide for the private key textbox in the setting modal */ -$(".peer_private_key_textbox_switch").on("click",function (){ +$(".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); + 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); }); @@ -1243,18 +1354,18 @@ $(".peer_private_key_textbox_switch").on("click",function (){ * =========== */ -let typingTimer; // Timeout object +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 () { +$('#search_peer_textbox').on('keyup', function() { clearTimeout(typingTimer); typingTimer = setTimeout(() => { window.configurations.loadPeers($(this).val()); }, doneTypingInterval); -}).on('keydown', function () { +}).on('keydown', function() { clearTimeout(typingTimer); }); @@ -1265,13 +1376,13 @@ $('#search_peer_textbox').on('keyup', function () { /** * Handle when sort peers changed */ -$body.on("change", "#sort_by_dropdown", function (){ +$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"}, + method: "POST", + data: JSON.stringify({ 'sort': $("#sort_by_dropdown option:selected").val() }), + headers: { "Content-Type": "application/json" }, url: "/update_dashboard_sort", - success: function (){ + success: function() { window.configurations.loadPeers($('#search_peer_textbox').val()); } }); @@ -1280,16 +1391,16 @@ $body.on("change", "#sort_by_dropdown", function (){ /** * Handle copy public key */ -$body.on("mouseenter", ".key", function(){ +$body.on("mouseenter", ".key", function() { let label = $(this).parent().siblings().children()[1]; label.style.opacity = "100"; -}).on("mouseout", ".key", function(){ +}).on("mouseout", ".key", function() { let label = $(this).parent().siblings().children()[1]; label.style.opacity = "0"; - setTimeout(function (){ + setTimeout(function() { label.innerHTML = "CLICK TO COPY"; - },200); -}).on("click", ".key", function(){ + }, 200); +}).on("click", ".key", function() { let label = $(this).parent().siblings().children()[1]; window.configurations.copyToClipboard($(this)); label.innerHTML = "COPIED!"; @@ -1298,12 +1409,12 @@ $body.on("mouseenter", ".key", function(){ /** * Handle when interval button got clicked */ -$body.on("click", ".update_interval", function(){ +$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)){ + if ([5000, 10000, 30000, 60000].includes(interval)) { window.configurations.updateRefreshInterval(interval); } @@ -1322,28 +1433,28 @@ $body.on("click", ".update_interval", function(){ /** * Handle when refresh button got clicked */ -$body.on("click", ".refresh", function (){ +$body.on("click", ".refresh", function() { window.configurations.loadPeers($('#search_peer_textbox').val()); }); /** * Handle when display mode button got clicked */ -$body.on("click", ".display_mode", function(){ +$body.on("click", ".display_mode", function() { $(".display-btn-group button").removeClass("active"); $(this).addClass("active"); window.localStorage.setItem("displayMode", $(this).data("display-mode")); window.configurations.updateDisplayMode(); - if ($(this).data("display-mode") === "list"){ - Array($(".peer_list").children()).forEach(function(child){ + if ($(this).data("display-mode") === "list") { + Array($(".peer_list").children()).forEach(function(child) { $(child).removeClass().addClass("col-12"); }); window.configurations.showToast("Displaying as List"); - }else{ - Array($(".peer_list").children()).forEach(function(child){ + } else { + Array($(".peer_list").children()).forEach(function(child) { $(child).removeClass().addClass("col-sm-6 col-lg-4"); - }); - window.configurations.showToast("Displaying as Grids"); + }); + window.configurations.showToast("Displaying as Grids"); } }); @@ -1354,35 +1465,35 @@ $body.on("click", ".display_mode", function(){ * ================= */ let $setting_btn_menu = $(".setting_btn_menu"); -$setting_btn_menu.css("top", ($setting_btn_menu.height() + 54)*(-1)); +$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.on("click", function() { + if ($setting_btn_menu.hasClass("show")) { $setting_btn_menu.removeClass("showing"); - setTimeout(function(){ + setTimeout(function() { $setting_btn_menu.removeClass("show"); }, 201); - }else{ - $setting_btn_menu.addClass("show"); - setTimeout(function(){ - $setting_btn_menu.addClass("showing"); - },10); + } 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)){ +$("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(){ + setTimeout(function() { $setting_btn_menu.removeClass("show"); }, 310); } @@ -1405,10 +1516,9 @@ $("#delete_peers_by_bulk_btn").on("click", () => { $delete_bulk_modal_list.html(''); peers.forEach((peer) => { let name; - if (peer.name === "") { name = "Untitled Peer"; } - else { name = peer.name; } + if (peer.name === "") { name = "Untitled Peer"; } else { name = peer.name; } $delete_bulk_modal_list.append(''+name+'
'+peer.id+'
'); + peer.id + '" data-name="' + name + '">' + name + '
' + peer.id + ''); }); window.configurations.deleteBulkModal().toggle(); }); @@ -1416,9 +1526,9 @@ $("#delete_peers_by_bulk_btn").on("click", () => { /** * When the item or tag of delete peers by bulk got clicked */ -$body.on("click", ".delete-bulk-peer-item", function(){ +$body.on("click", ".delete-bulk-peer-item", function() { window.configurations.toggleDeleteByBulkIP($(this)); -}).on("click", ".delete-peer-bulk-badge", function(){ +}).on("click", ".delete-peer-bulk-badge", function() { window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='" + $(this).data("id") + "']")); }); @@ -1428,10 +1538,10 @@ 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()){ +let changeObserver = new MutationObserver(function() { + if ($selected_peer_list.hasChildNodes()) { $("#confirm_delete_bulk_peers").removeAttr("disabled"); - }else{ + } else { $("#confirm_delete_bulk_peers").attr("disabled", "disabled"); } }); @@ -1446,19 +1556,19 @@ 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(){ +$("#confirm_delete_bulk_peers").on("click", function() { let btn = $(this); - if (confirm_delete_bulk_peers_interval !== undefined){ + if (confirm_delete_bulk_peers_interval !== undefined) { clearInterval(confirm_delete_bulk_peers_interval); confirm_delete_bulk_peers_interval = undefined; btn.html("Delete"); - }else{ + } else { let timer = 5; btn.html(`Deleting in ${timer} secs... Click to cancel`); - confirm_delete_bulk_peers_interval = setInterval(function(){ + confirm_delete_bulk_peers_interval = setInterval(function() { timer -= 1; btn.html(`Deleting in ${timer} secs... Click to cancel`); - if (timer === 0){ + if (timer === 0) { btn.html(`Deleting...`); btn.attr("disabled", "disabled"); let ips = []; @@ -1474,23 +1584,23 @@ $("#confirm_delete_bulk_peers").on("click", function(){ /** * Select all peers to delete */ -$("#select_all_delete_bulk_peers").on("click", function(){ - $(".delete-bulk-peer-item").each(function(){ - if (!$(this).hasClass("active")) { - window.configurations.toggleDeleteByBulkIP($(this)); - } - }); +$("#select_all_delete_bulk_peers").on("click", function() { + $(".delete-bulk-peer-item").each(function() { + if (!$(this).hasClass("active")) { + window.configurations.toggleDeleteByBulkIP($(this)); + } + }); }); /** * When delete peers by bulk window is hidden */ -$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", function(){ - $(".delete-bulk-peer-item").each(function(){ - if ($(this).hasClass("active")) { - window.configurations.toggleDeleteByBulkIP($(this)); - } - }); +$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", function() { + $(".delete-bulk-peer-item").each(function() { + if ($(this).hasClass("active")) { + window.configurations.toggleDeleteByBulkIP($(this)); + } + }); }); /** @@ -1502,13 +1612,13 @@ $(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", functi /** * When the download peers button got clicked */ -$body.on("click", ".btn-download-peer", function(e){ +$body.on("click", ".btn-download-peer", function(e) { e.preventDefault(); let link = $(this).attr("href"); $.ajax({ "url": link, "method": "GET", - success: function(res){ + success: function(res) { window.configurations.downloadOneConfig(res); } }); @@ -1517,15 +1627,15 @@ $body.on("click", ".btn-download-peer", function(e){ /** * When the download all peers got clicked */ -$("#download_all_peers").on("click", function(){ +$("#download_all_peers").on("click", function() { $.ajax({ "url": `/download_all/${window.configurations.getConfigurationName()}`, "method": "GET", - success: function(res){ - if (res.peers.length > 0){ - window.wireguard.generateZipFiles(res); - window.configurations.showToast("Peers' zip file download successful!"); - }else{ + success: function(res) { + if (res.peers.length > 0) { + window.wireguard.generateZipFiles(res); + window.configurations.showToast("Peers' zip file download successful!"); + } else { window.configurations.showToast("Oops! There are no peer can be download."); } } diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index 02e8a5e8..f75e42da 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1,23 +1 @@ -(function(){let peers=[];let configuration_name;let configuration_interval;let configuration_timeout=window.localStorage.getItem("configurationTimeout");if(configuration_timeout===null||!["5000","10000","30000","60000"].includes(configuration_timeout)){window.localStorage.setItem("configurationTimeout","10000");configuration_timeout=window.localStorage.getItem("configurationTimeout")}document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active");let display_mode=window.localStorage.getItem("displayMode");if(display_mode===null||!["grid","list"].includes(display_mode)){window.localStorage.setItem("displayMode","grid");display_mode="grid"}document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active");let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let chartUnit=window.localStorage.chartUnit;let chartUnitAvailable=["GB","MB","KB"];if(chartUnit===null||!chartUnitAvailable.includes(chartUnit)){window.localStorage.setItem("chartUnit","GB");$('.switchUnit[data-unit="GB"]').addClass("active")}else{$(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active")}chartUnit=window.localStorage.getItem("chartUnit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d");const totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:false,showScale:false,responsive:false,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%");totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width();totalDataUsageChartObj.resize();$(window).on("resize",function(){totalDataUsageChartObj.resize()});$(".fullScreen").on("click",function(){let $chartContainer=$(".chartContainer");if($chartContainer.hasClass("fullScreen")){$(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen");$chartContainer.removeClass("fullScreen")}else{$(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit");$chartContainer.addClass("fullScreen")}totalDataUsageChartObj.resize()});let mul=1;$(".switchUnit").on("click",function(){$(".switchUnit").removeClass("active");$(this).addClass("active");if($(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":if(chartUnit==="MB"){mul=1/1024}if(chartUnit==="KB"){mul=1/1048576}break;case"MB":if(chartUnit==="GB"){mul=1024}if(chartUnit==="KB"){mul=1/1024}break;case"KB":if(chartUnit==="GB"){mul=1048576}if(chartUnit==="MB"){mul=1024}break;default:break}window.localStorage.setItem("chartUnit",$(this).data("unit"));chartUnit=$(this).data("unit");totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul);totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul);totalDataUsageChartObj.update()}});function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active");$(`.sb-${configuration_name}-url`).addClass("active")}let firstLoading=true;$(".nav-conf-link").on("click",function(e){e.preventDefault();if(configuration_name!==$(this).data("conf-id")){firstLoading=true;$("#config_body").addClass("firstLoading");configuration_name=$(this).data("conf-id");if(loadPeers($("#search_peer_textbox").val())){setActiveConfigurationName();window.history.pushState(null,null,`/configuration/${configuration_name}`);$("title").text(`${configuration_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}}});function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name;$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let mode=display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
-
${peer.name===""?"Untitled":peer.name}
-
-
`;let peer_transfer=`
-

- ${roundN(peer.total_receive+total_r,4)} GB -

-

- ${roundN(peer.total_sent+total_s,4)} GB -

-
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` -
-
-
- - - `;if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(configuration_interval===undefined){setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(interval){configuration_timeout=interval;window.localStorage.setItem("configurationTimeout",configuration_timeout.toString());removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){let $lockGlyph="bi-lock-fill";let $unlockGlyph="bi-unlock-fill";if($(this).children().hasClass($lockGlyph)){$(this).children().removeClass($lockGlyph).addClass($unlockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")}else{$(this).children().removeClass($unlockGlyph).addClass($lockGlyph);$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$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([5e3,1e4,3e4,6e4].includes(interval)){window.configurations.updateRefreshInterval(interval)}});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");window.localStorage.setItem("displayMode",$(this).data("display-mode"));window.configurations.updateDisplayMode();if($(this).data("display-mode")==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file +!function(){let configuration_name,configuration_interval,configuration_timeout=window.localStorage.getItem("configurationTimeout");null!==configuration_timeout&&["5000","10000","30000","60000"].includes(configuration_timeout)||(window.localStorage.setItem("configurationTimeout","10000"),configuration_timeout=window.localStorage.getItem("configurationTimeout")),document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active");let display_mode=window.localStorage.getItem("displayMode");null!==display_mode&&["grid","list"].includes(display_mode)||(window.localStorage.setItem("displayMode","grid"),display_mode="grid"),document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active")),document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active");let $progress_bar=$(".progress-bar"),bootstrapModalConfig={keyboard:!1,backdrop:"static"},addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig),deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig),ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig),qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig),settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig),deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip(),$("[data-toggle='popover']").popover();let chartUnit=window.localStorage.chartUnit,chartUnitAvailable;null!==chartUnit&&["GB","MB","KB"].includes(chartUnit)?$(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active"):(window.localStorage.setItem("chartUnit","GB"),$('.switchUnit[data-unit="GB"]').addClass("active")),chartUnit=window.localStorage.getItem("chartUnit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d"),totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:!1,showScale:!1,responsive:!1,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%"),totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width(),totalDataUsageChartObj.resize(),$(window).on("resize",(function(){totalDataUsageChartObj.resize()})),$(".fullScreen").on("click",(function(){let $chartContainer=$(".chartContainer");$chartContainer.hasClass("fullScreen")?($(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"),$chartContainer.removeClass("fullScreen")):($(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit"),$chartContainer.addClass("fullScreen")),totalDataUsageChartObj.resize()}));let mul=1;function configurationAlert(response){if(""===response.listen_port&&"stopped"===response.status){let configAlert=document.createElement("div");configAlert.classList.add("alert"),configAlert.classList.add("alert-warning"),configAlert.setAttribute("role","alert"),configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.",document.querySelector("#config_info_alert").appendChild(configAlert)}if("N/A"===response.conf_address){let configAlert=document.createElement("div");configAlert.classList.add("alert"),configAlert.classList.add("alert-warning"),configAlert.setAttribute("role","alert"),configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.",document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active"),$(`.sb-${configuration_name}-url`).addClass("active")}$(".switchUnit").on("click",(function(){if($(".switchUnit").removeClass("active"),$(this).addClass("active"),$(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":"MB"===chartUnit&&(mul=1/1024),"KB"===chartUnit&&(mul=1/1048576);break;case"MB":"GB"===chartUnit&&(mul=1024),"KB"===chartUnit&&(mul=1/1024);break;case"KB":"GB"===chartUnit&&(mul=1048576),"MB"===chartUnit&&(mul=1024)}window.localStorage.setItem("chartUnit",$(this).data("unit")),chartUnit=$(this).data("unit"),totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul),totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul),totalDataUsageChartObj.update()}}));let firstLoading=!0;function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if("checked"===response.checked?$conf_status_btn.innerHTML=` ON`:$conf_status_btn.innerHTML=` OFF`,response.running_peer>0){let d,time=(new Date).toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});if(totalDataUsageChartObj.data.labels.push(`${time}`),0===totalDataUsageChartObj.data.datasets[0].data.length)totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2],totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1],totalDataUsageChartObj.data.datasets[0].data.push(0),totalDataUsageChartObj.data.datasets[1].data.push(0);else{50===totalDataUsageChartObj.data.datasets[0].data.length&&50===totalDataUsageChartObj.data.datasets[1].data.length&&(totalDataUsageChartObj.data.labels.shift(),totalDataUsageChartObj.data.datasets[0].data.shift(),totalDataUsageChartObj.data.datasets[1].data.shift());let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData,newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData,k=0;k="MB"===chartUnit?1024:"KB"===chartUnit?1048576:1,totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k),totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k),totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1],totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name,$conf_status_btn.classList.remove("info_loading"),document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected")),document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected"),document.querySelector("#conf_status").innerHTML=`${response.status}`,document.querySelector("#conf_connected_peers").innerHTML=response.running_peer,document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`,document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`,document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`,document.querySelector("#conf_public_key").innerHTML=response.public_key,document.querySelector("#conf_listen_port").innerHTML=""===response.listen_port?"N/A":response.listen_port,document.querySelector("#conf_address").innerHTML=response.conf_address,document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(0===response.peer_data.length)document.querySelector(".peer_list").innerHTML='

Oops! No peers found ‘︿’

';else{let mode="list"===display_mode?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach((function(peer){let total_r=0,total_s=0;total_r+=peer.cumu_receive,total_s+=peer.cumu_sent;let spliter='
',peer_name=`
\n
${""===peer.name?"Untitled":peer.name}
\n
\n
`,peer_transfer=`
\n

\n ${roundN(peer.total_receive+total_r,4)} GB\n

\n

\n ${roundN(peer.total_sent+total_s,4)} GB\n

\n
`,peer_key='
PEERCLICK TO COPY
'+peer.id+"
",peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
",peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
",peer_endpoint='
END POINT
'+peer.endpoint+"
",peer_control=`\n
\n
\n
\n \n \n `;""!==peer.private_key&&(peer_control+=''),peer_control+="
";let html='
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
";result+=html})),document.querySelector(".peer_list").innerHTML=result,void 0===configuration_interval&&setConfigurationInterval()}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key"),data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid"))if(""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=configuration_name,keys=[];for(let i=0;i<$new_add_amount.val();i++)keys.push(window.wireguard.generateKeypair());$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.val()}),success:function(response){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast($new_add_amount.val()+" peers added successful!"),window.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";else $add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Add"}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if("true"!==response){if(window.configurations.deleteModal()._isShown&&($("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none"),$("#delete_peer").removeAttr("disabled").html("Delete")),window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none"),$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else window.configurations.deleteModal()._isShown&&window.configurations.deleteModal().toggle(),window.configurations.deleteBulkModal()._isShown&&($("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"),$("#selected_peer_list").html(""),$(".delete-bulk-peer-item.active").removeClass("active"),window.configurations.deleteBulkModal().toggle()),window.configurations.loadPeers($("#search_peer_textbox").val()),$("#alertToast").toast("show"),$("#alertToast .toast-body").html("Peer deleted!"),$("#delete_peer").removeAttr("disabled").html("Delete")}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active")),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show")),document.querySelector("#right_body").classList.add("no-responding"),document.querySelector(".navbar").classList.add("no-responding"),document.querySelector(".no-response .container h4").innerHTML=message}),10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show")),document.querySelector("#right_body").classList.remove("no-responding"),document.querySelector(".navbar").classList.remove("no-responding"),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))}),1010)}function setConfigurationInterval(){configuration_interval=setInterval((function(){loadPeers($("#search_peer_textbox").val())}),configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%"),setTimeout((function(){stillLoadingProgressBar()}),300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%"),setTimeout((function(){$progress_bar.css("opacity","0")}),250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}$(".nav-conf-link").on("click",(function(e){e.preventDefault(),configuration_name!==$(this).data("conf-id")&&(firstLoading=!0,$("#config_body").addClass("firstLoading"),configuration_name=$(this).data("conf-id"),loadPeers($("#search_peer_textbox").val())&&(setActiveConfigurationName(),window.history.pushState(null,null,`/configuration/${configuration_name}`),$("title").text(`${configuration_name} | WGDashboard`),totalDataUsageChartObj.data.labels=[],totalDataUsageChartObj.data.datasets[0].data=[],totalDataUsageChartObj.data.datasets[1].data=[],totalDataUsageChartObj.update()))}));let time=0,count=0,d1=new Date;function loadPeers(searchString){d1=new Date;let good=!0;return $.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done((function(response){console.log(response),parsePeers(response)})).fail((function(){noResponding(),good=!1})),good}function parsePeers(response){if(response.status){let d2,seconds=new Date-d1;time+=seconds,count+=1,window.console.log(`Average time: ${time/count}ms`),$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`),removeNoResponding(),peers=response.data.peer_data,configurationAlert(response.data),configurationHeader(response.data),configurationPeers(response.data),$(".dot.dot-running").attr("title","Peer Connected").tooltip(),$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(),$("i[data-toggle='tooltip']").tooltip(),$("#configuration_name").text(configuration_name),firstLoading&&(firstLoading=!1,$("#config_body").removeClass("firstLoading"))}else noResponding(response.message),removeConfigurationInterval()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey,document.querySelector("#public_key").value=keys.publicKey,document.querySelector("#add_peer_alert").classList.add("d-none"),document.querySelector("#re_generate_key i").classList.remove("rotating"),document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show"),$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(interval){configuration_timeout=interval,window.localStorage.setItem("configurationTimeout",configuration_timeout.toString()),removeConfigurationInterval(),setConfigurationInterval(),showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`))}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob),link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list"),id=element.data("id"),name=""===element.data("name")?"Untitled Peer":element.data("name");element.hasClass("active")?(element.removeClass("active"),$("#selected_peer_list .badge[data-id='"+id+"']").remove()):(element.addClass("active"),$selected_peer_list.append(''+name+" - "+id+""))}function copyToClipboard(element){let $temp=$("");$body.append($temp),$temp.val($(element).text()).trigger("select"),document.execCommand("copy"),$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done((function(res){if(!0===res.status){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="",document.querySelector("#allowed_ips").value=available_ips[0],available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else document.querySelector("#allowed_ips").value=res.message,document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}))}window.configurations={addModal:()=>addModal,deleteBulkModal:()=>deleteBulkModal,deleteModal:()=>deleteModal,ipModal:()=>ipModal,qrcodeModal:()=>qrcodeModal,settingModal:()=>settingModal,configurationTimeout:()=>configuration_timeout,updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>configuration_name,setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>cleanIp(val),startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}}();let $body=$("body"),available_ips=[],$add_peer=document.getElementById("save_peer"),typingTimer;document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()}),document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");selector.contains(event.target)&&(selector.style.display="none",document.querySelector("div[role=status]").style.display="inline-block",location.replace(`/switch/${selector.getAttribute("id")}`))}),document.querySelector("#private_key").addEventListener("change",event=>{let publicKey=document.querySelector("#public_key");44===event.target.value.length?(publicKey.value=window.wireguard.generatePublicKey(event.target.value),publicKey.setAttribute("disabled","disabled")):(publicKey.attributes.removeNamedItem("disabled"),publicKey.value="")}),$("#add_modal").on("show.bs.modal",(function(){window.configurations.generateKeyPair(),window.configurations.getAvailableIps()})).on("hide.bs.modal",(function(){$("#allowed_ips_indicator").html("")})),$("#re_generate_key").on("click",(function(){$("#public_key").attr("disabled","disabled"),$("#re_generate_key i").addClass("rotating"),window.configurations.generateKeyPair()})),$("#allowed_ips").on("keyup",(function(){let s=window.configurations.cleanIp($(this).val());s=s.split(","),available_ips.includes(s[s.length-1])?$("#allowed_ips_indicator").removeClass().addClass("text-success").html(''):$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')})),$("#peer_name_textbox").on("keyup",(function(){$(".peer_name").html($(this).val())})),$add_peer.addEventListener("click",(function(){let $bulk_add;if($("#bulk_add").prop("checked"))$("#new_add_amount").hasClass("is-invalid")||window.configurations.addPeersByBulk();else{let $public_key=$("#public_key"),$private_key=$("#private_key"),$allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_name=$("#new_add_name"),$new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key");if($add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML="Adding...",""!==$allowed_ips.val()&&""!==$public_key.val()&&""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=window.configurations.getConfigurationName(),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){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast("Add peer successful!"),window.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"}})),$("#new_add_amount").on("keyup",(function(){let $bulk_amount_validation=$("#bulk_amount_validation");$(this).val().length>0?isNaN($(this).val())?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter a valid integer")):$(this).val()>available_ips.length?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`)):$(this).val()<1?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter at least 1 or more.")):$(this).removeClass("is-invalid").addClass("is-valid"):$(this).removeClass("is-invalid").removeClass("is-valid")})),$("#bulk_add").on("change",(function(){let hide=$(".non-bulk"),amount=$("#new_add_amount");if(!0===$(this).prop("checked")){for(let i=0;i{document.querySelector("#add_modal").classList.add("ip_modal_open")}).on("hidden.bs.modal",()=>{document.querySelector("#add_modal").classList.remove("ip_modal_open");let ips=[],$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=>window.configurations.triggerIp(ele))}),$body.on("click",".available-ip-badge",(function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active"),$(this).remove()})),$body.on("click",".available-ip-item",(function(){window.configurations.triggerIp($(this).data("ip"))})),$("#search_available_ip").on("click",(function(){window.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{window.configurations.ipModal().toggle();let ips=[],$selected_ip_list;$("#selected_ip_list").children().each((function(){ips.push($(this).data("ip"))})),$("#allowed_ips").val(ips.join(", ")),ips.forEach(ele=>window.configurations.triggerIp(ele))}),$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),window.configurations.qrcodeModal().toggle()}))})),$body.on("click",".btn-delete-peer",(function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id),window.configurations.deleteModal().toggle()})),$body.on("click",".btn-lock-peer",(function(){let $lockGlyph="bi-lock-fill",$unlockGlyph="bi-unlock-fill";$(this).children().hasClass($lockGlyph)?($(this).children().removeClass($lockGlyph).addClass($unlockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")):($(this).children().removeClass($unlockGlyph).addClass($lockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show"))})),$("#delete_peer").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Deleting...");let config=window.configurations.getConfigurationName(),peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)})),$body.on("click",".btn-setting-peer",(function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id),$.ajax({method:"POST",url:"/get_peer_data/"+window.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),window.configurations.settingModal().toggle(),window.configurations.endProgressBar()}})})),$("#setting_modal").on("hidden.bs.modal",(function(){$("#setting_peer_alert").addClass("d-none")})),$("#peer_private_key_textbox").on("change",(function(){let $save_peer_setting=$("#save_peer_setting");$(this).val().length>0&&$.ajax({url:"/check_key_match/"+window.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){"failed"===res.status?$("#setting_peer_alert").html(res.status).removeClass("d-none"):$("#setting_peer_alert").addClass("d-none")}))})),$("#save_peer_setting").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Saving...");let $peer_DNS_textbox=$("#peer_DNS_textbox"),$peer_allowed_ip_textbox=$("#peer_allowed_ip_textbox"),$peer_endpoint_allowed_ips=$("#peer_endpoint_allowed_ips"),$peer_name_textbox=$("#peer_name_textbox"),$peer_private_key_textbox=$("#peer_private_key_textbox"),$peer_preshared_key_textbox=$("#peer_preshared_key_textbox"),$peer_mtu=$("#peer_mtu"),$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"),conf_id=$(this).attr("conf_id"),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){"failed"===response.status?$("#setting_peer_alert").html(response.msg).removeClass("d-none"):(window.configurations.settingModal().toggle(),window.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")})),$(".peer_private_key_textbox_switch").on("click",(function(){let $peer_private_key_textbox=$("#peer_private_key_textbox"),mode="password"===$peer_private_key_textbox.attr("type")?"text":"password",icon="password"===$peer_private_key_textbox.attr("type")?"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)}));let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",(function(){clearTimeout(typingTimer),typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)})).on("keydown",(function(){clearTimeout(typingTimer)})),$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})})),$body.on("mouseenter",".key",(function(){let label;$(this).parent().siblings().children()[1].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];window.configurations.copyToClipboard($(this)),label.innerHTML="COPIED!"})),$body.on("click",".update_interval",(function(){let _new;$(".interval-btn-group button").removeClass("active"),$(this).addClass("active");let interval=$(this).data("refresh-interval");[5e3,1e4,3e4,6e4].includes(interval)&&window.configurations.updateRefreshInterval(interval)})),$body.on("click",".refresh",(function(){window.configurations.loadPeers($("#search_peer_textbox").val())})),$body.on("click",".display_mode",(function(){$(".display-btn-group button").removeClass("active"),$(this).addClass("active"),window.localStorage.setItem("displayMode",$(this).data("display-mode")),window.configurations.updateDisplayMode(),"list"===$(this).data("display-mode")?(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-12")})),window.configurations.showToast("Displaying as List")):(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")})),window.configurations.showToast("Displaying as Grids"))}));let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",-1*($setting_btn_menu.height()+54));let $setting_btn=$(".setting_btn");$setting_btn.on("click",(function(){$setting_btn_menu.hasClass("show")?($setting_btn_menu.removeClass("showing"),setTimeout((function(){$setting_btn_menu.removeClass("show")}),201)):($setting_btn_menu.addClass("show"),setTimeout((function(){$setting_btn_menu.addClass("showing")}),10))})),$("html").on("click",(function(r){document.querySelector(".setting_btn")!==r.target&&(document.querySelector(".setting_btn").contains(r.target)||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_btn").on("click",()=>{let $delete_bulk_modal_list=$("#delete_bulk_modal .list-group");$delete_bulk_modal_list.html(""),peers.forEach(peer=>{let name;name=""===peer.name?"Untitled Peer":peer.name,$delete_bulk_modal_list.append(''+name+"
"+peer.id+"
")}),window.configurations.deleteBulkModal().toggle()}),$body.on("click",".delete-bulk-peer-item",(function(){window.configurations.toggleDeleteByBulkIP($(this))})).on("click",".delete-peer-bulk-badge",(function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))}));let $selected_peer_list=document.getElementById("selected_peer_list"),changeObserver=new MutationObserver((function(){$selected_peer_list.hasChildNodes()?$("#confirm_delete_bulk_peers").removeAttr("disabled"):$("#confirm_delete_bulk_peers").attr("disabled","disabled")})),confirm_delete_bulk_peers_interval;changeObserver.observe($selected_peer_list,{attributes:!0,childList:!0,characterData:!0}),$("#confirm_delete_bulk_peers").on("click",(function(){let btn=$(this);if(void 0!==confirm_delete_bulk_peers_interval)clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0,btn.html("Delete");else{let timer=5;btn.html(`Deleting in ${timer} secs... Click to cancel`),confirm_delete_bulk_peers_interval=setInterval((function(){if(timer-=1,btn.html(`Deleting in ${timer} secs... Click to cancel`),0===timer){btn.html("Deleting..."),btn.attr("disabled","disabled");let ips=[];$selected_peer_list.childNodes.forEach(ele=>ips.push(ele.dataset.id)),window.configurations.deletePeers(window.configurations.getConfigurationName(),ips),clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0}}),1e3)}})),$("#select_all_delete_bulk_peers").on("click",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")||window.configurations.toggleDeleteByBulkIP($(this))}))})),$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")&&window.configurations.toggleDeleteByBulkIP($(this))}))})),$body.on("click",".btn-download-peer",(function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})})),$("#download_all_peers").on("click",(function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){res.peers.length>0?(window.wireguard.generateZipFiles(res),window.configurations.showToast("Peers' zip file download successful!")):window.configurations.showToast("Oops! There are no peer can be download.")}})})); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index 2f659a47..70c5b67d 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -27,9 +27,10 @@
SWITCH
-
-
@@ -424,8 +425,8 @@
-
- +
+
+{% include "tools.html" %} + +{% include "footer.html" %} + + \ No newline at end of file diff --git a/src/templates/signin.html b/src/templates/signin.html index 16e5e1bf..0a492858 100644 --- a/src/templates/signin.html +++ b/src/templates/signin.html @@ -67,7 +67,11 @@ if (res.status === true){ const urlParams = new URLSearchParams(window.location.search); if (urlParams.get("redirect")){ - window.location.replace(urlParams.get("redirect")) + if (document.URL.substring(0, 5) == "http:"){ + window.location.replace(`http://${urlParams.get("redirect")}`) + }else if (document.URL.substring(0, 5) == "https"){ + window.location.replace(`https://${urlParams.get("redirect")}`) + } }else{ window.location.replace("/"); } From 46efe2b8ddf67cc8b6dad8f80e45a41db03dfadd Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Thu, 24 Mar 2022 02:10:52 -0400 Subject: [PATCH 010/214] Finished developing add config --- src/api.py | 95 ++++++++++++++- src/dashboard.py | 107 +++++++++-------- src/static/css/dashboard.css | 15 +++ src/static/js/index.js | 224 ++++++++++++++++++++++++++++------- src/templates/index.html | 70 +++++------ src/util.py | 5 +- 6 files changed, 381 insertions(+), 135 deletions(-) diff --git a/src/api.py b/src/api.py index 22696d77..ca15d701 100644 --- a/src/api.py +++ b/src/api.py @@ -1,2 +1,95 @@ -from dashboard import request, jsonify, app +import ipaddress, subprocess, datetime, os, util +from util import * +notEnoughParameter = {"status": False, "reason": "Please provide all required parameters."} +good = {"status": True, "reason": ""} +def togglePeerAccess(data, g): + checkUnlock = g.cur.execute(f"SELECT * FROM {data['config']} WHERE id='{data['peerID']}'").fetchone() + if checkUnlock: + moveUnlockToLock = g.cur.execute(f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + print(g.cur.rowcount) + print(util.deletePeers(data['config'], [data['peerID']], g.cur, g.db)) + else: + moveLockToUnlock = g.cur.execute(f"SELECT * FROM {data['config']}_restrict_access WHERE id='{data['peerID']}'").fetchone() + try: + if len(moveLockToUnlock[-1]) == 0: + status = subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", + shell=True, stderr=subprocess.STDOUT) + else: + now = str(datetime.datetime.now().strftime("%m%d%Y%H%M%S")) + f_name = now + "_tmp_psk.txt" + f = open(f_name, "w+") + f.write(moveLockToUnlock[-1]) + f.close() + subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", + shell=True, stderr=subprocess.STDOUT) + os.remove(f_name) + status = subprocess.check_output(f"wg-quick save {data['config']}", shell=True, stderr=subprocess.STDOUT) + g.cur.execute(f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + g.cur.execute(f"DELETE FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + + except subprocess.CalledProcessError as exc: + return {"status": False, "reason": str(exc.output.strip())} + return good + + + +class addConfiguration: + def AddressCheck(data): + address = data['address'] + address = address.replace(" ", "") + address = address.split(',') + amount = 0 + for i in address: + try: + ips = ipaddress.ip_network(i, False) + amount += ips.num_addresses + except ValueError as e: + return {"status": False, "reason": str(e)} + if amount >= 1: + return {"status": True, "reason":"", "data":f"Total of {amount} IPs"} + else: + return {"status": True, "reason":"", "data":f"0 available IPs"} + + def PortCheck(data, configs): + port = data['port'] + if (not port.isdigit()) or int(port) < 1 or int(port) > 65535: + return {"status": False, "reason": f"Invalid port."} + for i in configs: + if i['port'] == port: + return {"status": False, "reason": f"{port} used by {i['conf']}."} + return good + + def NameCheck(data, configs): + name = data['name'] + name = name.replace(" ", "") + for i in configs: + if name == i['conf']: + return {"status": False, "reason":f"{name} already existed."} + return good + + def addConfiguration(data, configs, WG_CONF_PATH): + output = ["[Interface]", "SaveConfig = true"] + required = ['addConfigurationPrivateKey', 'addConfigurationListenPort', + 'addConfigurationAddress', 'addConfigurationPreUp', 'addConfigurationPreDown', + 'addConfigurationPostUp', 'addConfigurationPostDown'] + for i in required: + e = data[i] + if len(e) != 0: + key = i.replace("addConfiguration", "") + o = f"{key} = {e}" + output.append(o) + name = data['addConfigurationName'] + illegal_filename = [" ",".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", "com3", + "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", + "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"] + for i in illegal_filename: + name = name.replace(i, "") + try: + newFile = open(f"{WG_CONF_PATH}/{name}.conf", "w+") + newFile.write("\n".join(output)) + except Exception as e: + return {"status": False, "reason":str(e)} + return {"status": True, "reason":"", "data": name} \ No newline at end of file diff --git a/src/dashboard.py b/src/dashboard.py index c934d0e5..33671b95 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -31,7 +31,7 @@ from flask_socketio import SocketIO from util import * # Dashboard Version -DASHBOARD_VERSION = 'v3.0.5' +DASHBOARD_VERSION = 'v3.1' # WireGuard's configuration path WG_CONF_PATH = None @@ -58,6 +58,7 @@ socketio = SocketIO(app) # TODO: use class and object oriented programming + def connect_db(): """ Connect to the database @@ -521,7 +522,7 @@ def get_conf_list(): ) """ g.cur.execute(create_table) - temp = {"conf": i, "status": get_conf_status(i), "public_key": get_conf_pub_key(i)} + temp = {"conf": i, "status": get_conf_status(i), "public_key": get_conf_pub_key(i), "port": get_conf_listen_port(i)} if temp['status'] == "running": temp['checked'] = 'checked' else: @@ -731,6 +732,7 @@ def auth(): if password.hexdigest() == config["Account"]["password"] \ and data['username'] == config["Account"]["username"]: session['username'] = data['username'] + session.permanent = True config.clear() return jsonify({"status": True, "msg": ""}) config.clear() @@ -1107,15 +1109,15 @@ def switch(config_name): check = subprocess.check_output("wg-quick down " + config_name, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: - session["switch_msg"] = exc.output.strip().decode("utf-8") - return jsonify({"status": False, "reason":"Can't stop peer"}) + # session["switch_msg"] = exc.output.strip().decode("utf-8") + return jsonify({"status": False, "reason":"Can't stop peer", "message": str(exc.output.strip().decode("utf-8"))}) elif status == "stopped": try: subprocess.check_output("wg-quick up " + config_name, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: - session["switch_msg"] = exc.output.strip().decode("utf-8") - return jsonify({"status": False, "reason":"Can't turn on peer"}) + # session["switch_msg"] = exc.output.strip().decode("utf-8") + return jsonify({"status": False, "reason":"Can't turn on peer", "message": str(exc.output.strip().decode("utf-8"))}) return jsonify({"status": True, "reason":""}) @app.route('/add_peer_bulk/', methods=['POST']) @@ -1534,45 +1536,18 @@ def switch_display_mode(mode): # APIs +import api + + @app.route('/api/togglePeerAccess', methods=['POST']) def togglePeerAccess(): data = request.get_json() returnData = {"status": True, "reason": ""} required = ['peerID', 'config'] if checkJSONAllParameter(required, data): - checkUnlock = g.cur.execute(f"SELECT * FROM {data['config']} WHERE id='{data['peerID']}'").fetchone() - if checkUnlock: - moveUnlockToLock = g.cur.execute(f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") - if g.cur.rowcount == 1: - print(g.cur.rowcount) - print(deletePeers(data['config'], [data['peerID']], g.cur, g.db)) - else: - moveLockToUnlock = g.cur.execute(f"SELECT * FROM {data['config']}_restrict_access WHERE id='{data['peerID']}'").fetchone() - try: - if len(moveLockToUnlock[-1]) == 0: - status = subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", - shell=True, stderr=subprocess.STDOUT) - else: - now = str(datetime.now().strftime("%m%d%Y%H%M%S")) - f_name = now + "_tmp_psk.txt" - f = open(f_name, "w+") - f.write(moveLockToUnlock[-1]) - f.close() - subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", - shell=True, stderr=subprocess.STDOUT) - os.remove(f_name) - status = subprocess.check_output(f"wg-quick save {data['config']}", shell=True, stderr=subprocess.STDOUT) - g.cur.execute(f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") - if g.cur.rowcount == 1: - g.cur.execute(f"DELETE FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") - - except subprocess.CalledProcessError as exc: - returnData["status"] = False - returnData["reason"] = exc.output.strip() + returnData = api.togglePeerAccess(data, g) else: - returnData["status"] = False - returnData["reason"] = "Please provide all required parameters." - + return jsonify(api.notEnoughParameter) return jsonify(returnData) @app.route('/api/addConfigurationAddressCheck', methods=['POST']) @@ -1581,20 +1556,52 @@ def addConfigurationAddressCheck(): returnData = {"status": True, "reason": ""} required = ['address'] if checkJSONAllParameter(required, data): - try: - ips = list(ipaddress.ip_network(data['address'], False).hosts()) - amount = len(ips) - 1 - if amount >= 1: - returnData = {"status": True, "reason":"", "data":f"Total of {amount} IPs"} - else: - returnData = {"status": True, "reason":"", "data":f"0 IP available for peers"} - - except ValueError as e: - returnData = {"status": False, "reason": str(e)} + returnData = api.addConfiguration.AddressCheck(data) else: - returnData = {"status": False, "reason": "Please provide all required parameters."} + return jsonify(api.notEnoughParameter) return jsonify(returnData) - + +@app.route('/api/addConfigurationPortCheck', methods=['POST']) +def addConfigurationPortCheck(): + data = request.get_json() + returnData = {"status": True, "reason": ""} + required = ['port'] + if checkJSONAllParameter(required, data): + returnData = api.addConfiguration.PortCheck(data, get_conf_list()) + else: + return jsonify(api.notEnoughParameter) + return jsonify(returnData) + +@app.route('/api/addConfigurationNameCheck', methods=['POST']) +def addConfigurationNameCheck(): + data = request.get_json() + returnData = {"status": True, "reason": ""} + required = ['name'] + if checkJSONAllParameter(required, data): + returnData = api.addConfiguration.NameCheck(data, get_conf_list()) + else: + return jsonify(api.notEnoughParameter) + return jsonify(returnData) + +@app.route('/api/addConfiguration', methods=["POST"]) +def addConfiguration(): + data = request.get_json() + returnData = {"status": True, "reason": ""} + required = ['addConfigurationPrivateKey', 'addConfigurationName', 'addConfigurationListenPort', + 'addConfigurationAddress', 'addConfigurationPreUp', 'addConfigurationPreDown', + 'addConfigurationPostUp', 'addConfigurationPostDown'] + needFilled = ['addConfigurationPrivateKey', 'addConfigurationName', 'addConfigurationListenPort', + 'addConfigurationAddress'] + if not checkJSONAllParameter(needFilled, data): + return jsonify(api.notEnoughParameter) + for i in required: + if i not in data.keys(): + return jsonify(api.notEnoughParameter) + + returnData = api.addConfiguration.addConfiguration(data, get_conf_list(), WG_CONF_PATH) + return jsonify(returnData) + + """ Dashboard Tools Related diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 1db3560d..39ce07c5 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -772,4 +772,19 @@ pre.index-alert { .input-feedback{ display: none; +} + +#addConfigurationModal label{ + display: flex; + width: 100%; + align-items: center; +} + +#addConfigurationModal label a{ + margin-left: auto !important; +} + +#reGeneratePrivateKey{ + border-top-right-radius: 10px; + border-bottom-right-radius: 10px; } \ No newline at end of file diff --git a/src/static/js/index.js b/src/static/js/index.js index 2f23bf78..67151938 100644 --- a/src/static/js/index.js +++ b/src/static/js/index.js @@ -1,9 +1,22 @@ let numberToast = 0; -let addConfigurationModal = new bootstrap.Modal(document.getElementById('addConfigurationModal'), { +let emptyInputFeedback = "Can't leave empty"; +$('[data-toggle="tooltip"]').tooltip() +let $add_configuration = $("#add_configuration"); + +let addConfigurationModal = $("#addConfigurationModal"); + +addConfigurationModal.modal({ keyboard: false, - backdrop: 'static' + 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"); +}) + function showToast(msg){ $(".toastContainer").append( ` - -
+
+
{%endfor%} @@ -84,53 +82,49 @@
-
+

+					
                         
- +
- +
-
-
-
-
- -
-
- +
- - + + +
- - + + +
- - -
- Please provide a valid city. -
+ + +
- +

N/A

@@ -139,28 +133,26 @@
- +
- +
- +
- +
- - -
diff --git a/src/util.py b/src/util.py index ae6f94aa..c37edd90 100644 --- a/src/util.py +++ b/src/util.py @@ -104,9 +104,10 @@ def deletePeers(config_name, delete_keys, cur, db): def checkJSONAllParameter(required, data): if len(data) == 0: - print("length 0") return False for i in required: if i not in list(data.keys()): return False - return True \ No newline at end of file + return True + + From b9633bbcd6a13381febf9cc22973781853a44dff Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Thu, 24 Mar 2022 20:43:56 -0400 Subject: [PATCH 011/214] Finished implementing add/delete config --- src/api.py | 94 +++++++++++++++++++++--------- src/dashboard.py | 41 ++++++++++--- src/static/css/dashboard.css | 22 +++++-- src/static/css/dashboard.min.css | 2 +- src/static/js/configuration.js | 69 ++++++++++++++++++---- src/static/js/configuration.min.js | 51 +++++++++++++++- src/static/js/index.js | 34 +++++------ src/static/js/index.min.js | 10 ++++ src/templates/configuration.html | 48 ++++++++++----- src/templates/index.html | 18 +++--- src/util.py | 2 +- 11 files changed, 294 insertions(+), 97 deletions(-) create mode 100644 src/static/js/index.min.js diff --git a/src/api.py b/src/api.py index ca15d701..da40482d 100644 --- a/src/api.py +++ b/src/api.py @@ -1,43 +1,49 @@ import ipaddress, subprocess, datetime, os, util from util import * + notEnoughParameter = {"status": False, "reason": "Please provide all required parameters."} good = {"status": True, "reason": ""} + def togglePeerAccess(data, g): checkUnlock = g.cur.execute(f"SELECT * FROM {data['config']} WHERE id='{data['peerID']}'").fetchone() if checkUnlock: - moveUnlockToLock = g.cur.execute(f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") + moveUnlockToLock = g.cur.execute( + f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") if g.cur.rowcount == 1: print(g.cur.rowcount) print(util.deletePeers(data['config'], [data['peerID']], g.cur, g.db)) else: - moveLockToUnlock = g.cur.execute(f"SELECT * FROM {data['config']}_restrict_access WHERE id='{data['peerID']}'").fetchone() + moveLockToUnlock = g.cur.execute( + f"SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'").fetchone() try: if len(moveLockToUnlock[-1]) == 0: - status = subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", - shell=True, stderr=subprocess.STDOUT) + status = subprocess.check_output( + f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", + shell=True, stderr=subprocess.STDOUT) else: now = str(datetime.datetime.now().strftime("%m%d%Y%H%M%S")) f_name = now + "_tmp_psk.txt" f = open(f_name, "w+") f.write(moveLockToUnlock[-1]) f.close() - subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", - shell=True, stderr=subprocess.STDOUT) + subprocess.check_output( + f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", + shell=True, stderr=subprocess.STDOUT) os.remove(f_name) status = subprocess.check_output(f"wg-quick save {data['config']}", shell=True, stderr=subprocess.STDOUT) - g.cur.execute(f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + g.cur.execute( + f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") if g.cur.rowcount == 1: g.cur.execute(f"DELETE FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") - + except subprocess.CalledProcessError as exc: return {"status": False, "reason": str(exc.output.strip())} return good - class addConfiguration: - def AddressCheck(data): + def AddressCheck(self, data): address = data['address'] address = address.replace(" ", "") address = address.split(',') @@ -49,11 +55,11 @@ class addConfiguration: except ValueError as e: return {"status": False, "reason": str(e)} if amount >= 1: - return {"status": True, "reason":"", "data":f"Total of {amount} IPs"} + return {"status": True, "reason": "", "data": f"Total of {amount} IPs"} else: - return {"status": True, "reason":"", "data":f"0 available IPs"} - - def PortCheck(data, configs): + return {"status": True, "reason": "", "data": f"0 available IPs"} + + def PortCheck(self, data, configs): port = data['port'] if (not port.isdigit()) or int(port) < 1 or int(port) > 65535: return {"status": False, "reason": f"Invalid port."} @@ -61,20 +67,28 @@ class addConfiguration: if i['port'] == port: return {"status": False, "reason": f"{port} used by {i['conf']}."} return good - - def NameCheck(data, configs): + + def NameCheck(self, data, configs): name = data['name'] name = name.replace(" ", "") for i in configs: if name == i['conf']: - return {"status": False, "reason":f"{name} already existed."} + return {"status": False, "reason": f"{name} already existed."} + illegal_filename = ["(Space)", " ", ".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", + "com3", + "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", + "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"] + for i in illegal_filename: + name = name.replace(i, "") + if len(name) == 0: + return {"status": False, "reason": "Invalid name."} return good - def addConfiguration(data, configs, WG_CONF_PATH): + def addConfiguration(self, data, configs, WG_CONF_PATH): output = ["[Interface]", "SaveConfig = true"] - required = ['addConfigurationPrivateKey', 'addConfigurationListenPort', - 'addConfigurationAddress', 'addConfigurationPreUp', 'addConfigurationPreDown', - 'addConfigurationPostUp', 'addConfigurationPostDown'] + required = ['addConfigurationPrivateKey', 'addConfigurationListenPort', + 'addConfigurationAddress', 'addConfigurationPreUp', 'addConfigurationPreDown', + 'addConfigurationPostUp', 'addConfigurationPostDown'] for i in required: e = data[i] if len(e) != 0: @@ -82,14 +96,42 @@ class addConfiguration: o = f"{key} = {e}" output.append(o) name = data['addConfigurationName'] - illegal_filename = [" ",".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", "com3", - "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", - "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"] + illegal_filename = ["(Space)", " ", ".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", + "com3", + "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", + "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"] for i in illegal_filename: name = name.replace(i, "") + try: newFile = open(f"{WG_CONF_PATH}/{name}.conf", "w+") newFile.write("\n".join(output)) except Exception as e: - return {"status": False, "reason":str(e)} - return {"status": True, "reason":"", "data": name} \ No newline at end of file + return {"status": False, "reason": str(e)} + return {"status": True, "reason": "", "data": name} + + def deleteConfiguration(self, data, config, g, WG_CONF_PATH): + confs = [] + for i in config: + confs.append(i['conf']) + print(confs) + if data['name'] not in confs: + return {"status": False, "reason": "Configuration does not exist", "data": ""} + for i in config: + if i['conf'] == data['name']: + if i['status'] == "running": + try: + subprocess.check_output("wg-quick down " + data['name'], shell=True, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as exc: + return {"status": False, "reason": "Can't stop peer", "data": str(exc.output.strip().decode("utf-8"))} + + g.cur.execute(f'DROP TABLE {data["name"]}') + g.cur.execute(f'DROP TABLE {data["name"]}_restrict_access') + g.db.commit() + + try: + os.remove(f'{WG_CONF_PATH}/{data["name"]}.conf') + except Exception as e: + return {"status": False, "reason": "Can't delete peer", "data": str(e)} + + return good \ No newline at end of file diff --git a/src/dashboard.py b/src/dashboard.py index 33671b95..1bce24c7 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -1011,7 +1011,7 @@ def configuration(config_name): conf_data['checked'] = "checked" config_list = get_conf_list() if config_name not in [conf['conf'] for conf in config_list]: - return render_template('index.html', conf=get_conf_list()) + return redirect('/') refresh_interval = int(config.get("Server", "dashboard_refresh_interval")) dns_address = config.get("Peers", "peer_global_DNS") @@ -1110,14 +1110,14 @@ def switch(config_name): shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: # session["switch_msg"] = exc.output.strip().decode("utf-8") - return jsonify({"status": False, "reason":"Can't stop peer", "message": str(exc.output.strip().decode("utf-8"))}) + return jsonify({"status": False, "reason":"Can't stop configuration", "message": str(exc.output.strip().decode("utf-8"))}) elif status == "stopped": try: subprocess.check_output("wg-quick up " + config_name, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: # session["switch_msg"] = exc.output.strip().decode("utf-8") - return jsonify({"status": False, "reason":"Can't turn on peer", "message": str(exc.output.strip().decode("utf-8"))}) + return jsonify({"status": False, "reason":"Can't turn on configuration", "message": str(exc.output.strip().decode("utf-8"))}) return jsonify({"status": True, "reason":""}) @app.route('/add_peer_bulk/', methods=['POST']) @@ -1556,7 +1556,7 @@ def addConfigurationAddressCheck(): returnData = {"status": True, "reason": ""} required = ['address'] if checkJSONAllParameter(required, data): - returnData = api.addConfiguration.AddressCheck(data) + returnData = api.addConfiguration.AddressCheck(api.addConfiguration, data) else: return jsonify(api.notEnoughParameter) return jsonify(returnData) @@ -1567,7 +1567,7 @@ def addConfigurationPortCheck(): returnData = {"status": True, "reason": ""} required = ['port'] if checkJSONAllParameter(required, data): - returnData = api.addConfiguration.PortCheck(data, get_conf_list()) + returnData = api.addConfiguration.PortCheck(api.addConfiguration, data, get_conf_list()) else: return jsonify(api.notEnoughParameter) return jsonify(returnData) @@ -1578,7 +1578,7 @@ def addConfigurationNameCheck(): returnData = {"status": True, "reason": ""} required = ['name'] if checkJSONAllParameter(required, data): - returnData = api.addConfiguration.NameCheck(data, get_conf_list()) + returnData = api.addConfiguration.NameCheck(api.addConfiguration, data, get_conf_list()) else: return jsonify(api.notEnoughParameter) return jsonify(returnData) @@ -1597,11 +1597,36 @@ def addConfiguration(): for i in required: if i not in data.keys(): return jsonify(api.notEnoughParameter) + config = get_conf_list() + nameCheck = api.addConfiguration.NameCheck(api.addConfiguration, {"name": data['addConfigurationName']}, config) + if not nameCheck['status']: + return nameCheck - returnData = api.addConfiguration.addConfiguration(data, get_conf_list(), WG_CONF_PATH) + portCheck = api.addConfiguration.PortCheck(api.addConfiguration, {"port": data['addConfigurationListenPort']}, config) + if not portCheck['status']: + return portCheck + + addressCheck = api.addConfiguration.AddressCheck(api.addConfiguration, {"address": data['addConfigurationAddress']}) + if not addressCheck['status']: + return addressCheck + + returnData = api.addConfiguration.addConfiguration(api.addConfiguration, data, config, WG_CONF_PATH) return jsonify(returnData) - +@app.route('/api/deleteConfiguration', methods=['POST']) +def deleteConfiguration(): + data = request.get_json() + returnData = {"status": True, "reason": "", "data":""} + required = ['name'] + if not checkJSONAllParameter(required, data): + return jsonify(api.notEnoughParameter) + + returnData = api.addConfiguration.deleteConfiguration(api.addConfiguration, data, get_conf_list(), g, WG_CONF_PATH) + + + + + return returnData """ Dashboard Tools Related diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 39ce07c5..c7934580 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -272,7 +272,6 @@ body { } .index-switch { - text-align: right; display: flex; align-items: center; justify-content: flex-end; @@ -671,7 +670,7 @@ pre.index-alert { } #switch{ - transition: all 350ms ease-in; + transition: all 200ms ease-in; } .toggle--switch{ @@ -686,7 +685,7 @@ pre.index-alert { position: relative; border: 2px solid #6c757d8c; border-radius: 100px; - transition: all 350ms ease-in; + transition: all 200ms ease-in; cursor: pointer; margin: 0; } @@ -706,10 +705,15 @@ pre.index-alert { animation-name: off; animation-duration: 350ms; animation-fill-mode: forwards; - transition: all 350ms ease-in; + transition: all 200ms ease-in; cursor: pointer; } +.toggleLabel:hover::before{ + filter: brightness(1.2); +} + + .toggle--switch:checked + .toggleLabel{ background-color: #007bff17 !important; border: 2px solid #007bff8c; @@ -787,4 +791,12 @@ pre.index-alert { #reGeneratePrivateKey{ border-top-right-radius: 10px; border-bottom-right-radius: 10px; -} \ No newline at end of file +} + +.addConfigurationToggleStatus.waiting{ + opacity: 0.5; +} + +/*.conf_card .card-body .row .card-col{*/ +/* margin-bottom: 0.5rem;*/ +/*}*/ \ No newline at end of file diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index 6459c8b9..3ae31338 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -body{font-size:.875rem}.feather{height:16px;vertical-align:text-bottom;width:16px}.btn-primary{font-weight:700}.sidebar{bottom:0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1);left:0;padding:48px 0 0;position:fixed;top:0;z-index:100}.sidebar-sticky{height:calc(100vh - 48px);overflow-x:hidden;overflow-y:auto;padding-top:.5rem;position:relative;top:0}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{color:#333;font-weight:500;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{background-color:#dfdfdf;padding-left:30px}.sidebar .nav-link .feather{color:#999;margin-right:4px}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25);font-size:1rem;padding-bottom:.75rem;padding-top:.75rem}.navbar .navbar-toggler{right:1rem;top:.25rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{border-radius:0;border-width:0;padding:.75rem 1rem}.form-control-dark{background-color:hsla(0,0%,100%,.1);border-color:hsla(0,0%,100%,.1);color:#fff}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px hsla(0,0%,100%,.25)}.dot{border-radius:50px;display:inline-block;height:10px;margin-left:auto!important;width:10px}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;opacity:1;transition:all .4s cubic-bezier(.96,-.07,.34,1.01)}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:none!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:none!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{border:0!important;transform:scale(.9) rotate(180deg)}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#28a745}.btn-lock-peer.lock,.btn-lock-peer.lock:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{color:#17a2b8}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{background:#fff;border-color:#007bff;color:#007bff}.peer_data_group{display:flex;margin-bottom:.5rem;text-align:right}.peer_data_group p{margin-bottom:0;margin-right:1rem;text-transform:uppercase}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{align-items:center;display:flex;justify-content:flex-end;text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{bottom:3rem;display:flex;position:fixed;right:2rem;z-index:99}.btn-manage-group .setting_btn_menu{background-color:#fff;border-radius:10px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);display:none;min-width:200px;opacity:0;padding:1rem 0;position:absolute;right:0;top:-124px;transform:translateY(-30px);transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{opacity:1;transform:translateY(0)}.setting_btn_menu a{align-items:center;cursor:pointer;display:flex;font-size:1rem;padding:.5rem 1rem;transition:all .1s ease-in-out}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{border-radius:100px!important;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem;height:54px;padding:0 14px;z-index:99}@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(1turn);-moz-transform:rotate(1turn);-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}.rotating:before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{cursor:pointer;font-size:1.2rem;position:absolute;right:2rem;transform:translateY(-28px)}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.progress-bar{transition:.3s ease-in-out}.key{cursor:pointer;transition:.2s ease-in-out}.key:hover{color:#007bff}.card{border-radius:10px}.peer_list .card .button-group{height:22px}.form-control{border-radius:10px}.btn{border-radius:8px}#password,#username{height:inherit;padding:.6rem calc(.9rem + 32px)}label[for=password],label[for=username]{font-size:1rem;margin:0!important;padding:0;transform:translateY(30px) translateX(16px)}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}@-webkit-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}@-moz-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{height:19.19px;opacity:0!important}#conf_status_btn{transition:.2s ease-in-out}#conf_status_btn.info_loading{animation:loading 3s ease-in-out infinite;border-radius:5px;height:38px}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{filter:brightness(.5);transition:filter .2s ease-in-out}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-x:hidden;overflow-y:scroll}.no-response{align-items:center;background:#000000ba;display:none;flex-direction:column;height:100%;justify-content:center;opacity:0;position:fixed;transition:all 1s ease-in-out;width:100%;z-index:10000}.no-response.active{display:flex}.no-response.active.show{opacity:1}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px);transition:all 1s ease-in-out}pre.index-alert{background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;color:#fff;margin-bottom:0;margin-top:1rem;padding:1rem}.peerNameCol{align-items:center;display:flex;margin-bottom:.2rem}.peerName{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.peerLightContainer{margin:0;margin-left:auto!important;text-transform:uppercase}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{align-items:center;display:flex;margin-bottom:1rem}.chartTitle h6{line-height:1;margin-bottom:0;margin-right:.5rem}.chartContainer.fullScreen{background-color:#fff;height:100%;left:0;padding:32px;position:fixed;top:0;width:calc(100% + 15px);z-index:9999}.chartContainer.fullScreen .col-sm{height:100%;padding-right:0}.chartContainer.fullScreen .chartCanvasContainer{height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important;width:100%}#switch{transition:all .35s ease-in}.toggle--switch{display:none}.toggleLabel{background-color:#6c757d17;border:2px solid #6c757d8c;border-radius:100px;cursor:pointer;display:flex;height:32px;margin:0;position:relative;transition:all .35s ease-in;width:64px}.toggle--switch.waiting+.toggleLabel{opacity:.5}.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:off;background-color:#6c757d;border-radius:100px;content:"";cursor:pointer;height:26px;margin:1px;position:absolute;transition:all .35s ease-in;width:26px}.toggle--switch:checked+.toggleLabel{background-color:#007bff17!important;border:2px solid #007bff8c}.toggle--switch:checked+.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:on;background-color:#007bff}@keyframes on{0%{left:0}60%{left:0;width:40px}to{left:32px;width:26px}}@keyframes off{0%{left:32px}60%{left:18px;width:40px}to{left:0;width:26px}}.toast{min-width:300px}.toast,.toast-header{background-color:#fff}.toast-progressbar{background-color:#007bff;border-bottom-left-radius:.25rem;height:4px;width:100%} \ No newline at end of file +@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@keyframes on{0%{left:0}60%{left:0;width:40px}to{left:32px;width:26px}}@keyframes off{0%{left:32px}60%{left:18px;width:40px}to{left:0;width:26px}}body{font-size:.875rem}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key,.codeFont{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:all .4s cubic-bezier(.96,-.07,.34,1.01);opacity:1}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#28a745}.btn-lock-peer.lock,.btn-lock-peer.lock:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{display:flex;align-items:center;justify-content:flex-end}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:250px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{height:19.19px;opacity:0!important}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important}#switch{transition:all 200ms ease-in}.toggle--switch{display:none}.toggleLabel,.toggleLabel::before{border-radius:100px;transition:all 200ms ease-in;cursor:pointer}.toggleLabel{width:64px;height:32px;background-color:#6c757d17;display:flex;position:relative;border:2px solid #6c757d8c;margin:0}.addConfigurationToggleStatus.waiting,.toggle--switch.waiting+.toggleLabel{opacity:.5}.toggleLabel::before{background-color:#6c757d;height:26px;width:26px;content:"";margin:1px;position:absolute;animation-name:off;animation-duration:350ms;animation-fill-mode:forwards}.toggleLabel:hover::before{filter:brightness(1.2)}.toggle--switch:checked+.toggleLabel{background-color:#007bff17!important;border:2px solid #007bff8c}.toggle--switch:checked+.toggleLabel::before{background-color:#007bff;animation-name:on;animation-duration:350ms;animation-fill-mode:forwards}.toast{min-width:300px;background-color:#fff}.toast-header{background-color:rgba(255,255,255)}.toast-progressbar{width:100%;height:4px;background-color:#007bff;border-bottom-left-radius:.25rem}.addConfigurationAvailableIPs{margin-bottom:0}.input-feedback{display:none}#addConfigurationModal label{display:flex;width:100%;align-items:center}#addConfigurationModal label a{margin-left:auto!important}#reGeneratePrivateKey{border-top-right-radius:10px;border-bottom-right-radius:10px} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index a557cb2b..b1835e92 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -3,7 +3,6 @@ * Under Apache-2.0 License */ - let peers = []; (function() { /** @@ -37,6 +36,7 @@ let peers = []; let qrcodeModal = new bootstrap.Modal(document.getElementById('qrcode_modal'), bootstrapModalConfig); let settingModal = new bootstrap.Modal(document.getElementById('setting_modal'), bootstrapModalConfig); let deleteModal = new bootstrap.Modal(document.getElementById('delete_modal'), bootstrapModalConfig); + let configurationDeleteModal = new bootstrap.Modal(document.getElementById('configuration_delete_modal'), bootstrapModalConfig); $("[data-toggle='tooltip']").tooltip(); $("[data-toggle='popover']").popover(); @@ -207,7 +207,7 @@ let peers = []; setActiveConfigurationName(); window.history.pushState(null, null, `/configuration/${configuration_name}`); $("title").text(`${configuration_name} | WGDashboard`); - + $(".index-alert").addClass("d-none").text(``); totalDataUsageChartObj.data.labels = []; totalDataUsageChartObj.data.datasets[0].data = []; totalDataUsageChartObj.data.datasets[1].data = []; @@ -667,7 +667,7 @@ let peers = []; } function removeAllTooltips(){ - $(".tooltip").remove() + $(".tooltip").remove(); } function toggleAccess(peerID){ @@ -828,21 +828,30 @@ let peers = []; }); } + + + function deleteConfiguration(){ + + } + window.configurations = { addModal: () => { return addModal; }, deleteBulkModal: () => { return deleteBulkModal; }, deleteModal: () => { return deleteModal; }, + configurationDeleteModal: () => { return configurationDeleteModal; }, ipModal: () => { return ipModal; }, qrcodeModal: () => { return qrcodeModal; }, settingModal: () => { return settingModal; }, configurationTimeout: () => { return configuration_timeout; }, - updateDisplayMode: () => { display_mode = window.localStorage.getItem("displayMode") }, + updateDisplayMode: () => { display_mode = window.localStorage.getItem("displayMode"); }, + removeConfigurationInterval: () => { removeConfigurationInterval(); }, loadPeers: (searchString) => { loadPeers(searchString); }, addPeersByBulk: () => { addPeersByBulk(); }, deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); }, + deleteConfiguration: () => { deleteConfiguration() }, parsePeers: (response) => { parsePeers(response); }, - toggleAccess: (peerID) => { toggleAccess(peerID) }, + toggleAccess: (peerID) => { toggleAccess(peerID); }, setConfigurationName: (confName) => { configuration_name = confName; }, @@ -867,6 +876,40 @@ let $body = $("body"); let available_ips = []; let $add_peer = document.getElementById("save_peer"); +$("#configuration_delete").on("click", function(){ + window.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); + }); +} + +$("#sure_delete_configuration").on("click", function () { + window.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": window.configurations.getConfigurationName()}, done); +}); + + /** * ========== * Add peers @@ -883,7 +926,8 @@ document.querySelector(".add_btn").addEventListener("click", () => { /** * When configuration switch got click */ -$(".toggle--switch").on("click", function(){ +$(".toggle--switch").on("change", function(){ + console.log('lol') $(this).addClass("waiting").attr("disabled", "disabled"); let id = window.configurations.getConfigurationName(); let status = $(this).prop("checked"); @@ -891,22 +935,23 @@ $(".toggle--switch").on("click", function(){ $.ajax({ url: `/switch/${id}` }).done(function(res){ - console.log(); - if (res){ + if (res.status){ if (status){ window.configurations.showToast(`${id} is running.`) }else{ window.configurations.showToast(`${id} is stopped.`) } - ele.removeClass("waiting"); - ele.removeAttr("disabled"); }else{ if (status){ - $(this).prop("checked", false) + ele.prop("checked", false) }else{ - $(this).prop("checked", true) + ele.prop("checked", true) } + window.configurations.showToast(res.reason); + $(".index-alert").removeClass("d-none").text(`Configuration toggle failed. Please check the following error message:\n${res.message}`); } + ele.removeClass("waiting"); + ele.removeAttr("disabled"); window.configurations.loadPeers($('#search_peer_textbox').val()) }); diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index f75e42da..fa39b9a5 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1 +1,50 @@ -!function(){let configuration_name,configuration_interval,configuration_timeout=window.localStorage.getItem("configurationTimeout");null!==configuration_timeout&&["5000","10000","30000","60000"].includes(configuration_timeout)||(window.localStorage.setItem("configurationTimeout","10000"),configuration_timeout=window.localStorage.getItem("configurationTimeout")),document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active");let display_mode=window.localStorage.getItem("displayMode");null!==display_mode&&["grid","list"].includes(display_mode)||(window.localStorage.setItem("displayMode","grid"),display_mode="grid"),document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active")),document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active");let $progress_bar=$(".progress-bar"),bootstrapModalConfig={keyboard:!1,backdrop:"static"},addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig),deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig),ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig),qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig),settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig),deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip(),$("[data-toggle='popover']").popover();let chartUnit=window.localStorage.chartUnit,chartUnitAvailable;null!==chartUnit&&["GB","MB","KB"].includes(chartUnit)?$(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active"):(window.localStorage.setItem("chartUnit","GB"),$('.switchUnit[data-unit="GB"]').addClass("active")),chartUnit=window.localStorage.getItem("chartUnit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d"),totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:!1,showScale:!1,responsive:!1,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%"),totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width(),totalDataUsageChartObj.resize(),$(window).on("resize",(function(){totalDataUsageChartObj.resize()})),$(".fullScreen").on("click",(function(){let $chartContainer=$(".chartContainer");$chartContainer.hasClass("fullScreen")?($(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"),$chartContainer.removeClass("fullScreen")):($(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit"),$chartContainer.addClass("fullScreen")),totalDataUsageChartObj.resize()}));let mul=1;function configurationAlert(response){if(""===response.listen_port&&"stopped"===response.status){let configAlert=document.createElement("div");configAlert.classList.add("alert"),configAlert.classList.add("alert-warning"),configAlert.setAttribute("role","alert"),configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.",document.querySelector("#config_info_alert").appendChild(configAlert)}if("N/A"===response.conf_address){let configAlert=document.createElement("div");configAlert.classList.add("alert"),configAlert.classList.add("alert-warning"),configAlert.setAttribute("role","alert"),configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.",document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active"),$(`.sb-${configuration_name}-url`).addClass("active")}$(".switchUnit").on("click",(function(){if($(".switchUnit").removeClass("active"),$(this).addClass("active"),$(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":"MB"===chartUnit&&(mul=1/1024),"KB"===chartUnit&&(mul=1/1048576);break;case"MB":"GB"===chartUnit&&(mul=1024),"KB"===chartUnit&&(mul=1/1024);break;case"KB":"GB"===chartUnit&&(mul=1048576),"MB"===chartUnit&&(mul=1024)}window.localStorage.setItem("chartUnit",$(this).data("unit")),chartUnit=$(this).data("unit"),totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul),totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul),totalDataUsageChartObj.update()}}));let firstLoading=!0;function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if("checked"===response.checked?$conf_status_btn.innerHTML=` ON`:$conf_status_btn.innerHTML=` OFF`,response.running_peer>0){let d,time=(new Date).toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});if(totalDataUsageChartObj.data.labels.push(`${time}`),0===totalDataUsageChartObj.data.datasets[0].data.length)totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2],totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1],totalDataUsageChartObj.data.datasets[0].data.push(0),totalDataUsageChartObj.data.datasets[1].data.push(0);else{50===totalDataUsageChartObj.data.datasets[0].data.length&&50===totalDataUsageChartObj.data.datasets[1].data.length&&(totalDataUsageChartObj.data.labels.shift(),totalDataUsageChartObj.data.datasets[0].data.shift(),totalDataUsageChartObj.data.datasets[1].data.shift());let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData,newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData,k=0;k="MB"===chartUnit?1024:"KB"===chartUnit?1048576:1,totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k),totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k),totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1],totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name,$conf_status_btn.classList.remove("info_loading"),document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected")),document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected"),document.querySelector("#conf_status").innerHTML=`${response.status}`,document.querySelector("#conf_connected_peers").innerHTML=response.running_peer,document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`,document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`,document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`,document.querySelector("#conf_public_key").innerHTML=response.public_key,document.querySelector("#conf_listen_port").innerHTML=""===response.listen_port?"N/A":response.listen_port,document.querySelector("#conf_address").innerHTML=response.conf_address,document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(0===response.peer_data.length)document.querySelector(".peer_list").innerHTML='

Oops! No peers found ‘︿’

';else{let mode="list"===display_mode?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach((function(peer){let total_r=0,total_s=0;total_r+=peer.cumu_receive,total_s+=peer.cumu_sent;let spliter='
',peer_name=`
\n
${""===peer.name?"Untitled":peer.name}
\n
\n
`,peer_transfer=`
\n

\n ${roundN(peer.total_receive+total_r,4)} GB\n

\n

\n ${roundN(peer.total_sent+total_s,4)} GB\n

\n
`,peer_key='
PEERCLICK TO COPY
'+peer.id+"
",peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
",peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
",peer_endpoint='
END POINT
'+peer.endpoint+"
",peer_control=`\n
\n
\n
\n \n \n `;""!==peer.private_key&&(peer_control+=''),peer_control+="
";let html='
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
";result+=html})),document.querySelector(".peer_list").innerHTML=result,void 0===configuration_interval&&setConfigurationInterval()}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key"),data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid"))if(""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=configuration_name,keys=[];for(let i=0;i<$new_add_amount.val();i++)keys.push(window.wireguard.generateKeypair());$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.val()}),success:function(response){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast($new_add_amount.val()+" peers added successful!"),window.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";else $add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Add"}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if("true"!==response){if(window.configurations.deleteModal()._isShown&&($("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none"),$("#delete_peer").removeAttr("disabled").html("Delete")),window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none"),$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else window.configurations.deleteModal()._isShown&&window.configurations.deleteModal().toggle(),window.configurations.deleteBulkModal()._isShown&&($("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"),$("#selected_peer_list").html(""),$(".delete-bulk-peer-item.active").removeClass("active"),window.configurations.deleteBulkModal().toggle()),window.configurations.loadPeers($("#search_peer_textbox").val()),$("#alertToast").toast("show"),$("#alertToast .toast-body").html("Peer deleted!"),$("#delete_peer").removeAttr("disabled").html("Delete")}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active")),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show")),document.querySelector("#right_body").classList.add("no-responding"),document.querySelector(".navbar").classList.add("no-responding"),document.querySelector(".no-response .container h4").innerHTML=message}),10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show")),document.querySelector("#right_body").classList.remove("no-responding"),document.querySelector(".navbar").classList.remove("no-responding"),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))}),1010)}function setConfigurationInterval(){configuration_interval=setInterval((function(){loadPeers($("#search_peer_textbox").val())}),configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%"),setTimeout((function(){stillLoadingProgressBar()}),300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%"),setTimeout((function(){$progress_bar.css("opacity","0")}),250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}$(".nav-conf-link").on("click",(function(e){e.preventDefault(),configuration_name!==$(this).data("conf-id")&&(firstLoading=!0,$("#config_body").addClass("firstLoading"),configuration_name=$(this).data("conf-id"),loadPeers($("#search_peer_textbox").val())&&(setActiveConfigurationName(),window.history.pushState(null,null,`/configuration/${configuration_name}`),$("title").text(`${configuration_name} | WGDashboard`),totalDataUsageChartObj.data.labels=[],totalDataUsageChartObj.data.datasets[0].data=[],totalDataUsageChartObj.data.datasets[1].data=[],totalDataUsageChartObj.update()))}));let time=0,count=0,d1=new Date;function loadPeers(searchString){d1=new Date;let good=!0;return $.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done((function(response){console.log(response),parsePeers(response)})).fail((function(){noResponding(),good=!1})),good}function parsePeers(response){if(response.status){let d2,seconds=new Date-d1;time+=seconds,count+=1,window.console.log(`Average time: ${time/count}ms`),$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`),removeNoResponding(),peers=response.data.peer_data,configurationAlert(response.data),configurationHeader(response.data),configurationPeers(response.data),$(".dot.dot-running").attr("title","Peer Connected").tooltip(),$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(),$("i[data-toggle='tooltip']").tooltip(),$("#configuration_name").text(configuration_name),firstLoading&&(firstLoading=!1,$("#config_body").removeClass("firstLoading"))}else noResponding(response.message),removeConfigurationInterval()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey,document.querySelector("#public_key").value=keys.publicKey,document.querySelector("#add_peer_alert").classList.add("d-none"),document.querySelector("#re_generate_key i").classList.remove("rotating"),document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show"),$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(interval){configuration_timeout=interval,window.localStorage.setItem("configurationTimeout",configuration_timeout.toString()),removeConfigurationInterval(),setConfigurationInterval(),showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`))}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob),link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list"),id=element.data("id"),name=""===element.data("name")?"Untitled Peer":element.data("name");element.hasClass("active")?(element.removeClass("active"),$("#selected_peer_list .badge[data-id='"+id+"']").remove()):(element.addClass("active"),$selected_peer_list.append(''+name+" - "+id+""))}function copyToClipboard(element){let $temp=$("");$body.append($temp),$temp.val($(element).text()).trigger("select"),document.execCommand("copy"),$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done((function(res){if(!0===res.status){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="",document.querySelector("#allowed_ips").value=available_ips[0],available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else document.querySelector("#allowed_ips").value=res.message,document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}))}window.configurations={addModal:()=>addModal,deleteBulkModal:()=>deleteBulkModal,deleteModal:()=>deleteModal,ipModal:()=>ipModal,qrcodeModal:()=>qrcodeModal,settingModal:()=>settingModal,configurationTimeout:()=>configuration_timeout,updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>configuration_name,setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>cleanIp(val),startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}}();let $body=$("body"),available_ips=[],$add_peer=document.getElementById("save_peer"),typingTimer;document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()}),document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");selector.contains(event.target)&&(selector.style.display="none",document.querySelector("div[role=status]").style.display="inline-block",location.replace(`/switch/${selector.getAttribute("id")}`))}),document.querySelector("#private_key").addEventListener("change",event=>{let publicKey=document.querySelector("#public_key");44===event.target.value.length?(publicKey.value=window.wireguard.generatePublicKey(event.target.value),publicKey.setAttribute("disabled","disabled")):(publicKey.attributes.removeNamedItem("disabled"),publicKey.value="")}),$("#add_modal").on("show.bs.modal",(function(){window.configurations.generateKeyPair(),window.configurations.getAvailableIps()})).on("hide.bs.modal",(function(){$("#allowed_ips_indicator").html("")})),$("#re_generate_key").on("click",(function(){$("#public_key").attr("disabled","disabled"),$("#re_generate_key i").addClass("rotating"),window.configurations.generateKeyPair()})),$("#allowed_ips").on("keyup",(function(){let s=window.configurations.cleanIp($(this).val());s=s.split(","),available_ips.includes(s[s.length-1])?$("#allowed_ips_indicator").removeClass().addClass("text-success").html(''):$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')})),$("#peer_name_textbox").on("keyup",(function(){$(".peer_name").html($(this).val())})),$add_peer.addEventListener("click",(function(){let $bulk_add;if($("#bulk_add").prop("checked"))$("#new_add_amount").hasClass("is-invalid")||window.configurations.addPeersByBulk();else{let $public_key=$("#public_key"),$private_key=$("#private_key"),$allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_name=$("#new_add_name"),$new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key");if($add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML="Adding...",""!==$allowed_ips.val()&&""!==$public_key.val()&&""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=window.configurations.getConfigurationName(),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){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast("Add peer successful!"),window.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"}})),$("#new_add_amount").on("keyup",(function(){let $bulk_amount_validation=$("#bulk_amount_validation");$(this).val().length>0?isNaN($(this).val())?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter a valid integer")):$(this).val()>available_ips.length?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`)):$(this).val()<1?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter at least 1 or more.")):$(this).removeClass("is-invalid").addClass("is-valid"):$(this).removeClass("is-invalid").removeClass("is-valid")})),$("#bulk_add").on("change",(function(){let hide=$(".non-bulk"),amount=$("#new_add_amount");if(!0===$(this).prop("checked")){for(let i=0;i{document.querySelector("#add_modal").classList.add("ip_modal_open")}).on("hidden.bs.modal",()=>{document.querySelector("#add_modal").classList.remove("ip_modal_open");let ips=[],$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=>window.configurations.triggerIp(ele))}),$body.on("click",".available-ip-badge",(function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active"),$(this).remove()})),$body.on("click",".available-ip-item",(function(){window.configurations.triggerIp($(this).data("ip"))})),$("#search_available_ip").on("click",(function(){window.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{window.configurations.ipModal().toggle();let ips=[],$selected_ip_list;$("#selected_ip_list").children().each((function(){ips.push($(this).data("ip"))})),$("#allowed_ips").val(ips.join(", ")),ips.forEach(ele=>window.configurations.triggerIp(ele))}),$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),window.configurations.qrcodeModal().toggle()}))})),$body.on("click",".btn-delete-peer",(function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id),window.configurations.deleteModal().toggle()})),$body.on("click",".btn-lock-peer",(function(){let $lockGlyph="bi-lock-fill",$unlockGlyph="bi-unlock-fill";$(this).children().hasClass($lockGlyph)?($(this).children().removeClass($lockGlyph).addClass($unlockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")):($(this).children().removeClass($unlockGlyph).addClass($lockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show"))})),$("#delete_peer").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Deleting...");let config=window.configurations.getConfigurationName(),peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)})),$body.on("click",".btn-setting-peer",(function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id),$.ajax({method:"POST",url:"/get_peer_data/"+window.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),window.configurations.settingModal().toggle(),window.configurations.endProgressBar()}})})),$("#setting_modal").on("hidden.bs.modal",(function(){$("#setting_peer_alert").addClass("d-none")})),$("#peer_private_key_textbox").on("change",(function(){let $save_peer_setting=$("#save_peer_setting");$(this).val().length>0&&$.ajax({url:"/check_key_match/"+window.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){"failed"===res.status?$("#setting_peer_alert").html(res.status).removeClass("d-none"):$("#setting_peer_alert").addClass("d-none")}))})),$("#save_peer_setting").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Saving...");let $peer_DNS_textbox=$("#peer_DNS_textbox"),$peer_allowed_ip_textbox=$("#peer_allowed_ip_textbox"),$peer_endpoint_allowed_ips=$("#peer_endpoint_allowed_ips"),$peer_name_textbox=$("#peer_name_textbox"),$peer_private_key_textbox=$("#peer_private_key_textbox"),$peer_preshared_key_textbox=$("#peer_preshared_key_textbox"),$peer_mtu=$("#peer_mtu"),$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"),conf_id=$(this).attr("conf_id"),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){"failed"===response.status?$("#setting_peer_alert").html(response.msg).removeClass("d-none"):(window.configurations.settingModal().toggle(),window.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")})),$(".peer_private_key_textbox_switch").on("click",(function(){let $peer_private_key_textbox=$("#peer_private_key_textbox"),mode="password"===$peer_private_key_textbox.attr("type")?"text":"password",icon="password"===$peer_private_key_textbox.attr("type")?"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)}));let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",(function(){clearTimeout(typingTimer),typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)})).on("keydown",(function(){clearTimeout(typingTimer)})),$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})})),$body.on("mouseenter",".key",(function(){let label;$(this).parent().siblings().children()[1].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];window.configurations.copyToClipboard($(this)),label.innerHTML="COPIED!"})),$body.on("click",".update_interval",(function(){let _new;$(".interval-btn-group button").removeClass("active"),$(this).addClass("active");let interval=$(this).data("refresh-interval");[5e3,1e4,3e4,6e4].includes(interval)&&window.configurations.updateRefreshInterval(interval)})),$body.on("click",".refresh",(function(){window.configurations.loadPeers($("#search_peer_textbox").val())})),$body.on("click",".display_mode",(function(){$(".display-btn-group button").removeClass("active"),$(this).addClass("active"),window.localStorage.setItem("displayMode",$(this).data("display-mode")),window.configurations.updateDisplayMode(),"list"===$(this).data("display-mode")?(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-12")})),window.configurations.showToast("Displaying as List")):(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")})),window.configurations.showToast("Displaying as Grids"))}));let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",-1*($setting_btn_menu.height()+54));let $setting_btn=$(".setting_btn");$setting_btn.on("click",(function(){$setting_btn_menu.hasClass("show")?($setting_btn_menu.removeClass("showing"),setTimeout((function(){$setting_btn_menu.removeClass("show")}),201)):($setting_btn_menu.addClass("show"),setTimeout((function(){$setting_btn_menu.addClass("showing")}),10))})),$("html").on("click",(function(r){document.querySelector(".setting_btn")!==r.target&&(document.querySelector(".setting_btn").contains(r.target)||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_btn").on("click",()=>{let $delete_bulk_modal_list=$("#delete_bulk_modal .list-group");$delete_bulk_modal_list.html(""),peers.forEach(peer=>{let name;name=""===peer.name?"Untitled Peer":peer.name,$delete_bulk_modal_list.append(''+name+"
"+peer.id+"
")}),window.configurations.deleteBulkModal().toggle()}),$body.on("click",".delete-bulk-peer-item",(function(){window.configurations.toggleDeleteByBulkIP($(this))})).on("click",".delete-peer-bulk-badge",(function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))}));let $selected_peer_list=document.getElementById("selected_peer_list"),changeObserver=new MutationObserver((function(){$selected_peer_list.hasChildNodes()?$("#confirm_delete_bulk_peers").removeAttr("disabled"):$("#confirm_delete_bulk_peers").attr("disabled","disabled")})),confirm_delete_bulk_peers_interval;changeObserver.observe($selected_peer_list,{attributes:!0,childList:!0,characterData:!0}),$("#confirm_delete_bulk_peers").on("click",(function(){let btn=$(this);if(void 0!==confirm_delete_bulk_peers_interval)clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0,btn.html("Delete");else{let timer=5;btn.html(`Deleting in ${timer} secs... Click to cancel`),confirm_delete_bulk_peers_interval=setInterval((function(){if(timer-=1,btn.html(`Deleting in ${timer} secs... Click to cancel`),0===timer){btn.html("Deleting..."),btn.attr("disabled","disabled");let ips=[];$selected_peer_list.childNodes.forEach(ele=>ips.push(ele.dataset.id)),window.configurations.deletePeers(window.configurations.getConfigurationName(),ips),clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0}}),1e3)}})),$("#select_all_delete_bulk_peers").on("click",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")||window.configurations.toggleDeleteByBulkIP($(this))}))})),$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")&&window.configurations.toggleDeleteByBulkIP($(this))}))})),$body.on("click",".btn-download-peer",(function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})})),$("#download_all_peers").on("click",(function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){res.peers.length>0?(window.wireguard.generateZipFiles(res),window.configurations.showToast("Peers' zip file download successful!")):window.configurations.showToast("Oops! There are no peer can be download.")}})})); \ No newline at end of file +import{ajaxPostJSON}from"./index";let peers=[];(function(){let configuration_name;let configuration_interval;let configuration_timeout=window.localStorage.getItem("configurationTimeout");if(configuration_timeout===null||!["5000","10000","30000","60000"].includes(configuration_timeout)){window.localStorage.setItem("configurationTimeout","10000");configuration_timeout=window.localStorage.getItem("configurationTimeout")}document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active");let display_mode=window.localStorage.getItem("displayMode");if(display_mode===null||!["grid","list"].includes(display_mode)){window.localStorage.setItem("displayMode","grid");display_mode="grid"}document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${display_mode}"]`).classList.add("active");let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);let configurationDeleteModal=new bootstrap.Modal(document.getElementById("configuration_delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let chartUnit=window.localStorage.chartUnit;let chartUnitAvailable=["GB","MB","KB"];if(chartUnit===null||!chartUnitAvailable.includes(chartUnit)){window.localStorage.setItem("chartUnit","GB");$('.switchUnit[data-unit="GB"]').addClass("active")}else{$(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active")}chartUnit=window.localStorage.getItem("chartUnit");const totalDataUsageChart=document.getElementById("totalDataUsageChartObj").getContext("2d");const totalDataUsageChartObj=new Chart(totalDataUsageChart,{type:"line",data:{labels:[],datasets:[{label:"Data Sent",data:[],stroke:"#FFFFFF",borderColor:"#28a745",tension:.1,borderWidth:2},{label:"Data Received",data:[],stroke:"#FFFFFF",borderColor:"#007bff",tension:.1,borderWidth:2}]},options:{maintainAspectRatio:false,showScale:false,responsive:false,scales:{y:{min:0,ticks:{min:0,callback:function(value,index,ticks){return`${value} ${chartUnit}`}}}},plugins:{tooltip:{callbacks:{label:function(context){return`${context.dataset.label}: ${context.parsed.y} ${chartUnit}`}}}}}});let $totalDataUsageChartObj=$("#totalDataUsageChartObj");$totalDataUsageChartObj.css("width","100%");totalDataUsageChartObj.width=$totalDataUsageChartObj.parent().width();totalDataUsageChartObj.resize();$(window).on("resize",function(){totalDataUsageChartObj.resize()});$(".fullScreen").on("click",function(){let $chartContainer=$(".chartContainer");if($chartContainer.hasClass("fullScreen")){$(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen");$chartContainer.removeClass("fullScreen")}else{$(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit");$chartContainer.addClass("fullScreen")}totalDataUsageChartObj.resize()});let mul=1;$(".switchUnit").on("click",function(){$(".switchUnit").removeClass("active");$(this).addClass("active");if($(this).data("unit")!==chartUnit){switch($(this).data("unit")){case"GB":if(chartUnit==="MB"){mul=1/1024}if(chartUnit==="KB"){mul=1/1048576}break;case"MB":if(chartUnit==="GB"){mul=1024}if(chartUnit==="KB"){mul=1/1024}break;case"KB":if(chartUnit==="GB"){mul=1048576}if(chartUnit==="MB"){mul=1024}break;default:break}window.localStorage.setItem("chartUnit",$(this).data("unit"));chartUnit=$(this).data("unit");totalDataUsageChartObj.data.datasets[0].data=totalDataUsageChartObj.data.datasets[0].data.map(x=>x*mul);totalDataUsageChartObj.data.datasets[1].data=totalDataUsageChartObj.data.datasets[1].data.map(x=>x*mul);totalDataUsageChartObj.update()}});function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function setActiveConfigurationName(){$(".nav-conf-link").removeClass("active");$(`.sb-${configuration_name}-url`).addClass("active")}let firstLoading=true;$(".nav-conf-link").on("click",function(e){e.preventDefault();if(configuration_name!==$(this).data("conf-id")){firstLoading=true;$("#config_body").addClass("firstLoading");configuration_name=$(this).data("conf-id");if(loadPeers($("#search_peer_textbox").val())){setActiveConfigurationName();window.history.pushState(null,null,`/configuration/${configuration_name}`);$("title").text(`${configuration_name} | WGDashboard`);totalDataUsageChartObj.data.labels=[];totalDataUsageChartObj.data.datasets[0].data=[];totalDataUsageChartObj.data.datasets[1].data=[];totalDataUsageChartObj.update()}}});function configurationHeader(response){let $conf_status_btn=$(".toggle--switch");if(response.checked==="checked"){$conf_status_btn.prop("checked",true)}else{$conf_status_btn.prop("checked",false)}$conf_status_btn.data("conf-id",configuration_name);if(response.running_peer>0){let d=new Date;let time=d.toLocaleString("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});totalDataUsageChartObj.data.labels.push(`${time}`);if(totalDataUsageChartObj.data.datasets[0].data.length===0){totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2];totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[0].data.push(0);totalDataUsageChartObj.data.datasets[1].data.push(0)}else{if(totalDataUsageChartObj.data.datasets[0].data.length===50&&totalDataUsageChartObj.data.datasets[1].data.length===50){totalDataUsageChartObj.data.labels.shift();totalDataUsageChartObj.data.datasets[0].data.shift();totalDataUsageChartObj.data.datasets[1].data.shift()}let newTotalReceive=response.total_data_usage[2]-totalDataUsageChartObj.data.datasets[1].lastData;let newTotalSent=response.total_data_usage[1]-totalDataUsageChartObj.data.datasets[0].lastData;let k=0;if(chartUnit==="MB"){k=1024}else if(chartUnit==="KB"){k=1048576}else{k=1}totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k);totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k);totalDataUsageChartObj.data.datasets[0].lastData=response.total_data_usage[1];totalDataUsageChartObj.data.datasets[1].lastData=response.total_data_usage[2]}totalDataUsageChartObj.update()}document.querySelector("#conf_name").textContent=configuration_name;$("#switch").removeClass("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;let delay=0;let h6=$(".info h6");for(let i=0;i

Oops! No peers found ‘︿’

`}else{let mode=display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+
${peer.name===""?"Untitled":peer.name}
+
+
`;let peer_transfer=`
+

+ ${roundN(peer.total_receive+total_r,4)} GB +

+

+ ${roundN(peer.total_sent+total_s,4)} GB +

+
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` +
+
+
+ + + `;if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});response.lock_access_peers.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
+
${peer.name===""?"Untitled":peer.name}
+
+
`;let peer_transfer=`
+

+ ${roundN(peer.total_receive+total_r,4)} GB +

+

+ ${roundN(peer.total_sent+total_s,4)} GB +

+
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` +
+
+
+ + Peer Disabled +
`;let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(configuration_interval===undefined){setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());window.configurations.showToast(`Deleted ${peer_ids.length} peers`);$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){removeAllTooltips();let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function removeAllTooltips(){$(".tooltip").remove()}function toggleAccess(peerID){$.ajax({url:"/api/togglePeerAccess",method:"POST",headers:{"Content-Type":"application/json"},data:JSON.stringify({peerID:peerID,config:configuration_name})}).done(function(res){if(res.status){loadPeers($("#search_peer_textbox").val())}else{showToast(res.reason)}})}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}let numberToast=0;function showToast(msg){$(".toastContainer").append(``);$(`#${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");numberToast++}function updateRefreshInterval(interval){configuration_timeout=interval;window.localStorage.setItem("configurationTimeout",configuration_timeout.toString());removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}function deleteConfiguration(){}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},configurationDeleteModal:()=>{return configurationDeleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},removeConfigurationInterval:()=>{removeConfigurationInterval()},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},deleteConfiguration:()=>{deleteConfiguration()},parsePeers:response=>{parsePeers(response)},toggleAccess:peerID=>{toggleAccess(peerID)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");$("#configuration_delete").on("click",function(){window.configurations.configurationDeleteModal().toggle()});$("#sure_delete_configuration").on("click",function(){window.configurations.removeConfigurationInterval();$(this).attr("disabled","disabled");function done(res){if(res.status){window.configurations.configurationDeleteModal().toggle()}}ajaxPostJSON("/api/deleteConfiguration",{name:configuration_name},done)});document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});$(".toggle--switch").on("click",function(){$(this).addClass("waiting").attr("disabled","disabled");let id=window.configurations.getConfigurationName();let status=$(this).prop("checked");let ele=$(this);$.ajax({url:`/switch/${id}`}).done(function(res){console.log();if(res){if(status){window.configurations.showToast(`${id} is running.`)}else{window.configurations.showToast(`${id} is stopped.`)}ele.removeClass("waiting");ele.removeAttr("disabled")}else{if(status){$(this).prop("checked",false)}else{$(this).prop("checked",true)}}window.configurations.loadPeers($("#search_peer_textbox").val())})});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).data("peer-id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){window.configurations.toggleAccess($(this).data("peer-id"),window.configurations.getConfigurationName());if($(this).hasClass("lock")){console.log($(this).data("peer-name"));window.configurations.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{window.configurations.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")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).data("peer-id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$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([5e3,1e4,3e4,6e4].includes(interval)){window.configurations.updateRefreshInterval(interval)}});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");window.localStorage.setItem("displayMode",$(this).data("display-mode"));window.configurations.updateDisplayMode();if($(this).data("display-mode")==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/static/js/index.js b/src/static/js/index.js index 67151938..72b690a0 100644 --- a/src/static/js/index.js +++ b/src/static/js/index.js @@ -15,7 +15,7 @@ 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"); -}) +}); function showToast(msg){ $(".toastContainer").append( @@ -28,7 +28,7 @@ function showToast(msg){
${msg}
-
` ) +
` ); $(`#${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)`); @@ -46,7 +46,6 @@ $(".toggle--switch").on("change", function(){ url: `/switch/${id}` }).done(function(res){ let dot = $(`div[data-conf-id="${id}"] .dot`); - console.log(); if (res.status){ if (status){ dot.removeClass("dot-stopped").addClass("dot-running"); @@ -57,11 +56,7 @@ $(".toggle--switch").on("change", function(){ showToast(`${id} is stopped.`); } }else{ - // $(".index-alert").removeClass("d-none"); - // $(".index-alert-full code").text(res.message); ele.parents().children(".card-message").html(`
Configuration toggle failed. Please check the following error message:
${res.message}
`) - - if (status){ ele.prop("checked", false) }else{ @@ -113,6 +108,7 @@ function ajaxPostJSON(url, data, doneFunc){ doneFunc(res); }); } + function validInput(input){ input.removeClass("is-invalid").addClass("is-valid").removeAttr("disabled").data("checked", true); } @@ -215,42 +211,40 @@ $("#addConfigurationBtn").on("click", function(){ } if (filled){ $("#addConfigurationModal .modal-footer .btn").hide(); - $(".addConfigurationStatus").removeClass("d-none").html(`
Loading...
Adding peers`) + $(".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")) + q.push($i.attr("name")); } - function done(res){ + let done = (res) => { let name = res.data; + $(".addConfigurationAddStatus").removeClass("text-primary").addClass("text-success").html(` ${name} added successfully.`); if (res.status){ setTimeout(() => { - - $(".addConfigurationStatus").html(`
Loading...
Toggling ${res.data}`) + $(".addConfigurationToggleStatus").removeClass("waiting").html(`
Toggle Configuration`) $.ajax({ url: `/switch/${name}` }).done(function(res){ if (res.status){ - $(".addConfigurationStatus").removeClass("text-primary").addClass("text-success").html(` ${name} toggled! Refresh in 5 seconds.`); + $(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-success").html(` Toggle Successfully. Refresh in 5 seconds.`); setTimeout(() => { - $(".addConfigurationStatus").text("Refeshing...") + $(".addConfigurationToggleStatus").text("Refeshing...") location.reload(); }, 5000); }else{ - $(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} toggle failed.`) - $("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason); - $("#addCconfigurationAlertMessage").removeClass("d-none").text(res.message); + $(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} toggle failed.`) + $("#addCconfigurationAlertMessage").removeClass("d-none").html(`${name} toggle failed. Please check the following error message:
${res.message}`); } - }) + }); }, 500); - }else{ $(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} adding failed.`) $("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason); } - } + }; ajaxPostJSON("/api/addConfiguration", data, done); } }); \ No newline at end of file diff --git a/src/static/js/index.min.js b/src/static/js/index.min.js new file mode 100644 index 00000000..46f95d92 --- /dev/null +++ b/src/static/js/index.min.js @@ -0,0 +1,10 @@ +let numberToast=0;let emptyInputFeedback="Can't leave empty";$('[data-toggle="tooltip"]').tooltip();let $add_configuration=$("#add_configuration");let addConfigurationModal=$("#addConfigurationModal");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")});function showToast(msg){$(".toastContainer").append(``);$(`#${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");numberToast++}$(".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(`
Configuration toggle failed. Please check the following error message:
${res.message}
`);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"){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)})}export{ajaxPostJSON};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(`${res.data}`);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{let name=res.data;$(".addConfigurationAddStatus").removeClass("text-primary").addClass("text-success").html(` ${name} added successfully.`);if(res.status){setTimeout(()=>{$(".addConfigurationToggleStatus").removeClass("waiting").html(`
Toggle Configuration`);$.ajax({url:`/switch/${name}`}).done(function(res){if(res.status){$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-success").html(` Toggle Successfully. Refresh in 5 seconds.`);setTimeout(()=>{$(".addConfigurationToggleStatus").text("Refeshing...");location.reload()},5e3)}else{$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} toggle failed.`);$("#addCconfigurationAlertMessage").removeClass("d-none").html(`${name} toggle failed. Please check the following error message:
${res.message}`)}})},500)}else{$(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} adding failed.`);$("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason)}};ajaxPostJSON("/api/addConfiguration",data,done)}}); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index 06ac027e..1f311c7b 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -19,7 +19,9 @@
-
+
+

+                    
CONFIGURATION @@ -29,8 +31,8 @@ SWITCH
- - + +
@@ -142,9 +144,11 @@
@@ -262,6 +266,29 @@
+
-
- -
+
{% include "tools.html" %} {% include "footer.html" %} diff --git a/src/templates/index.html b/src/templates/index.html index 39ae50a2..3ccb63f3 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -27,8 +27,8 @@ {% if conf == [] %}

You don't have any WireGuard configurations yet. Please check the configuration folder or change it in "Settings". By default the folder is "/etc/wireguard".

{% endif %} - - + + {% for i in conf%}
@@ -56,7 +56,7 @@
- +
{%endfor%} @@ -77,9 +77,6 @@
@@ -162,4 +165,5 @@ {% include "footer.html" %} + \ No newline at end of file diff --git a/src/util.py b/src/util.py index c37edd90..6f95a62f 100644 --- a/src/util.py +++ b/src/util.py @@ -106,7 +106,7 @@ def checkJSONAllParameter(required, data): if len(data) == 0: return False for i in required: - if i not in list(data.keys()): + if i not in list(data.keys()) or len(data[i]) == 0: return False return True From a196dce1fa8ed612bb0691a1b92eb864a6e59071 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Mon, 28 Mar 2022 08:09:28 -0400 Subject: [PATCH 012/214] Removed flask-socketio --- src/dashboard.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index 1bce24c7..760fe2a4 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -24,8 +24,6 @@ import ifcfg from flask import Flask, request, render_template, redirect, url_for, session, jsonify, g from flask_qrcode import QRcode from icmplib import ping, traceroute -# TESTING -from flask_socketio import SocketIO # Import other python files from util import * From 337c9bc01e6bf784f4ec299f6015b920dca8560b Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Mon, 28 Mar 2022 15:33:26 -0400 Subject: [PATCH 013/214] Update dashboard.py --- src/dashboard.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/dashboard.py b/src/dashboard.py index 760fe2a4..b640f1db 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -52,7 +52,6 @@ app.config['TEMPLATES_AUTO_RELOAD'] = True # Enable QR Code Generator QRcode(app) -socketio = SocketIO(app) # TODO: use class and object oriented programming From 5af2fff9caac9dacabcc8612256b4d8b67568652 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Tue, 29 Mar 2022 15:11:50 -0400 Subject: [PATCH 014/214] IPv6 configuration IP should be working now --- src/api.py | 3 +++ src/dashboard.py | 17 +++++++++++++++-- src/templates/index.html | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/api.py b/src/api.py index da40482d..1ab44939 100644 --- a/src/api.py +++ b/src/api.py @@ -66,6 +66,9 @@ class addConfiguration: for i in configs: if i['port'] == port: return {"status": False, "reason": f"{port} used by {i['conf']}."} + checkSystem = subprocess.run(f'ss -tulpn | grep :{port} > /dev/null', shell=True) + if checkSystem.returncode != 1: + return {"status": False, "reason": f"Port {port} used by other process in your system."} return good def NameCheck(self, data, configs): diff --git a/src/dashboard.py b/src/dashboard.py index b640f1db..c9c9d4ab 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -607,19 +607,32 @@ def f_available_ips(config_name): """ config_interface = read_conf_file_interface(config_name) if "Address" in config_interface: + available = [] existed = [] conf_address = config_interface['Address'] address = conf_address.split(',') for i in address: add, sub = i.split("/") - existed.append(ipaddress.ip_address(add)) + existed.append(ipaddress.ip_address(add.replace(" ", ""))) peers = g.cur.execute("SELECT allowed_ip FROM " + config_name).fetchall() for i in peers: add = i[0].split(",") for k in add: a, s = k.split("/") existed.append(ipaddress.ip_address(a.strip())) - available = list(ipaddress.ip_network(address[0], False).hosts()) + count = 0 + for i in address: + tmpIP = ipaddress.ip_network(i.replace(" ", ""), False) + if tmpIP.version == 6: + for i in tmpIP.hosts(): + if i not in existed: + available.append(i) + count += 1 + if count > 100: + break + else: + available = available + list(tmpIP.hosts()) + for i in existed: try: available.remove(i) diff --git a/src/templates/index.html b/src/templates/index.html index 3ccb63f3..783c996a 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -9,7 +9,7 @@ {% include "navbar.html" %}
{% include "sidebar.html" %} -
+

Home

From c8ca9ef7ab499f4a1ed411d465433f49d416ca9b Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Wed, 30 Mar 2022 00:54:11 -0400 Subject: [PATCH 015/214] Minimized some js code --- src/static/js/configuration.js | 79 +++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index b1835e92..71f5e44a 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -303,11 +303,15 @@ let peers = []; let total_s = 0; total_r += peer.cumu_receive; total_s += peer.cumu_sent; + + let spliter = '
'; let peer_name = `
${peer.name === "" ? "Untitled" : peer.name}
-
+
+ +
`; let peer_transfer = `
@@ -318,10 +322,31 @@ let peers = []; ${roundN(peer.total_sent + total_s, 4)} GB

`; - let peer_key = '
PEERCLICK TO COPY
' + peer.id + '
'; - let peer_allowed_ip = '
ALLOWED IP
' + peer.allowed_ip + '
'; - let peer_latest_handshake = '
LATEST HANDSHAKE
' + peer.latest_handshake + '
'; - let peer_endpoint = '
END POINT
' + peer.endpoint + '
'; + let peer_key = + `
+ + PEER + CLICK TO COPY + +
${peer.id}
+
`; + let peer_allowed_ip = ` +
+ + ALLOWED IP + +
${peer.allowed_ip}
+
`; + let peer_latest_handshake = + `
+ LATEST HANDSHAKE +
${peer.latest_handshake}
+
`; + let peer_endpoint = + `
+ END POINT +
${peer.endpoint}
+
`; let peer_control = `

@@ -336,27 +361,31 @@ let peers = []; `; if (peer.private_key !== "") { - peer_control += ''; + peer_control += + ``; } - peer_control += '
'; - let html = '
' + - '
' + - '
' + - '
' + - peer_name + - spliter + - peer_transfer + - peer_key + - peer_allowed_ip + - peer_latest_handshake + - spliter + - peer_endpoint + - spliter + - peer_control + - '
' + - '
' + - '
' + - '
'; + peer_control += ''; + let html = + `
+
+
+
` + + peer_name + + spliter + + peer_transfer + + peer_key + + peer_allowed_ip + + peer_latest_handshake + + spliter + + peer_endpoint + + spliter + + peer_control + + `
`; result += html; }); response.lock_access_peers.forEach(function(peer) { From 71a6a36a542242ae9f4c73ea615c106616bd0a58 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Wed, 30 Mar 2022 14:06:05 -0400 Subject: [PATCH 016/214] Update dashboard.css --- src/static/css/dashboard.css | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index c7934580..9341d27a 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -449,14 +449,14 @@ main { /*padding: 0.6rem 0.9em;*/ } -#username, -#password { +.login-box #username, +.login-box #password { padding: 0.6rem calc( 0.9rem + 32px); height: inherit; } -label[for="username"], -label[for="password"] { +.login-box label[for="username"], +.login-box label[for="password"] { font-size: 1rem; margin: 0 !important; transform: translateY(30px) translateX(16px); From 46da285831e93d28235c14fe846a42309306c451 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Wed, 30 Mar 2022 14:20:08 -0400 Subject: [PATCH 017/214] Adjusted js --- src/static/js/configuration.js | 26 ++++++++++++++++++++++---- src/templates/configuration.html | 13 +++++-------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 71f5e44a..4c60d707 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -408,10 +408,28 @@ let peers = []; ${roundN(peer.total_sent + total_s, 4)} GB

`; - let peer_key = '
PEERCLICK TO COPY
' + peer.id + '
'; - let peer_allowed_ip = '
ALLOWED IP
' + peer.allowed_ip + '
'; - let peer_latest_handshake = '
LATEST HANDSHAKE
' + peer.latest_handshake + '
'; - let peer_endpoint = '
END POINT
' + peer.endpoint + '
'; + let peer_key = + `
+ + PEERCLICK TO COPY + +
${peer.id}/samp>
+
`; + let peer_allowed_ip = + `
+ ALLOWED IP +
${peer.allowed_ip}
+
`; + let peer_latest_handshake = + `
+ LATEST HANDSHAKE +
${peer.latest_handshake}
+
`; + let peer_endpoint = + `
+ END POINT +
${peer.endpoint}
+
`; let peer_control = `

diff --git a/src/templates/configuration.html b/src/templates/configuration.html index 1f311c7b..e8db51a5 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -96,15 +96,15 @@
-
+
-
+
-
+
diff --git a/src/wgd.sh b/src/wgd.sh old mode 100644 new mode 100755 From 179da2ac05ed1f3f73db66c9b68d29768efbc1c3 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Wed, 6 Apr 2022 20:59:23 -0400 Subject: [PATCH 019/214] Finished peer data usage chart --- src/api.py | 25 + src/dashboard.py | 37 +- src/static/css/dashboard.css | 35 +- src/static/js/configuration.js | 1101 ++++------------------ src/static/js/configurationTool.js | 880 +++++++++++++++++ src/static/js/configurationsTools.js | 0 src/static/js/configurationsTools.min.js | 0 src/templates/configuration.html | 43 +- 8 files changed, 1190 insertions(+), 931 deletions(-) create mode 100644 src/static/js/configurationTool.js delete mode 100644 src/static/js/configurationsTools.js delete mode 100644 src/static/js/configurationsTools.min.js diff --git a/src/api.py b/src/api.py index 1ab44939..0acc8d10 100644 --- a/src/api.py +++ b/src/api.py @@ -1,4 +1,6 @@ import ipaddress, subprocess, datetime, os, util + +from flask import jsonify from util import * notEnoughParameter = {"status": False, "reason": "Please provide all required parameters."} @@ -41,6 +43,29 @@ def togglePeerAccess(data, g): return {"status": False, "reason": str(exc.output.strip())} return good +class managePeer: + def getPeerDataUsage(self, data, cur): + interval = { + "30min": (60 * 30) / 30, + "1h": (60 * 60) / 30, + "6h": (60 * 60 * 6) / 30, + "24h": (60 * 60 * 24) / 30, + "all": "" + } + if data['interval'] not in interval.keys(): + return {"status": False, "reason": "Invalid interval."} + intv = "" + if data['interval'] != "all": + intv = f" LIMIT {int(interval[data['interval']])}" + timeData = cur.execute(f"SELECT total_receive, total_sent, time FROM wg0_transfer WHERE id='{data['peerID']}' ORDER BY time DESC{intv};") + chartData = [] + for i in timeData: + chartData.append({ + "total_receive": i[0], + "total_sent": i[1], + "time": i[2] + }) + return {"status": True, "reason": "", "data": chartData} class addConfiguration: def AddressCheck(self, data): diff --git a/src/dashboard.py b/src/dashboard.py index 8fcfd6b4..0f6f6ace 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -1569,6 +1569,16 @@ def switch_display_mode(mode): # APIs import api +@app.route('/api/getPeerDataUsage', methods=['POST']) +def getPeerDataUsage(): + data = request.get_json() + returnData = {"status": True, "reason": ""} + required = ['peerID', 'config', 'interval'] + if checkJSONAllParameter(required, data): + returnData = api.managePeer.getPeerDataUsage(api.managePeer, data, g.cur) + else: + return jsonify(api.notEnoughParameter) + return jsonify(returnData) @app.route('/api/togglePeerAccess', methods=['POST']) def togglePeerAccess(): @@ -1751,7 +1761,7 @@ def goodbye(): global bgThread stop_thread = True - print("Exiting Python Script!") + print("Stopping background thread") def get_all_transfer_thread(): print("waiting 15 sec ") @@ -1762,8 +1772,9 @@ def get_all_transfer_thread(): db = connect_db() cur = db.cursor() while True: - if stop_thread: - break + print(stop_thread) + # if stop_thread: + # break conf = [] for i in os.listdir(WG_CONF_PATH): if regex_match("^(.{1,}).(conf)$", i): @@ -1809,10 +1820,6 @@ def get_all_transfer_thread(): conf.append(temp) if len(conf) > 0: conf = sorted(conf, key=itemgetter('conf')) - - - print("adding...........") - # l = get_conf_list() for i in conf: print(i['conf']) config_name = i['conf'] @@ -1833,15 +1840,12 @@ def get_all_transfer_thread(): total_receive = cur_i[0][0] cur_total_sent = round(int(data_usage[i][2]) / (1024 ** 3), 4) cur_total_receive = round(int(data_usage[i][1]) / (1024 ** 3), 4) - # if cur_i[0][4] == "running": cumulative_receive = cur_i[0][2] + total_receive cumulative_sent = cur_i[0][3] + total_sent if total_sent <= cur_total_sent and total_receive <= cur_total_receive: total_sent = cur_total_sent total_receive = cur_total_receive else: - # cumulative_receive = cur_i[0][2] + total_receive - # cumulative_sent = cur_i[0][3] + total_sent cur.execute("UPDATE %s SET cumu_receive = %f, cumu_sent = %f, cumu_data = %f WHERE id = '%s'" % (config_name, round(cumulative_receive, 4), round(cumulative_sent, 4), round(cumulative_sent + cumulative_receive, 4), data_usage[i][0])) @@ -1857,11 +1861,10 @@ def get_all_transfer_thread(): VALUES ('{data_usage[i][0]}', {round(total_receive, 4)}, {round(total_sent, 4)}, {round(total_receive + total_sent, 4)},{round(cumulative_receive, 4)}, {round(cumulative_sent, 4)}, {round(cumulative_sent + cumulative_receive, 4)}, '{now_string}') ''') - # get_transfer(i['conf']) db.commit() except subprocess.CalledProcessError: - print(i['conf'] + " stopped") - time.sleep(15) + pass + time.sleep(30) except KeyboardInterrupt: return True """ @@ -1973,8 +1976,6 @@ def run_dashboard(): """ Get host and port for web-server """ - - def get_host_bind(): init_dashboard() config = configparser.ConfigParser(strict=False) @@ -1983,7 +1984,6 @@ def get_host_bind(): app_port = config.get("Server", "app_port") return app_ip, app_port - if __name__ == "__main__": init_dashboard() UPDATE = check_update() @@ -1998,7 +1998,8 @@ if __name__ == "__main__": global bgThread global stop_thread stop_thread = False - bgThread = threading.Thread(target=get_all_transfer_thread) + bgThread.daemon = True bgThread.start() - app.run(host=app_ip, debug=False, port=app_port) + + app.run(host=app_ip, debug=False, port=app_port) \ No newline at end of file diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 9341d27a..7bb61b59 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -169,7 +169,8 @@ body { .btn-control { border: none !important; - padding: 0 1rem 0 0; + padding: 0; + margin: 0 1rem 0 0; } .btn-control:active, @@ -221,10 +222,14 @@ body { color: #6c757d } -.btn-setting-peer:hover { +.btn-control.btn-outline-primary:hover{ color: #007bff } +/* .btn-setting-peer:hover { + color: #007bff +} */ + .btn-download-peer:hover { color: #17a2b8; } @@ -799,4 +804,28 @@ pre.index-alert { /*.conf_card .card-body .row .card-col{*/ /* margin-bottom: 0.5rem;*/ -/*}*/ \ No newline at end of file +/*}*/ + +.peerDataUsageChartContainer{ + min-height: 50vh; + width: 100%; +} + +.peerDataUsageChartControl{ + display: block !important; + margin: 0; +} + +.peerDataUsageChartControl .switchUnit{ + width: 33.3%; +} + +.peerDataUsageChartControl .switchTimePeriod{ + width: 25%; +} + +@media (min-width: 1200px){ + #peerDataUsage .modal-xl { + max-width: 95vw; + } +} diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 4c60d707..7854fe9d 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -4,10 +4,10 @@ */ let peers = []; -(function() { +(function () { /** * Definitions - */ + */ let configuration_name; let configuration_interval; let configuration_timeout = window.localStorage.getItem("configurationTimeout"); @@ -37,6 +37,7 @@ let peers = []; let settingModal = new bootstrap.Modal(document.getElementById('setting_modal'), bootstrapModalConfig); let deleteModal = new bootstrap.Modal(document.getElementById('delete_modal'), bootstrapModalConfig); let configurationDeleteModal = new bootstrap.Modal(document.getElementById('configuration_delete_modal'), bootstrapModalConfig); + let peerDataUsageModal = new bootstrap.Modal(document.getElementById('peerDataUsage'), bootstrapModalConfig); $("[data-toggle='tooltip']").tooltip(); $("[data-toggle='popover']").popover(); @@ -62,21 +63,27 @@ let peers = []; data: { labels: [], datasets: [{ - label: 'Data Sent', - data: [], - stroke: '#FFFFFF', - borderColor: '#28a745', - tension: 0.1, - borderWidth: 2 - }, - { - label: 'Data Received', - data: [], - stroke: '#FFFFFF', - borderColor: '#007bff', - tension: 0.1, - borderWidth: 2 - } + label: 'Data Sent', + data: [], + stroke: '#FFFFFF', + borderColor: '#28a745', + backgroundColor: '#28a7452b', + pointRadius: 1, + fill: {target: 'origin'}, + tension: 0, + borderWidth: 1 + }, + { + label: 'Data Received', + data: [], + stroke: '#FFFFFF', + borderColor: '#007bff', + backgroundColor: '#007bff2b', + pointRadius: 1, + fill: {target: 'origin'}, + tension: 0, + borderWidth: 1 + } ] }, options: { @@ -88,7 +95,7 @@ let peers = []; min: 0, ticks: { min: 0, - callback: function(value, index, ticks) { + callback: function (value, index, ticks) { return `${value} ${chartUnit}`; } } @@ -97,7 +104,7 @@ let peers = []; plugins: { tooltip: { callbacks: { - label: function(context) { + label: function (context) { return `${context.dataset.label}: ${context.parsed.y} ${chartUnit}`; } } @@ -110,11 +117,11 @@ let peers = []; $totalDataUsageChartObj.css("width", "100%"); totalDataUsageChartObj.width = $totalDataUsageChartObj.parent().width(); totalDataUsageChartObj.resize(); - $(window).on("resize", function() { + $(window).on("resize", function () { totalDataUsageChartObj.resize(); }); - $(".fullScreen").on("click", function() { + $(".fullScreen").on("click", function () { let $chartContainer = $(".chartContainer"); if ($chartContainer.hasClass("fullScreen")) { $(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"); @@ -127,9 +134,9 @@ let peers = []; }); let mul = 1; - $(".switchUnit").on("click", function() { + $(".switchUnit").on("click", function () { $(".switchUnit").removeClass("active"); - $(this).addClass("active"); + $(`.switchUnit[data-unit=${$(this).data('unit')}]`).addClass("active"); if ($(this).data('unit') !== chartUnit) { switch ($(this).data('unit')) { case "GB": @@ -164,9 +171,99 @@ let peers = []; totalDataUsageChartObj.data.datasets[0].data = totalDataUsageChartObj.data.datasets[0].data.map(x => x * mul); totalDataUsageChartObj.data.datasets[1].data = totalDataUsageChartObj.data.datasets[1].data.map(x => x * mul); totalDataUsageChartObj.update(); + + peerDataUsageChartObj.data.datasets[0].data = peerDataUsageChartObj.data.datasets[0].data.map(x => x * mul); + peerDataUsageChartObj.data.datasets[1].data = peerDataUsageChartObj.data.datasets[1].data.map(x => x * mul); + peerDataUsageChartObj.update(); } }); + /** + * Peer Chart + * @param {Any} response + */ + let peerTimePeriod = window.localStorage.peerTimePeriod; + let peerTimePeriodAvailable = ["30min", "1h", "6h", "24h", "all"]; + + if (peerTimePeriod === null || !peerTimePeriodAvailable.includes(peerTimePeriod)) { + window.localStorage.setItem("peerTimePeriod", "30min"); + $('.switchTimePeriod[data-time="30min"]').addClass("active"); + } else { + $(`.switchTimePeriod[data-time="${peerTimePeriod}"]`).addClass("active"); + } + peerTimePeriod = window.localStorage.getItem("peerTimePeriod"); + + + const peerDataUsageChart = document.getElementById('peerDataUsageChartObj').getContext('2d'); + const peerDataUsageChartObj = new Chart(peerDataUsageChart, { + type: 'line', + data: { + labels: [], + datasets: [{ + label: 'Data Sent', + data: [], + stroke: '#FFFFFF', + borderColor: '#28a745', + backgroundColor: '#28a7452b', + pointRadius: 0, + fill: {target: 'origin'}, + tension: 0, + borderWidth: 1 + }, + { + label: 'Data Received', + data: [], + stroke: '#FFFFFF', + borderColor: '#007bff', + backgroundColor: '#007bff2b', + pointRadius: 0, + fill: {target: 'origin'}, + tension: 0, + borderWidth: 1 + } + ] + }, + options: { + interaction: { + mode: 'nearest' + }, + // showLine: false, + maintainAspectRatio: false, + showScale: false, + responsive: false, + scales: { + y: { + min: 0, + ticks: { + min: 0, + callback: function (value, index, ticks) { + return `${value} ${chartUnit}`; + } + } + }, + x: { + display: false + } + }, + plugins: { + tooltip: { + callbacks: { + label: function (context) { + return `${context.dataset.label}: ${context.parsed.y} ${chartUnit}`; + } + } + } + } + } + }); + + let $peerDataUsageChartObj = $("#peerDataUsageChartObj"); + $peerDataUsageChartObj.css("width", "100%"); + peerDataUsageChartObj.width = $peerDataUsageChartObj.parent().width(); + peerDataUsageChartObj.resize(); + $(window).on("resize", function () { + peerDataUsageChartObj.resize(); + }); /** * To show alert on the configuration page @@ -197,7 +294,7 @@ let peers = []; } let firstLoading = true; - $(".nav-conf-link").on("click", function(e) { + $(".nav-conf-link").on("click", function (e) { e.preventDefault(); if (configuration_name !== $(this).data("conf-id")) { firstLoading = true; @@ -225,7 +322,7 @@ let peers = []; if (response.checked === "checked") { $conf_status_btn.prop("checked", true) - }else{ + } else { $conf_status_btn.prop("checked", false) } $conf_status_btn.data("conf-id", configuration_name) @@ -281,8 +378,8 @@ let peers = []; document.querySelector("#conf_address").innerHTML = response.conf_address; let delay = 0; let h6 = $(".info h6"); - for (let i = 0; i < h6.length; i++){ - setTimeout(function(){ + for (let i = 0; i < h6.length; i++) { + setTimeout(function () { $(h6[i]).removeClass("info_loading"); }, delay) delay += 40 @@ -298,13 +395,13 @@ let peers = []; document.querySelector(".peer_list").innerHTML = `

Oops! No peers found ‘︿’

`; } else { let mode = display_mode === "list" ? "col-12" : "col-sm-6 col-lg-4"; - response.peer_data.forEach(function(peer) { + response.peer_data.forEach(function (peer) { let total_r = 0; let total_s = 0; total_r += peer.cumu_receive; total_s += peer.cumu_sent; - - + + let spliter = '
'; let peer_name = `
@@ -322,7 +419,7 @@ let peers = []; ${roundN(peer.total_sent + total_s, 4)} GB

`; - let peer_key = + let peer_key = `
PEER @@ -337,12 +434,12 @@ let peers = [];
${peer.allowed_ip}
`; - let peer_latest_handshake = + let peer_latest_handshake = `
LATEST HANDSHAKE
${peer.latest_handshake}
`; - let peer_endpoint = + let peer_endpoint = `
END POINT
${peer.endpoint}
@@ -354,14 +451,18 @@ let peers = []; + + `; if (peer.private_key !== "") { - peer_control += + peer_control += ``; } peer_control += '
'; - let html = + let html = `
` + - peer_name + - spliter + - peer_transfer + - peer_key + - peer_allowed_ip + - peer_latest_handshake + - spliter + - peer_endpoint + - spliter + - peer_control + + peer_name + + spliter + + peer_transfer + + peer_key + + peer_allowed_ip + + peer_latest_handshake + + spliter + + peer_endpoint + + spliter + + peer_control + `
`; result += html; }); - response.lock_access_peers.forEach(function(peer) { + response.lock_access_peers.forEach(function (peer) { let total_r = 0; let total_s = 0; total_r += peer.cumu_receive; @@ -408,24 +509,24 @@ let peers = []; ${roundN(peer.total_sent + total_s, 4)} GB

`; - let peer_key = + let peer_key = `
PEERCLICK TO COPY
${peer.id}/samp>
`; - let peer_allowed_ip = + let peer_allowed_ip = `
ALLOWED IP
${peer.allowed_ip}
`; - let peer_latest_handshake = + let peer_latest_handshake = `
LATEST HANDSHAKE
${peer.latest_handshake}
`; - let peer_endpoint = + let peer_endpoint = `
END POINT
${peer.endpoint}
@@ -474,9 +575,9 @@ let peers = []; $add_peer.setAttribute("disabled", "disabled"); $add_peer.innerHTML = `Adding ${$new_add_amount.val()} peers...`; let $new_add_DNS = $("#new_add_DNS"); - $new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val())); + $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(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val())); + $new_add_endpoint_allowed_ip.val(configurations.cleanIp($new_add_endpoint_allowed_ip.val())); let $new_add_MTU = $("#new_add_MTU"); let $new_add_keep_alive = $("#new_add_keep_alive"); let $enable_preshare_key = $("#enable_preshare_key"); @@ -503,20 +604,20 @@ let peers = []; "keys": keys, "amount": $new_add_amount.val() }), - success: function(response) { + 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 { - window.configurations.loadPeers(""); + configurations.loadPeers(""); data_list.forEach((ele) => ele.removeAttr("disabled")); $("#add_peer_form").trigger("reset"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; - window.configurations.showToast($new_add_amount.val() + " peers added successful!"); - window.configurations.addModal().toggle(); + configurations.showToast($new_add_amount.val() + " peers added successful!"); + configurations.addModal().toggle(); } } }); @@ -544,31 +645,31 @@ let peers = []; "Content-Type": "application/json" }, data: JSON.stringify({ "action": "delete", "peer_ids": peer_ids }), - success: function(response) { + success: function (response) { if (response !== "true") { - if (window.configurations.deleteModal()._isShown) { + if (configurations.deleteModal()._isShown) { $("#remove_peer_alert").html(response + $("#add_peer_alert").html()) .removeClass("d-none"); $("#delete_peer").removeAttr("disabled").html("Delete"); } - if (window.configurations.deleteBulkModal()._isShown) { + if (configurations.deleteBulkModal()._isShown) { let $bulk_remove_peer_alert = $("#bulk_remove_peer_alert"); $bulk_remove_peer_alert.html(response + $bulk_remove_peer_alert.html()) .removeClass("d-none"); $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); } } else { - if (window.configurations.deleteModal()._isShown) { - window.configurations.deleteModal().toggle(); + if (configurations.deleteModal()._isShown) { + configurations.deleteModal().toggle(); } - if (window.configurations.deleteBulkModal()._isShown) { + if (configurations.deleteBulkModal()._isShown) { $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); $("#selected_peer_list").html(''); $(".delete-bulk-peer-item.active").removeClass('active'); - window.configurations.deleteBulkModal().toggle(); + configurations.deleteBulkModal().toggle(); } - window.configurations.loadPeers($('#search_peer_textbox').val()); - window.configurations.showToast(`Deleted ${peer_ids.length} peers`) + configurations.loadPeers($('#search_peer_textbox').val()); + configurations.showToast(`Deleted ${peer_ids.length} peers`) $("#delete_peer").removeAttr("disabled").html("Delete"); } } @@ -580,7 +681,7 @@ let peers = []; */ function noResponding(message = "Opps!
I can't connect to the server.") { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("active")); - setTimeout(function() { + setTimeout(function () { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("show")); document.querySelector("#right_body").classList.add("no-responding"); document.querySelector(".navbar").classList.add("no-responding"); @@ -595,7 +696,7 @@ let peers = []; document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("show")); document.querySelector("#right_body").classList.remove("no-responding"); document.querySelector(".navbar").classList.remove("no-responding"); - setTimeout(function() { + setTimeout(function () { document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("active")); }, 1010); } @@ -604,7 +705,7 @@ let peers = []; * Set configuration refresh Interval */ function setConfigurationInterval() { - configuration_interval = setInterval(function() { + configuration_interval = setInterval(function () { loadPeers($('#search_peer_textbox').val()); }, configuration_timeout); } @@ -626,7 +727,7 @@ let peers = []; .css("background", "linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)") .css("width", "25%"); - setTimeout(function() { + setTimeout(function () { stillLoadingProgressBar(); }, 300); } @@ -643,7 +744,7 @@ let peers = []; */ function endProgressBar() { $progress_bar.css("transition", "0.3s ease-in-out").css("width", "100%"); - setTimeout(function() { + setTimeout(function () { $progress_bar.css("opacity", "0"); }, 250); } @@ -674,10 +775,10 @@ let peers = []; method: "GET", url: `/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`, headers: { "Content-Type": "application/json" } - }).done(function(response) { + }).done(function (response) { console.log(response); parsePeers(response); - }).fail(function() { + }).fail(function () { noResponding(); good = false; }); @@ -691,14 +792,14 @@ let peers = []; let seconds = (d2 - d1); time += seconds; count += 1; - window.console.log(`Average time: ${time/count}ms`); + window.console.log(`Average time: ${time / count}ms`); $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); removeNoResponding(); peers = response.data.peer_data; configurationAlert(response.data); configurationHeader(response.data); configurationPeers(response.data); - + $(".dot.dot-running").attr("title", "Peer Connected").tooltip(); $(".dot.dot-stopped").attr("title", "Peer Disconnected").tooltip(); $("i[data-toggle='tooltip']").tooltip(); @@ -713,20 +814,20 @@ let peers = []; } } - function removeAllTooltips(){ + function removeAllTooltips() { $(".tooltip").remove(); } - function toggleAccess(peerID){ + function toggleAccess(peerID) { $.ajax({ url: "/api/togglePeerAccess", method: "POST", - headers: {"Content-Type": "application/json"}, - data: JSON.stringify({"peerID": peerID, "config": configuration_name}) - }).done(function(res){ - if(res.status){ + headers: { "Content-Type": "application/json" }, + data: JSON.stringify({ "peerID": peerID, "config": configuration_name }) + }).done(function (res) { + if (res.status) { loadPeers($('#search_peer_textbox').val()); - }else{ + } else { showToast(res.reason); } }); @@ -751,7 +852,7 @@ let peers = []; let numberToast = 0; function showToast(msg) { $(".toastContainer").append( - `
- +
Delete Peers @@ -154,6 +154,46 @@
+ - - - - - - - - + {% include "modal.html" %}
{% include "tools.html" %} diff --git a/src/templates/footer.html b/src/templates/footer.html index 9c4c4e6a..f03d9472 100644 --- a/src/templates/footer.html +++ b/src/templates/footer.html @@ -1,3 +1,4 @@ + \ No newline at end of file diff --git a/src/templates/header.html b/src/templates/header.html index 12fed9ad..4dd70d1b 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -16,4 +16,5 @@ + \ No newline at end of file diff --git a/src/templates/index.html b/src/templates/index.html index 783c996a..95329a06 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -27,9 +27,7 @@ {% if conf == [] %}

You don't have any WireGuard configurations yet. Please check the configuration folder or change it in "Settings". By default the folder is "/etc/wireguard".

{% endif %} - - - {% for i in conf%} + {% for i in conf %}
@@ -56,7 +54,6 @@
-
{%endfor%} diff --git a/src/templates/modal.html b/src/templates/modal.html new file mode 100644 index 00000000..0acbab0c --- /dev/null +++ b/src/templates/modal.html @@ -0,0 +1,357 @@ + + + + + + + + \ No newline at end of file diff --git a/src/templates/navbar.html b/src/templates/navbar.html index 1915ad6a..261dd19d 100644 --- a/src/templates/navbar.html +++ b/src/templates/navbar.html @@ -1,10 +1,11 @@
-
-
\ No newline at end of file +
+
+ diff --git a/src/templates/settings.html b/src/templates/settings.html index 1f6c267d..c7e2ebc7 100644 --- a/src/templates/settings.html +++ b/src/templates/settings.html @@ -197,8 +197,9 @@ countdown--; }, 1000) $.post('/update_wg_conf_path', $('.update_wg_conf_path').serialize()) - }); + $(".bottomNavSettings").addClass("active"); + \ No newline at end of file diff --git a/src/templates/sidebar.html b/src/templates/sidebar.html index 0967abb7..bc4e6325 100644 --- a/src/templates/sidebar.html +++ b/src/templates/sidebar.html @@ -1,3 +1,76 @@ +
+
+ +
+ + +
-
diff --git a/src/templates/modal.html b/src/templates/modal.html index 0acbab0c..c60caefb 100644 --- a/src/templates/modal.html +++ b/src/templates/modal.html @@ -354,4 +354,109 @@
+
+ \ No newline at end of file diff --git a/src/templates/sidebar.html b/src/templates/sidebar.html index bc4e6325..3f24d2bf 100644 --- a/src/templates/sidebar.html +++ b/src/templates/sidebar.html @@ -62,7 +62,6 @@ -
From 2b90a2eed28af374fb7c8fd980e497aaa102cdef Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Thu, 21 Apr 2022 15:11:35 -0400 Subject: [PATCH 023/214] Update header.html --- src/templates/header.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/templates/header.html b/src/templates/header.html index 85f825f4..52684ac2 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -14,7 +14,9 @@ + + From 23491f1e8c8ea103e19bc6af98607d7b3d6b1504 Mon Sep 17 00:00:00 2001 From: LeoEricson Date: Thu, 21 Apr 2022 21:30:55 +0000 Subject: [PATCH 024/214] Add dark theme --- src/static/css/theme/dark.css | 385 ++++++++++++++++++++++-------- src/static/css/theme/dark.css.map | 1 + src/static/css/theme/dark.min.css | 1 + src/static/css/theme/dark.scss | 365 ++++++++++++++++++++++++++++ src/templates/header.html | 4 +- 5 files changed, 653 insertions(+), 103 deletions(-) create mode 100644 src/static/css/theme/dark.css.map create mode 100644 src/static/css/theme/dark.min.css create mode 100644 src/static/css/theme/dark.scss diff --git a/src/static/css/theme/dark.css b/src/static/css/theme/dark.css index c47e957a..296a89e9 100644 --- a/src/static/css/theme/dark.css +++ b/src/static/css/theme/dark.css @@ -1,123 +1,306 @@ -:root{ - --blue: #3f9eff; - --dark1: #1C1C1E; - --dark2: #232323; - --dark3: #3f3f3f; +:root { + --green: hsl(120deg, 30%, 50%) !important; + --blue: hsl(235deg, 60%, 60%) !important; + --red: hsl(0deg, 60%, 60%) !important; + --magenta: hsl(315deg, 60%, 60%) !important; } -a{ - color: var(--blue); +body { + background: #222222; + color: hsl(0deg, 0%, 80%); } -body{ - background-color: var(--dark1); - color: #ffffff; +.btn-primary { + color: hsl(0deg, 0%, 90%) !important; + border-color: hsl(235deg, 60%, 60%) !important; + background: hsl(235deg, 60%, 60%) !important; +} +.btn-primary:hover { + background-color: hsl(235deg, 60%, 50%) !important; + border-color: hsl(235deg, 60%, 50%) !important; } -hr{ - border-top: 1px solid rgb(255 255 255 / 10%); +.btn-outline-primary { + color: hsl(235deg, 60%, 60%) !important; + border-color: hsl(235deg, 60%, 60%) !important; + background: transparent !important; } - -/* Color */ - -.bg-dark{ - background-color: #232323!important; +.btn-outline-primary:hover, .btn-outline-primary.active { + color: hsl(0deg, 0%, 90%) !important; } - -.text-primary{ - color: var(--blue) !important; +.btn-outline-primary.active { + background-color: hsl(235deg, 60%, 60%) !important; + border-color: hsl(235deg, 60%, 60%) !important; } - -/* Form Related */ - -.form-control{ - color: #ffffff; - background-color: #232323; - border: 1px solid #686868; -} - -.form-control:focus { - color: #ffffff; - background-color: #232323; - border-color: #686868; - outline: 0; - box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.50); -} - -.form-control:disabled, .form-control[readonly]{ - background-color: #525252; - opacity: 1; - color: #a5a5a5; -} - -.custom-control-label::before{ - background-color: transparent; -} - -/* Side Bar */ - -.sidebar{ - background-color: #232323 !important; -} - -.sidebar .nav-link, .bottomNavContainer .nav-link{ - color: #dddddd; -} - -.sidebar .nav-link.active, .bottomNavContainer .nav-link.active{ - color: var(--blue) !important; -} - -.nav-link:hover{ - background-color: #3f3f3f; -} - -.card{ - background-color: #232323; -} - - -/* Button Related */ - -.btn-outline-primary{ - color: var(--blue); - border-color: var(--blue); -} - .btn-outline-primary:hover { - color: #fff; - background-color: var(--blue); - border-color: var(--blue); + background-color: hsl(235deg, 60%, 50%) !important; + border-color: hsl(235deg, 60%, 50%) !important; } -.btn-outline-primary:not(:disabled):not(.disabled).active, .btn-outline-primary:not(:disabled):not(.disabled):active, .show>.btn-outline-primary.dropdown-toggle{ - background-color: var(--blue); - border-color: var(--blue); +.btn-success { + color: hsl(0deg, 0%, 90%) !important; + border-color: hsl(120deg, 30%, 50%) !important; + background: hsl(120deg, 30%, 50%) !important; +} +.btn-success:hover { + background-color: hsl(120deg, 30%, 40%) !important; + border-color: hsl(120deg, 30%, 40%) !important; } - -/* Configuration Card (index.html) */ -.conf_card:hover{ - border-color: var(--blue); +.btn-outline-success { + color: hsl(120deg, 30%, 50%) !important; + border-color: hsl(120deg, 30%, 50%) !important; + background: transparent !important; +} +.btn-outline-success:hover, .btn-outline-success.active { + color: hsl(0deg, 0%, 90%) !important; +} +.btn-outline-success.active { + background-color: hsl(120deg, 30%, 50%) !important; + border-color: hsl(120deg, 30%, 50%) !important; +} +.btn-outline-success:hover { + background-color: hsl(120deg, 30%, 40%) !important; + border-color: hsl(120deg, 30%, 40%) !important; } -/* Modal */ -.modal-content{ - background-color: var(--dark1); +.btn-danger { + color: hsl(0deg, 0%, 90%) !important; + border-color: hsl(0deg, 60%, 60%) !important; + background: hsl(0deg, 60%, 60%) !important; +} +.btn-danger:hover { + background-color: hsl(0deg, 60%, 50%) !important; + border-color: hsl(0deg, 60%, 50%) !important; } -.modal-header, .modal-footer{ - border-color:rgb(255 255 255 / 10%);; +.btn-outline-danger { + color: hsl(0deg, 60%, 60%) !important; + border-color: hsl(0deg, 60%, 60%) !important; + background: transparent !important; +} +.btn-outline-danger:hover, .btn-outline-danger.active { + color: hsl(0deg, 0%, 90%) !important; +} +.btn-outline-danger.active { + background-color: hsl(0deg, 60%, 60%) !important; + border-color: hsl(0deg, 60%, 60%) !important; +} +.btn-outline-danger:hover { + background-color: hsl(0deg, 60%, 50%) !important; + border-color: hsl(0deg, 60%, 50%) !important; } -/* List Group Item */ -.list-group-item{ - background-color: var(--dark2); - color: white; +.btn-secondary { + color: hsl(0deg, 0%, 90%) !important; + border-color: #424242 !important; + background: #424242 !important; +} +.btn-secondary:hover { + background-color: #383838 !important; + border-color: #383838 !important; } -.list-group-item:hover{ - color: white; - background-color: var(--dark3); - border-color: var(--dark3); -} \ No newline at end of file +.btn-outline-secondary { + color: #424242 !important; + border-color: #424242 !important; + background: transparent !important; +} +.btn-outline-secondary:hover, .btn-outline-secondary.active { + color: hsl(0deg, 0%, 90%) !important; +} +.btn-outline-secondary.active { + background-color: #424242 !important; + border-color: #424242 !important; +} +.btn-outline-secondary:hover { + background-color: #383838 !important; + border-color: #383838 !important; +} + +.btn-control.btn-lock-peer.lock { + color: hsl(0deg, 60%, 60%) !important; +} +.btn-control.btn-lock-peer.lock:hover { + color: hsl(0deg, 60%, 50%) !important; +} +.btn-control:hover { + background-color: transparent !important; +} +.btn-control:hover.btn-outline-primary { + color: hsl(235deg, 60%, 50%) !important; +} +.btn-control:hover.btn-outline-success { + color: hsl(120deg, 30%, 40%) !important; +} +.btn-control:hover.btn-outline-danger { + color: hsl(0deg, 60%, 50%) !important; +} +.btn-control:hover.btn-outline-secondary { + color: #383838 !important; +} + +.form-control { + background: #272727 !important; + border-color: transparent !important; + color: hsl(0deg, 0%, 80%) !important; +} + +.card .form-control { + background: #2c2c2c !important; +} + +.sidebar .nav-link, +.bottomNavContainer .nav-link { + color: hsl(0deg, 0%, 80%); +} +.sidebar .nav-link:hover, +.bottomNavContainer .nav-link:hover { + background: #222222; +} + +nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse, +.navbar-brand, +.bg-dark { + background-color: #1e1e1e !important; + background: #1e1e1e !important; +} + +.card { + background: #272727; +} + +.text-muted { + color: hsl(0deg, 0%, 50%) !important; +} + +.text-danger { + color: hsl(0deg, 60%, 60%) !important; +} + +.text-success { + color: hsl(120deg, 30%, 50%) !important; +} + +.text-primary { + color: hsl(235deg, 60%, 60%) !important; +} + +.text-info { + color: hsl(190deg, 60%, 60%) !important; +} + +a.text-success:focus, +a.text-success:hover { + color: hsl(120deg, 30%, 40%) !important; +} + +a.text-danger:focus, +a.text-danger:hover { + color: hsl(0deg, 60%, 50%) !important; +} + +a.text-info:focus, +a.text-info:hover { + color: hsl(190deg, 60%, 50%) !important; +} + +.dot-running { + background-color: hsl(120deg, 30%, 50%) !important; +} + +.card-running { + border-color: hsl(120deg, 30%, 50%); +} + +.toggle--switch:checked + .toggleLabel::before { + background-color: hsl(235deg, 60%, 60%) !important; +} + +.toggle--switch:checked + .toggleLabel { + background-color: #2e336b !important; + border-color: hsl(235deg, 60%, 60%) !important; +} + +.sidebar .nav-link.active, +.bottomNavContainer .nav-link.active { + color: hsl(235deg, 60%, 60%) !important; +} + +hr { + border-color: #2e2e2e; +} + +.modal-content { + background-color: #222222; +} + +.modal-header, +.modal-footer { + background-color: #1e1e1e; + border-color: #2e2e2e; +} + +code { + color: hsl(315deg, 60%, 60%); +} + +.close { + color: hsl(0deg, 0%, 80%); + text-shadow: none; +} +.close:hover { + color: hsl(0deg, 0%, 70%); +} + +.chartContainer.fullScreen { + background-color: #222222 !important; +} + +.popover { + background-color: #333333 !important; + border: none !important; +} + +.popover-body { + color: hsl(0deg, 0%, 80%) !important; +} + +div.toast { + background-color: #424242 !important; +} +div.toast div.toast-header { + background-color: #333333 !important; + color: hsl(0deg, 0%, 80%) !important; + border-bottom-color: #424242 !important; +} +div.toast div.toast-body { + background-color: #383838 !important; + color: hsl(0deg, 0%, 80%) !important; +} +div.toast div.toast-progressbar { + background-color: hsl(235deg, 60%, 60%) !important; +} + +.bs-popover-auto[x-placement^=right] > .arrow::after, +.bs-popover-right > .arrow::after { + border-right-color: #333333 !important; +} + +.btn-manage-group .setting_btn_menu { + background-color: #2c2c2c !important; +} + +.setting_btn_menu a:hover { + background-color: #333333 !important; +} + +.table { + color: hsl(0deg, 0%, 80%) !important; +} +.table th, +.table td { + border-color: #333333 !important; +} + +/*# sourceMappingURL=dark.css.map */ diff --git a/src/static/css/theme/dark.css.map b/src/static/css/theme/dark.css.map new file mode 100644 index 00000000..d074bca2 --- /dev/null +++ b/src/static/css/theme/dark.css.map @@ -0,0 +1 @@ +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AA8BA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YArCS;EAsCT,OAdS;;;AAiBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;AAAA;EAEE,OA1LS;;AA4LT;AAAA;EACE,YArNO;;;AAyNX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YA/NS;;;AAkOX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAlQU;;;AAqQZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cAzRS;;;AA4RX;EACE,kBAjSS;;;AAoSX;AAAA;EAEE,kBAvSS;EAwST,cAnSS;;;AAsSX;EACE,OAtRY;;;AAyRd;EACE,OAvRS;EAwRT;;AAEA;EACE,OA1RO;;;AA8RX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE","file":"dark.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.min.css b/src/static/css/theme/dark.min.css new file mode 100644 index 00000000..c0ffb171 --- /dev/null +++ b/src/static/css/theme/dark.min.css @@ -0,0 +1 @@ +:root{--green:hsl(120deg,30%,50%)!important;--blue:hsl(235deg,60%,60%)!important;--red:hsl(0deg,60%,60%)!important;--magenta:hsl(315deg,60%,60%)!important}body{background:#222;color:hsl(0deg,0%,80%)}.btn-primary{color:hsl(0deg,0%,90%)!important;border-color:hsl(235deg,60%,60%)!important;background:hsl(235deg,60%,60%)!important}.btn-primary:hover{background-color:hsl(235deg,60%,50%)!important;border-color:hsl(235deg,60%,50%)!important}.btn-outline-primary{color:hsl(235deg,60%,60%)!important;border-color:hsl(235deg,60%,60%)!important;background:transparent!important}.btn-outline-primary:hover,.btn-outline-primary.active{color:hsl(0deg,0%,90%)!important}.btn-outline-primary.active{background-color:hsl(235deg,60%,60%)!important;border-color:hsl(235deg,60%,60%)!important}.btn-outline-primary:hover{background-color:hsl(235deg,60%,50%)!important;border-color:hsl(235deg,60%,50%)!important}.btn-success{color:hsl(0deg,0%,90%)!important;border-color:hsl(120deg,30%,50%)!important;background:hsl(120deg,30%,50%)!important}.btn-success:hover{background-color:hsl(120deg,30%,40%)!important;border-color:hsl(120deg,30%,40%)!important}.btn-outline-success{color:hsl(120deg,30%,50%)!important;border-color:hsl(120deg,30%,50%)!important;background:transparent!important}.btn-outline-success:hover,.btn-outline-success.active{color:hsl(0deg,0%,90%)!important}.btn-outline-success.active{background-color:hsl(120deg,30%,50%)!important;border-color:hsl(120deg,30%,50%)!important}.btn-outline-success:hover{background-color:hsl(120deg,30%,40%)!important;border-color:hsl(120deg,30%,40%)!important}.btn-danger{color:hsl(0deg,0%,90%)!important;border-color:hsl(0deg,60%,60%)!important;background:hsl(0deg,60%,60%)!important}.btn-danger:hover{background-color:hsl(0deg,60%,50%)!important;border-color:hsl(0deg,60%,50%)!important}.btn-outline-danger{color:hsl(0deg,60%,60%)!important;border-color:hsl(0deg,60%,60%)!important;background:transparent!important}.btn-outline-danger:hover,.btn-outline-danger.active{color:hsl(0deg,0%,90%)!important}.btn-outline-danger.active{background-color:hsl(0deg,60%,60%)!important;border-color:hsl(0deg,60%,60%)!important}.btn-outline-danger:hover{background-color:hsl(0deg,60%,50%)!important;border-color:hsl(0deg,60%,50%)!important}.btn-secondary{color:hsl(0deg,0%,90%)!important;border-color:#424242!important;background:#424242!important}.btn-secondary:hover{background-color:#383838!important;border-color:#383838!important}.btn-outline-secondary{color:#424242!important;border-color:#424242!important;background:transparent!important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:hsl(0deg,0%,90%)!important}.btn-outline-secondary.active{background-color:#424242!important;border-color:#424242!important}.btn-outline-secondary:hover{background-color:#383838!important;border-color:#383838!important}.btn-control.btn-lock-peer.lock{color:hsl(0deg,60%,60%)!important}.btn-control.btn-lock-peer.lock:hover{color:hsl(0deg,60%,50%)!important}.btn-control:hover{background-color:transparent!important}.btn-control:hover.btn-outline-primary{color:hsl(235deg,60%,50%)!important}.btn-control:hover.btn-outline-success{color:hsl(120deg,30%,40%)!important}.btn-control:hover.btn-outline-danger{color:hsl(0deg,60%,50%)!important}.btn-control:hover.btn-outline-secondary{color:#383838!important}.form-control{background:#272727!important;border-color:transparent!important;color:hsl(0deg,0%,80%)!important}.card .form-control{background:#2c2c2c!important}.sidebar .nav-link,.bottomNavContainer .nav-link{color:hsl(0deg,0%,80%)}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e!important;background:#1e1e1e!important}.card{background:#272727}.text-muted{color:hsl(0deg,0%,50%)!important}.text-danger{color:hsl(0deg,60%,60%)!important}.text-success{color:hsl(120deg,30%,50%)!important}.text-primary{color:hsl(235deg,60%,60%)!important}.text-info{color:hsl(190deg,60%,60%)!important}a.text-success:focus,a.text-success:hover{color:hsl(120deg,30%,40%)!important}a.text-danger:focus,a.text-danger:hover{color:hsl(0deg,60%,50%)!important}a.text-info:focus,a.text-info:hover{color:hsl(190deg,60%,50%)!important}.dot-running{background-color:hsl(120deg,30%,50%)!important}.card-running{border-color:hsl(120deg,30%,50%)}.toggle--switch:checked + .toggleLabel::before{background-color:hsl(235deg,60%,60%)!important}.toggle--switch:checked + .toggleLabel{background-color:#2e336b!important;border-color:hsl(235deg,60%,60%)!important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:hsl(235deg,60%,60%)!important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:hsl(315deg,60%,60%)}.close{color:hsl(0deg,0%,80%);text-shadow:none}.close:hover{color:hsl(0deg,0%,70%)}.chartContainer.fullScreen{background-color:#222!important}.popover{background-color:#333!important;border:none!important}.popover-body{color:hsl(0deg,0%,80%)!important}div.toast{background-color:#424242!important}div.toast div.toast-header{background-color:#333!important;color:hsl(0deg,0%,80%)!important;border-bottom-color:#424242!important}div.toast div.toast-body{background-color:#383838!important;color:hsl(0deg,0%,80%)!important}div.toast div.toast-progressbar{background-color:hsl(235deg,60%,60%)!important}.bs-popover-auto[x-placement^=right] > .arrow::after,.bs-popover-right > .arrow::after{border-right-color:#333!important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c!important}.setting_btn_menu a:hover{background-color:#333!important}.table{color:hsl(0deg,0%,80%)!important}.table th,.table td{border-color:#333!important} \ No newline at end of file diff --git a/src/static/css/theme/dark.scss b/src/static/css/theme/dark.scss new file mode 100644 index 00000000..c7a27b08 --- /dev/null +++ b/src/static/css/theme/dark.scss @@ -0,0 +1,365 @@ +$grey-100: #1e1e1e; +$grey-200: #222222; +$grey-300: #242424; +$grey-400: #272727; +$grey-500: #2c2c2c; +$grey-600: #2e2e2e; +$grey-700: #333333; +$grey-800: #383838; +$grey-900: #424242; + +$green-400: hsl(120deg, 30%, 40%); +$green-500: hsl(120deg, 30%, 50%); + +$red-400: hsl(0deg, 60%, 50%); +$red-500: hsl(0deg, 60%, 60%); + +$blue-400: hsl(235deg, 60%, 50%); +$blue-500: hsl(235deg, 60%, 60%); + +$cyan-400: hsl(190deg, 60%, 50%); +$cyan-500: hsl(190deg, 60%, 60%); + +$magenta-500: hsl(315deg, 60%, 60%); + +$text-100: hsl(0deg, 0%, 90%); +$text-200: hsl(0deg, 0%, 80%); +$text-300: hsl(0deg, 0%, 70%); +$text-400: hsl(0deg, 0%, 60%); +$text-500: hsl(0deg, 0%, 50%); + +:root { + --green: #{$green-500} !important; + --blue: #{$blue-500} !important; + --red: #{$red-500} !important; + --magenta: #{$magenta-500} !important; +} + +body { + background: $grey-200; + color: $text-200; +} + +.btn-primary { + color: $text-100 !important; + border-color: $blue-500 !important; + background: $blue-500 !important; + + &:hover { + background-color: $blue-400 !important; + border-color: $blue-400 !important; + } +} + +.btn-outline-primary { + color: $blue-500 !important; + border-color: $blue-500 !important; + background: transparent !important; + + &:hover, + &.active { + color: $text-100 !important; + } + + &.active { + background-color: $blue-500 !important; + border-color: $blue-500 !important; + } + + &:hover { + background-color: $blue-400 !important; + border-color: $blue-400 !important; + } +} + +.btn-success { + color: $text-100 !important; + border-color: $green-500 !important; + background: $green-500 !important; + + &:hover { + background-color: $green-400 !important; + border-color: $green-400 !important; + } +} + +.btn-outline-success { + color: $green-500 !important; + border-color: $green-500 !important; + background: transparent !important; + + &:hover, + &.active { + color: $text-100 !important; + } + + &.active { + background-color: $green-500 !important; + border-color: $green-500 !important; + } + + &:hover { + background-color: $green-400 !important; + border-color: $green-400 !important; + } +} + +.btn-danger { + color: $text-100 !important; + border-color: $red-500 !important; + background: $red-500 !important; + + &:hover { + background-color: $red-400 !important; + border-color: $red-400 !important; + } +} + +.btn-outline-danger { + color: $red-500 !important; + border-color: $red-500 !important; + background: transparent !important; + + &:hover, + &.active { + color: $text-100 !important; + } + + &.active { + background-color: $red-500 !important; + border-color: $red-500 !important; + } + + &:hover { + background-color: $red-400 !important; + border-color: $red-400 !important; + } +} + +.btn-secondary { + color: $text-100 !important; + border-color: $grey-900 !important; + background: $grey-900 !important; + + &:hover { + background-color: $grey-800 !important; + border-color: $grey-800 !important; + } +} + +.btn-outline-secondary { + color: $grey-900 !important; + border-color: $grey-900 !important; + background: transparent !important; + + &:hover, + &.active { + color: $text-100 !important; + } + + &.active { + background-color: $grey-900 !important; + border-color: $grey-900 !important; + } + + &:hover { + background-color: $grey-800 !important; + border-color: $grey-800 !important; + } +} + +.btn-control { + &.btn-lock-peer.lock { + color: $red-500 !important; + &:hover { + color: $red-400 !important; + } + } + + &:hover { + background-color: transparent !important; + + &.btn-outline-primary { + color: $blue-400 !important; + } + + &.btn-outline-success { + color: $green-400 !important; + } + + &.btn-outline-danger { + color: $red-400 !important; + } + + &.btn-outline-secondary { + color: $grey-800 !important; + } + } +} + +.form-control { + background: $grey-400 !important; + border-color: transparent !important; + color: $text-200 !important; +} + +.card .form-control { + background: $grey-500 !important; +} + +.sidebar .nav-link, +.bottomNavContainer .nav-link { + color: $text-200; + + &:hover { + background: $grey-200; + } +} + +nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse, +.navbar-brand, +.bg-dark { + background-color: $grey-100 !important; + background: $grey-100 !important; +} + +.card { + background: $grey-400; +} + +.text-muted { + color: $text-500 !important; +} + +.text-danger { + color: $red-500 !important; +} + +.text-success { + color: $green-500 !important; +} + +.text-primary { + color: $blue-500 !important; +} + +.text-info { + color: $cyan-500 !important; +} + +a.text-success:focus, +a.text-success:hover { + color: $green-400 !important; +} + +a.text-danger:focus, +a.text-danger:hover { + color: $red-400 !important; +} + +a.text-info:focus, +a.text-info:hover { + color: $cyan-400 !important; +} + +.dot-running { + background-color: $green-500 !important; +} + +.card-running { + border-color: $green-500; +} + +.toggle--switch:checked + .toggleLabel::before { + background-color: $blue-500 !important; +} +.toggle--switch:checked + .toggleLabel { + background-color: mix($blue-500, #000f) !important; + border-color: $blue-500 !important; +} + +.sidebar .nav-link.active, +.bottomNavContainer .nav-link.active { + color: $blue-500 !important; +} + +hr { + border-color: $grey-600; +} + +.modal-content { + background-color: $grey-200; +} + +.modal-header, +.modal-footer { + background-color: $grey-100; + border-color: $grey-600; +} + +code { + color: $magenta-500; +} + +.close { + color: $text-200; + text-shadow: none; + + &:hover { + color: $text-300; + } +} + +.chartContainer.fullScreen { + background-color: $grey-200 !important; +} + +.popover { + background-color: $grey-700 !important; + border: none !important; +} + +.popover-body { + color: $text-200 !important; +} + +div.toast { + background-color: $grey-900 !important; + + div.toast-header { + background-color: $grey-700 !important; + color: $text-200 !important; + border-bottom-color: $grey-900 !important; + } + + div.toast-body { + background-color: $grey-800 !important; + color: $text-200 !important; + } + + div.toast-progressbar { + background-color: $blue-500 !important; + } +} + +.bs-popover-auto[x-placement^="right"] > .arrow::after, +.bs-popover-right > .arrow::after { + border-right-color: $grey-700 !important; +} + +.btn-manage-group .setting_btn_menu { + background-color: $grey-500 !important; +} + +.setting_btn_menu a:hover { + background-color: $grey-700 !important; +} + +.table { + color: $text-200 !important; + + th, + td { + border-color: $grey-700 !important; + } +} diff --git a/src/templates/header.html b/src/templates/header.html index 52684ac2..bfb8e4fb 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -15,9 +15,9 @@ - + - \ No newline at end of file + From 7f668c16536a590a577fff9c8336e25717861a56 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Fri, 22 Apr 2022 00:12:22 -0400 Subject: [PATCH 025/214] Some changes to dark mode css --- src/static/css/theme/dark.css | 10 +++++++++- src/static/css/theme/dark.css.map | 2 +- src/static/css/theme/dark.min.css | 2 +- src/static/css/theme/dark.min.css.map | 1 + src/static/css/theme/dark.scss | 13 ++++++++++++- 5 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 src/static/css/theme/dark.min.css.map diff --git a/src/static/css/theme/dark.css b/src/static/css/theme/dark.css index 296a89e9..e13ee09f 100644 --- a/src/static/css/theme/dark.css +++ b/src/static/css/theme/dark.css @@ -141,11 +141,15 @@ body { } .form-control { - background: #272727 !important; + background-color: #272727 !important; border-color: transparent !important; color: hsl(0deg, 0%, 80%) !important; } +.form-control:disabled { + color: #777777 !important; +} + .card .form-control { background: #2c2c2c !important; } @@ -303,4 +307,8 @@ div.toast div.toast-progressbar { border-color: #333333 !important; } +.btn-outline-primary.focus, .btn-outline-primary:focus, .btn-primary.focus, .btn-primary:focus { + box-shadow: 0 0 0 0.2rem rgba(144, 153, 255, 0.29) !important; +} + /*# sourceMappingURL=dark.css.map */ diff --git a/src/static/css/theme/dark.css.map b/src/static/css/theme/dark.css.map index d074bca2..8e752c31 100644 --- a/src/static/css/theme/dark.css.map +++ b/src/static/css/theme/dark.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AA8BA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YArCS;EAsCT,OAdS;;;AAiBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;AAAA;EAEE,OA1LS;;AA4LT;AAAA;EACE,YArNO;;;AAyNX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YA/NS;;;AAkOX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAlQU;;;AAqQZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cAzRS;;;AA4RX;EACE,kBAjSS;;;AAoSX;AAAA;EAEE,kBAvSS;EAwST,cAnSS;;;AAsSX;EACE,OAtRY;;;AAyRd;EACE,OAvRS;EAwRT;;AAEA;EACE,OA1RO;;;AA8RX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE","file":"dark.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YAvCS;EAwCT,OAdS;;;AAiBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE,OA9LS;;AAgMT;AAAA;EACE,YA3NO;;;AA+NX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YArOS;;;AAwOX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAvQU;;;AA0QZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cA/RS;;;AAkSX;EACE,kBAvSS;;;AA0SX;AAAA;EAEE,kBA7SS;EA8ST,cAzSS;;;AA4SX;EACE,OA1RY;;;AA6Rd;EACE,OA3RS;EA4RT;;AAEA;EACE,OA9RO;;;AAkSX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE;;;AAKJ;EACE","file":"dark.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.min.css b/src/static/css/theme/dark.min.css index c0ffb171..0346ca86 100644 --- a/src/static/css/theme/dark.min.css +++ b/src/static/css/theme/dark.min.css @@ -1 +1 @@ -:root{--green:hsl(120deg,30%,50%)!important;--blue:hsl(235deg,60%,60%)!important;--red:hsl(0deg,60%,60%)!important;--magenta:hsl(315deg,60%,60%)!important}body{background:#222;color:hsl(0deg,0%,80%)}.btn-primary{color:hsl(0deg,0%,90%)!important;border-color:hsl(235deg,60%,60%)!important;background:hsl(235deg,60%,60%)!important}.btn-primary:hover{background-color:hsl(235deg,60%,50%)!important;border-color:hsl(235deg,60%,50%)!important}.btn-outline-primary{color:hsl(235deg,60%,60%)!important;border-color:hsl(235deg,60%,60%)!important;background:transparent!important}.btn-outline-primary:hover,.btn-outline-primary.active{color:hsl(0deg,0%,90%)!important}.btn-outline-primary.active{background-color:hsl(235deg,60%,60%)!important;border-color:hsl(235deg,60%,60%)!important}.btn-outline-primary:hover{background-color:hsl(235deg,60%,50%)!important;border-color:hsl(235deg,60%,50%)!important}.btn-success{color:hsl(0deg,0%,90%)!important;border-color:hsl(120deg,30%,50%)!important;background:hsl(120deg,30%,50%)!important}.btn-success:hover{background-color:hsl(120deg,30%,40%)!important;border-color:hsl(120deg,30%,40%)!important}.btn-outline-success{color:hsl(120deg,30%,50%)!important;border-color:hsl(120deg,30%,50%)!important;background:transparent!important}.btn-outline-success:hover,.btn-outline-success.active{color:hsl(0deg,0%,90%)!important}.btn-outline-success.active{background-color:hsl(120deg,30%,50%)!important;border-color:hsl(120deg,30%,50%)!important}.btn-outline-success:hover{background-color:hsl(120deg,30%,40%)!important;border-color:hsl(120deg,30%,40%)!important}.btn-danger{color:hsl(0deg,0%,90%)!important;border-color:hsl(0deg,60%,60%)!important;background:hsl(0deg,60%,60%)!important}.btn-danger:hover{background-color:hsl(0deg,60%,50%)!important;border-color:hsl(0deg,60%,50%)!important}.btn-outline-danger{color:hsl(0deg,60%,60%)!important;border-color:hsl(0deg,60%,60%)!important;background:transparent!important}.btn-outline-danger:hover,.btn-outline-danger.active{color:hsl(0deg,0%,90%)!important}.btn-outline-danger.active{background-color:hsl(0deg,60%,60%)!important;border-color:hsl(0deg,60%,60%)!important}.btn-outline-danger:hover{background-color:hsl(0deg,60%,50%)!important;border-color:hsl(0deg,60%,50%)!important}.btn-secondary{color:hsl(0deg,0%,90%)!important;border-color:#424242!important;background:#424242!important}.btn-secondary:hover{background-color:#383838!important;border-color:#383838!important}.btn-outline-secondary{color:#424242!important;border-color:#424242!important;background:transparent!important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:hsl(0deg,0%,90%)!important}.btn-outline-secondary.active{background-color:#424242!important;border-color:#424242!important}.btn-outline-secondary:hover{background-color:#383838!important;border-color:#383838!important}.btn-control.btn-lock-peer.lock{color:hsl(0deg,60%,60%)!important}.btn-control.btn-lock-peer.lock:hover{color:hsl(0deg,60%,50%)!important}.btn-control:hover{background-color:transparent!important}.btn-control:hover.btn-outline-primary{color:hsl(235deg,60%,50%)!important}.btn-control:hover.btn-outline-success{color:hsl(120deg,30%,40%)!important}.btn-control:hover.btn-outline-danger{color:hsl(0deg,60%,50%)!important}.btn-control:hover.btn-outline-secondary{color:#383838!important}.form-control{background:#272727!important;border-color:transparent!important;color:hsl(0deg,0%,80%)!important}.card .form-control{background:#2c2c2c!important}.sidebar .nav-link,.bottomNavContainer .nav-link{color:hsl(0deg,0%,80%)}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e!important;background:#1e1e1e!important}.card{background:#272727}.text-muted{color:hsl(0deg,0%,50%)!important}.text-danger{color:hsl(0deg,60%,60%)!important}.text-success{color:hsl(120deg,30%,50%)!important}.text-primary{color:hsl(235deg,60%,60%)!important}.text-info{color:hsl(190deg,60%,60%)!important}a.text-success:focus,a.text-success:hover{color:hsl(120deg,30%,40%)!important}a.text-danger:focus,a.text-danger:hover{color:hsl(0deg,60%,50%)!important}a.text-info:focus,a.text-info:hover{color:hsl(190deg,60%,50%)!important}.dot-running{background-color:hsl(120deg,30%,50%)!important}.card-running{border-color:hsl(120deg,30%,50%)}.toggle--switch:checked + .toggleLabel::before{background-color:hsl(235deg,60%,60%)!important}.toggle--switch:checked + .toggleLabel{background-color:#2e336b!important;border-color:hsl(235deg,60%,60%)!important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:hsl(235deg,60%,60%)!important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:hsl(315deg,60%,60%)}.close{color:hsl(0deg,0%,80%);text-shadow:none}.close:hover{color:hsl(0deg,0%,70%)}.chartContainer.fullScreen{background-color:#222!important}.popover{background-color:#333!important;border:none!important}.popover-body{color:hsl(0deg,0%,80%)!important}div.toast{background-color:#424242!important}div.toast div.toast-header{background-color:#333!important;color:hsl(0deg,0%,80%)!important;border-bottom-color:#424242!important}div.toast div.toast-body{background-color:#383838!important;color:hsl(0deg,0%,80%)!important}div.toast div.toast-progressbar{background-color:hsl(235deg,60%,60%)!important}.bs-popover-auto[x-placement^=right] > .arrow::after,.bs-popover-right > .arrow::after{border-right-color:#333!important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c!important}.setting_btn_menu a:hover{background-color:#333!important}.table{color:hsl(0deg,0%,80%)!important}.table th,.table td{border-color:#333!important} \ No newline at end of file +:root{--green: hsl(120deg, 30%, 50%) !important;--blue: hsl(235deg, 60%, 60%) !important;--red: hsl(0deg, 60%, 60%) !important;--magenta: hsl(315deg, 60%, 60%) !important}body{background:#222;color:#ccc}.btn-primary{color:#e6e6e6 !important;border-color:#5c66d6 !important;background:#5c66d6 !important}.btn-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-outline-primary{color:#5c66d6 !important;border-color:#5c66d6 !important;background:rgba(0,0,0,0) !important}.btn-outline-primary:hover,.btn-outline-primary.active{color:#e6e6e6 !important}.btn-outline-primary.active{background-color:#5c66d6 !important;border-color:#5c66d6 !important}.btn-outline-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-success{color:#e6e6e6 !important;border-color:#59a659 !important;background:#59a659 !important}.btn-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-outline-success{color:#59a659 !important;border-color:#59a659 !important;background:rgba(0,0,0,0) !important}.btn-outline-success:hover,.btn-outline-success.active{color:#e6e6e6 !important}.btn-outline-success.active{background-color:#59a659 !important;border-color:#59a659 !important}.btn-outline-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-danger{color:#e6e6e6 !important;border-color:#d65c5c !important;background:#d65c5c !important}.btn-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-outline-danger{color:#d65c5c !important;border-color:#d65c5c !important;background:rgba(0,0,0,0) !important}.btn-outline-danger:hover,.btn-outline-danger.active{color:#e6e6e6 !important}.btn-outline-danger.active{background-color:#d65c5c !important;border-color:#d65c5c !important}.btn-outline-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-secondary{color:#e6e6e6 !important;border-color:#424242 !important;background:#424242 !important}.btn-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-outline-secondary{color:#424242 !important;border-color:#424242 !important;background:rgba(0,0,0,0) !important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:#e6e6e6 !important}.btn-outline-secondary.active{background-color:#424242 !important;border-color:#424242 !important}.btn-outline-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-control.btn-lock-peer.lock{color:#d65c5c !important}.btn-control.btn-lock-peer.lock:hover{color:#c33 !important}.btn-control:hover{background-color:rgba(0,0,0,0) !important}.btn-control:hover.btn-outline-primary{color:#3340cc !important}.btn-control:hover.btn-outline-success{color:#478547 !important}.btn-control:hover.btn-outline-danger{color:#c33 !important}.btn-control:hover.btn-outline-secondary{color:#383838 !important}.form-control{background-color:#272727 !important;border-color:rgba(0,0,0,0) !important;color:#ccc !important}.form-control:disabled{color:#777 !important}.card .form-control{background:#2c2c2c !important}.sidebar .nav-link,.bottomNavContainer .nav-link{color:#ccc}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e !important;background:#1e1e1e !important}.card{background:#272727}.text-muted{color:gray !important}.text-danger{color:#d65c5c !important}.text-success{color:#59a659 !important}.text-primary{color:#5c66d6 !important}.text-info{color:#5cc2d6 !important}a.text-success:focus,a.text-success:hover{color:#478547 !important}a.text-danger:focus,a.text-danger:hover{color:#c33 !important}a.text-info:focus,a.text-info:hover{color:#33b3cc !important}.dot-running{background-color:#59a659 !important}.card-running{border-color:#59a659}.toggle--switch:checked+.toggleLabel::before{background-color:#5c66d6 !important}.toggle--switch:checked+.toggleLabel{background-color:#2e336b !important;border-color:#5c66d6 !important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:#5c66d6 !important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:#d65cb8}.close{color:#ccc;text-shadow:none}.close:hover{color:#b3b3b3}.chartContainer.fullScreen{background-color:#222 !important}.popover{background-color:#333 !important;border:none !important}.popover-body{color:#ccc !important}div.toast{background-color:#424242 !important}div.toast div.toast-header{background-color:#333 !important;color:#ccc !important;border-bottom-color:#424242 !important}div.toast div.toast-body{background-color:#383838 !important;color:#ccc !important}div.toast div.toast-progressbar{background-color:#5c66d6 !important}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{border-right-color:#333 !important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c !important}.setting_btn_menu a:hover{background-color:#333 !important}.table{color:#ccc !important}.table th,.table td{border-color:#333 !important}.btn-outline-primary.focus,.btn-outline-primary:focus,.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(144,153,255,.29) !important}/*# sourceMappingURL=dark.min.css.map */ diff --git a/src/static/css/theme/dark.min.css.map b/src/static/css/theme/dark.min.css.map new file mode 100644 index 00000000..91f63513 --- /dev/null +++ b/src/static/css/theme/dark.min.css.map @@ -0,0 +1 @@ +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA,MACE,0CACA,yCACA,sCACA,4CAGF,KACE,WAvCS,KAwCT,MAdS,KAiBX,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,YACE,yBACA,gCACA,8BAEA,kBACE,iCACA,6BAIJ,oBACE,yBACA,gCACA,oCAEA,qDAEE,yBAGF,2BACE,oCACA,gCAGF,0BACE,iCACA,6BAIJ,eACE,yBACA,gCACA,8BAEA,qBACE,oCACA,gCAIJ,uBACE,yBACA,gCACA,oCAEA,2DAEE,yBAGF,8BACE,oCACA,gCAGF,6BACE,oCACA,gCAKF,gCACE,yBACA,sCACE,sBAIJ,mBACE,0CAEA,uCACE,yBAGF,uCACE,yBAGF,sCACE,sBAGF,yCACE,yBAKN,cACE,oCACA,sCACA,sBAGF,uBACE,sBAGF,oBACE,8BAGF,iDAEE,MA9LS,KAgMT,6DACE,WA3NO,KA+NX,8FAGE,oCACA,8BAGF,MACE,WArOS,QAwOX,YACE,sBAGF,aACE,yBAGF,cACE,yBAGF,cACE,yBAGF,WACE,yBAGF,0CAEE,yBAGF,wCAEE,sBAGF,oCAEE,yBAGF,aACE,oCAGF,cACE,aAvQU,QA0QZ,6CACE,oCAEF,qCACE,oCACA,gCAGF,+DAEE,yBAGF,GACE,aA/RS,QAkSX,eACE,iBAvSS,KA0SX,4BAEE,iBA7SS,QA8ST,aAzSS,QA4SX,KACE,MA1RY,QA6Rd,OACE,MA3RS,KA4RT,iBAEA,aACE,MA9RO,QAkSX,2BACE,iCAGF,SACE,iCACA,uBAGF,cACE,sBAGF,UACE,oCAEA,2BACE,iCACA,sBACA,uCAGF,yBACE,oCACA,sBAGF,gCACE,oCAIJ,mFAEE,mCAGF,oCACE,oCAGF,0BACE,iCAGF,OACE,sBAEA,oBAEE,6BAKJ,4FACE","file":"dark.min.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.scss b/src/static/css/theme/dark.scss index c7a27b08..5395d979 100644 --- a/src/static/css/theme/dark.scss +++ b/src/static/css/theme/dark.scss @@ -7,6 +7,7 @@ $grey-600: #2e2e2e; $grey-700: #333333; $grey-800: #383838; $grey-900: #424242; +$grey-1000: #777777; $green-400: hsl(120deg, 30%, 40%); $green-500: hsl(120deg, 30%, 50%); @@ -16,6 +17,7 @@ $red-500: hsl(0deg, 60%, 60%); $blue-400: hsl(235deg, 60%, 50%); $blue-500: hsl(235deg, 60%, 60%); +$blue-400-clear: rgba(51, 64, 204, 0.25); $cyan-400: hsl(190deg, 60%, 50%); $cyan-500: hsl(190deg, 60%, 60%); @@ -198,11 +200,15 @@ body { } .form-control { - background: $grey-400 !important; + background-color: $grey-400 !important; border-color: transparent !important; color: $text-200 !important; } +.form-control:disabled{ + color: $grey-1000 !important; +} + .card .form-control { background: $grey-500 !important; } @@ -363,3 +369,8 @@ div.toast { border-color: $grey-700 !important; } } + + +.btn-outline-primary.focus, .btn-outline-primary:focus, .btn-primary.focus, .btn-primary:focus{ + box-shadow: 0 0 0 0.2rem rgb(144 153 255 / 29%) !important; +} \ No newline at end of file From 36e33a4c10f70b5b6cd53a019382bda531fc8e78 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Fri, 22 Apr 2022 16:21:16 -0400 Subject: [PATCH 026/214] Adjust the dark mode theme for PWA --- src/static/css/theme/dark.css | 23 ++++++++++++++++++- src/static/css/theme/dark.css.map | 2 +- src/static/css/theme/dark.min.css | 2 +- src/static/css/theme/dark.min.css.map | 2 +- src/static/css/theme/dark.scss | 33 +++++++++++++++++++++++++-- 5 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/static/css/theme/dark.css b/src/static/css/theme/dark.css index e13ee09f..e7049471 100644 --- a/src/static/css/theme/dark.css +++ b/src/static/css/theme/dark.css @@ -141,7 +141,7 @@ body { } .form-control { - background-color: #272727 !important; + background-color: #2c2c2c !important; border-color: transparent !important; color: hsl(0deg, 0%, 80%) !important; } @@ -154,6 +154,13 @@ body { background: #2c2c2c !important; } +.conf_card a { + color: hsl(235deg, 60%, 60%); +} +.conf_card:hover { + border-color: hsl(235deg, 60%, 60%); +} + .sidebar .nav-link, .bottomNavContainer .nav-link { color: hsl(0deg, 0%, 80%); @@ -311,4 +318,18 @@ div.toast div.toast-progressbar { box-shadow: 0 0 0 0.2rem rgba(144, 153, 255, 0.29) !important; } +.bottomNav { + background-color: #272727 !important; +} +.bottomNav .bottomNavButton { + color: hsl(0deg, 0%, 60%); +} +.bottomNav .bottomNavButton.active { + color: hsl(235deg, 60%, 60%) !important; +} + +.subNav { + background-color: #272727 !important; +} + /*# sourceMappingURL=dark.css.map */ diff --git a/src/static/css/theme/dark.css.map b/src/static/css/theme/dark.css.map index 8e752c31..4de8d027 100644 --- a/src/static/css/theme/dark.css.map +++ b/src/static/css/theme/dark.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YAvCS;EAwCT,OAdS;;;AAiBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE,OA9LS;;AAgMT;AAAA;EACE,YA3NO;;;AA+NX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YArOS;;;AAwOX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAvQU;;;AA0QZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cA/RS;;;AAkSX;EACE,kBAvSS;;;AA0SX;AAAA;EAEE,kBA7SS;EA8ST,cAzSS;;;AA4SX;EACE,OA1RY;;;AA6Rd;EACE,OA3RS;EA4RT;;AAEA;EACE,OA9RO;;;AAkSX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE;;;AAKJ;EACE","file":"dark.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YAvCS;EAwCT,OAdS;;;AAkBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAIA;EACE,OAxMO;;AA0MT;EACE,cA3MO;;;AA+MX;AAAA;EAEE,OAxMS;;AA0MT;AAAA;EACE,YArOO;;;AAyOX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YA/OS;;;AAkPX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAjRU;;;AAoRZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cAzSS;;;AA4SX;EACE,kBAjTS;;;AAoTX;AAAA;EAEE,kBAvTS;EAwTT,cAnTS;;;AAsTX;EACE,OApSY;;;AAuSd;EACE,OArSS;EAsST;;AAEA;EACE,OAxSO;;;AA4SX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE;;;AAKJ;EACE;;;AAIA;EACE;;AAIA;EACE,OA7WK;;AAgXT;EACE;;;AAIJ;EACE","file":"dark.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.min.css b/src/static/css/theme/dark.min.css index 0346ca86..ffb8183f 100644 --- a/src/static/css/theme/dark.min.css +++ b/src/static/css/theme/dark.min.css @@ -1 +1 @@ -:root{--green: hsl(120deg, 30%, 50%) !important;--blue: hsl(235deg, 60%, 60%) !important;--red: hsl(0deg, 60%, 60%) !important;--magenta: hsl(315deg, 60%, 60%) !important}body{background:#222;color:#ccc}.btn-primary{color:#e6e6e6 !important;border-color:#5c66d6 !important;background:#5c66d6 !important}.btn-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-outline-primary{color:#5c66d6 !important;border-color:#5c66d6 !important;background:rgba(0,0,0,0) !important}.btn-outline-primary:hover,.btn-outline-primary.active{color:#e6e6e6 !important}.btn-outline-primary.active{background-color:#5c66d6 !important;border-color:#5c66d6 !important}.btn-outline-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-success{color:#e6e6e6 !important;border-color:#59a659 !important;background:#59a659 !important}.btn-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-outline-success{color:#59a659 !important;border-color:#59a659 !important;background:rgba(0,0,0,0) !important}.btn-outline-success:hover,.btn-outline-success.active{color:#e6e6e6 !important}.btn-outline-success.active{background-color:#59a659 !important;border-color:#59a659 !important}.btn-outline-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-danger{color:#e6e6e6 !important;border-color:#d65c5c !important;background:#d65c5c !important}.btn-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-outline-danger{color:#d65c5c !important;border-color:#d65c5c !important;background:rgba(0,0,0,0) !important}.btn-outline-danger:hover,.btn-outline-danger.active{color:#e6e6e6 !important}.btn-outline-danger.active{background-color:#d65c5c !important;border-color:#d65c5c !important}.btn-outline-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-secondary{color:#e6e6e6 !important;border-color:#424242 !important;background:#424242 !important}.btn-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-outline-secondary{color:#424242 !important;border-color:#424242 !important;background:rgba(0,0,0,0) !important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:#e6e6e6 !important}.btn-outline-secondary.active{background-color:#424242 !important;border-color:#424242 !important}.btn-outline-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-control.btn-lock-peer.lock{color:#d65c5c !important}.btn-control.btn-lock-peer.lock:hover{color:#c33 !important}.btn-control:hover{background-color:rgba(0,0,0,0) !important}.btn-control:hover.btn-outline-primary{color:#3340cc !important}.btn-control:hover.btn-outline-success{color:#478547 !important}.btn-control:hover.btn-outline-danger{color:#c33 !important}.btn-control:hover.btn-outline-secondary{color:#383838 !important}.form-control{background-color:#272727 !important;border-color:rgba(0,0,0,0) !important;color:#ccc !important}.form-control:disabled{color:#777 !important}.card .form-control{background:#2c2c2c !important}.sidebar .nav-link,.bottomNavContainer .nav-link{color:#ccc}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e !important;background:#1e1e1e !important}.card{background:#272727}.text-muted{color:gray !important}.text-danger{color:#d65c5c !important}.text-success{color:#59a659 !important}.text-primary{color:#5c66d6 !important}.text-info{color:#5cc2d6 !important}a.text-success:focus,a.text-success:hover{color:#478547 !important}a.text-danger:focus,a.text-danger:hover{color:#c33 !important}a.text-info:focus,a.text-info:hover{color:#33b3cc !important}.dot-running{background-color:#59a659 !important}.card-running{border-color:#59a659}.toggle--switch:checked+.toggleLabel::before{background-color:#5c66d6 !important}.toggle--switch:checked+.toggleLabel{background-color:#2e336b !important;border-color:#5c66d6 !important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:#5c66d6 !important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:#d65cb8}.close{color:#ccc;text-shadow:none}.close:hover{color:#b3b3b3}.chartContainer.fullScreen{background-color:#222 !important}.popover{background-color:#333 !important;border:none !important}.popover-body{color:#ccc !important}div.toast{background-color:#424242 !important}div.toast div.toast-header{background-color:#333 !important;color:#ccc !important;border-bottom-color:#424242 !important}div.toast div.toast-body{background-color:#383838 !important;color:#ccc !important}div.toast div.toast-progressbar{background-color:#5c66d6 !important}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{border-right-color:#333 !important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c !important}.setting_btn_menu a:hover{background-color:#333 !important}.table{color:#ccc !important}.table th,.table td{border-color:#333 !important}.btn-outline-primary.focus,.btn-outline-primary:focus,.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(144,153,255,.29) !important}/*# sourceMappingURL=dark.min.css.map */ +:root{--green: hsl(120deg, 30%, 50%) !important;--blue: hsl(235deg, 60%, 60%) !important;--red: hsl(0deg, 60%, 60%) !important;--magenta: hsl(315deg, 60%, 60%) !important}body{background:#222;color:#ccc}.btn-primary{color:#e6e6e6 !important;border-color:#5c66d6 !important;background:#5c66d6 !important}.btn-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-outline-primary{color:#5c66d6 !important;border-color:#5c66d6 !important;background:rgba(0,0,0,0) !important}.btn-outline-primary:hover,.btn-outline-primary.active{color:#e6e6e6 !important}.btn-outline-primary.active{background-color:#5c66d6 !important;border-color:#5c66d6 !important}.btn-outline-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-success{color:#e6e6e6 !important;border-color:#59a659 !important;background:#59a659 !important}.btn-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-outline-success{color:#59a659 !important;border-color:#59a659 !important;background:rgba(0,0,0,0) !important}.btn-outline-success:hover,.btn-outline-success.active{color:#e6e6e6 !important}.btn-outline-success.active{background-color:#59a659 !important;border-color:#59a659 !important}.btn-outline-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-danger{color:#e6e6e6 !important;border-color:#d65c5c !important;background:#d65c5c !important}.btn-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-outline-danger{color:#d65c5c !important;border-color:#d65c5c !important;background:rgba(0,0,0,0) !important}.btn-outline-danger:hover,.btn-outline-danger.active{color:#e6e6e6 !important}.btn-outline-danger.active{background-color:#d65c5c !important;border-color:#d65c5c !important}.btn-outline-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-secondary{color:#e6e6e6 !important;border-color:#424242 !important;background:#424242 !important}.btn-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-outline-secondary{color:#424242 !important;border-color:#424242 !important;background:rgba(0,0,0,0) !important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:#e6e6e6 !important}.btn-outline-secondary.active{background-color:#424242 !important;border-color:#424242 !important}.btn-outline-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-control.btn-lock-peer.lock{color:#d65c5c !important}.btn-control.btn-lock-peer.lock:hover{color:#c33 !important}.btn-control:hover{background-color:rgba(0,0,0,0) !important}.btn-control:hover.btn-outline-primary{color:#3340cc !important}.btn-control:hover.btn-outline-success{color:#478547 !important}.btn-control:hover.btn-outline-danger{color:#c33 !important}.btn-control:hover.btn-outline-secondary{color:#383838 !important}.form-control{background-color:#2c2c2c !important;border-color:rgba(0,0,0,0) !important;color:#ccc !important}.form-control:disabled{color:#777 !important}.card .form-control{background:#2c2c2c !important}.conf_card a{color:#5c66d6}.conf_card:hover{border-color:#5c66d6}.sidebar .nav-link,.bottomNavContainer .nav-link{color:#ccc}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e !important;background:#1e1e1e !important}.card{background:#272727}.text-muted{color:gray !important}.text-danger{color:#d65c5c !important}.text-success{color:#59a659 !important}.text-primary{color:#5c66d6 !important}.text-info{color:#5cc2d6 !important}a.text-success:focus,a.text-success:hover{color:#478547 !important}a.text-danger:focus,a.text-danger:hover{color:#c33 !important}a.text-info:focus,a.text-info:hover{color:#33b3cc !important}.dot-running{background-color:#59a659 !important}.card-running{border-color:#59a659}.toggle--switch:checked+.toggleLabel::before{background-color:#5c66d6 !important}.toggle--switch:checked+.toggleLabel{background-color:#2e336b !important;border-color:#5c66d6 !important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:#5c66d6 !important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:#d65cb8}.close{color:#ccc;text-shadow:none}.close:hover{color:#b3b3b3}.chartContainer.fullScreen{background-color:#222 !important}.popover{background-color:#333 !important;border:none !important}.popover-body{color:#ccc !important}div.toast{background-color:#424242 !important}div.toast div.toast-header{background-color:#333 !important;color:#ccc !important;border-bottom-color:#424242 !important}div.toast div.toast-body{background-color:#383838 !important;color:#ccc !important}div.toast div.toast-progressbar{background-color:#5c66d6 !important}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{border-right-color:#333 !important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c !important}.setting_btn_menu a:hover{background-color:#333 !important}.table{color:#ccc !important}.table th,.table td{border-color:#333 !important}.btn-outline-primary.focus,.btn-outline-primary:focus,.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(144,153,255,.29) !important}.bottomNav{background-color:#272727 !important}.bottomNav .bottomNavButton{color:#999}.bottomNav .bottomNavButton.active{color:#5c66d6 !important}.subNav{background-color:#272727 !important}/*# sourceMappingURL=dark.min.css.map */ diff --git a/src/static/css/theme/dark.min.css.map b/src/static/css/theme/dark.min.css.map index 91f63513..4cb79dbf 100644 --- a/src/static/css/theme/dark.min.css.map +++ b/src/static/css/theme/dark.min.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA,MACE,0CACA,yCACA,sCACA,4CAGF,KACE,WAvCS,KAwCT,MAdS,KAiBX,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,YACE,yBACA,gCACA,8BAEA,kBACE,iCACA,6BAIJ,oBACE,yBACA,gCACA,oCAEA,qDAEE,yBAGF,2BACE,oCACA,gCAGF,0BACE,iCACA,6BAIJ,eACE,yBACA,gCACA,8BAEA,qBACE,oCACA,gCAIJ,uBACE,yBACA,gCACA,oCAEA,2DAEE,yBAGF,8BACE,oCACA,gCAGF,6BACE,oCACA,gCAKF,gCACE,yBACA,sCACE,sBAIJ,mBACE,0CAEA,uCACE,yBAGF,uCACE,yBAGF,sCACE,sBAGF,yCACE,yBAKN,cACE,oCACA,sCACA,sBAGF,uBACE,sBAGF,oBACE,8BAGF,iDAEE,MA9LS,KAgMT,6DACE,WA3NO,KA+NX,8FAGE,oCACA,8BAGF,MACE,WArOS,QAwOX,YACE,sBAGF,aACE,yBAGF,cACE,yBAGF,cACE,yBAGF,WACE,yBAGF,0CAEE,yBAGF,wCAEE,sBAGF,oCAEE,yBAGF,aACE,oCAGF,cACE,aAvQU,QA0QZ,6CACE,oCAEF,qCACE,oCACA,gCAGF,+DAEE,yBAGF,GACE,aA/RS,QAkSX,eACE,iBAvSS,KA0SX,4BAEE,iBA7SS,QA8ST,aAzSS,QA4SX,KACE,MA1RY,QA6Rd,OACE,MA3RS,KA4RT,iBAEA,aACE,MA9RO,QAkSX,2BACE,iCAGF,SACE,iCACA,uBAGF,cACE,sBAGF,UACE,oCAEA,2BACE,iCACA,sBACA,uCAGF,yBACE,oCACA,sBAGF,gCACE,oCAIJ,mFAEE,mCAGF,oCACE,oCAGF,0BACE,iCAGF,OACE,sBAEA,oBAEE,6BAKJ,4FACE","file":"dark.min.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA,MACE,0CACA,yCACA,sCACA,4CAGF,KACE,WAvCS,KAwCT,MAdS,KAkBX,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,YACE,yBACA,gCACA,8BAEA,kBACE,iCACA,6BAIJ,oBACE,yBACA,gCACA,oCAEA,qDAEE,yBAGF,2BACE,oCACA,gCAGF,0BACE,iCACA,6BAIJ,eACE,yBACA,gCACA,8BAEA,qBACE,oCACA,gCAIJ,uBACE,yBACA,gCACA,oCAEA,2DAEE,yBAGF,8BACE,oCACA,gCAGF,6BACE,oCACA,gCAKF,gCACE,yBACA,sCACE,sBAIJ,mBACE,0CAEA,uCACE,yBAGF,uCACE,yBAGF,sCACE,sBAGF,yCACE,yBAKN,cACE,oCACA,sCACA,sBAGF,uBACE,sBAGF,oBACE,8BAIA,aACE,MAxMO,QA0MT,iBACE,aA3MO,QA+MX,iDAEE,MAxMS,KA0MT,6DACE,WArOO,KAyOX,8FAGE,oCACA,8BAGF,MACE,WA/OS,QAkPX,YACE,sBAGF,aACE,yBAGF,cACE,yBAGF,cACE,yBAGF,WACE,yBAGF,0CAEE,yBAGF,wCAEE,sBAGF,oCAEE,yBAGF,aACE,oCAGF,cACE,aAjRU,QAoRZ,6CACE,oCAEF,qCACE,oCACA,gCAGF,+DAEE,yBAGF,GACE,aAzSS,QA4SX,eACE,iBAjTS,KAoTX,4BAEE,iBAvTS,QAwTT,aAnTS,QAsTX,KACE,MApSY,QAuSd,OACE,MArSS,KAsST,iBAEA,aACE,MAxSO,QA4SX,2BACE,iCAGF,SACE,iCACA,uBAGF,cACE,sBAGF,UACE,oCAEA,2BACE,iCACA,sBACA,uCAGF,yBACE,oCACA,sBAGF,gCACE,oCAIJ,mFAEE,mCAGF,oCACE,oCAGF,0BACE,iCAGF,OACE,sBAEA,oBAEE,6BAKJ,4FACE,wDAIA,WACE,oCAIA,4BACE,MA7WK,KAgXT,mCACE,yBAIJ,QACE","file":"dark.min.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.scss b/src/static/css/theme/dark.scss index 5395d979..b0ecc8be 100644 --- a/src/static/css/theme/dark.scss +++ b/src/static/css/theme/dark.scss @@ -42,6 +42,7 @@ body { color: $text-200; } + .btn-primary { color: $text-100 !important; border-color: $blue-500 !important; @@ -200,7 +201,7 @@ body { } .form-control { - background-color: $grey-400 !important; + background-color: $grey-500 !important; border-color: transparent !important; color: $text-200 !important; } @@ -213,6 +214,15 @@ body { background: $grey-500 !important; } +.conf_card{ + a{ + color: $blue-500; + } + &:hover{ + border-color: $blue-500; + } +} + .sidebar .nav-link, .bottomNavContainer .nav-link { color: $text-200; @@ -373,4 +383,23 @@ div.toast { .btn-outline-primary.focus, .btn-outline-primary:focus, .btn-primary.focus, .btn-primary:focus{ box-shadow: 0 0 0 0.2rem rgb(144 153 255 / 29%) !important; -} \ No newline at end of file +} + +.bottomNav{ + &{ + background-color: $grey-400 !important; + } + + .bottomNavButton{ + &{ + color: $text-400; + } + } + .bottomNavButton.active{ + color: $blue-500 !important; + } +} + +.subNav{ + background-color: $grey-400 !important; +} From e06cc1bd2d0db3f980eb63c65c9a5a9b620ab865 Mon Sep 17 00:00:00 2001 From: Donald Cheng Hong Zou Date: Sat, 23 Apr 2022 00:34:11 -0400 Subject: [PATCH 027/214] Finally finished theme switching!!!! --- src/api.py | 12 ++++- src/dashboard.py | 15 ++++++ src/static/css/dashboard.css | 4 ++ src/static/css/theme/dark.css | 50 +++++++++++++++++++- src/static/css/theme/dark.css.map | 2 +- src/static/css/theme/dark.min.css | 2 +- src/static/css/theme/dark.min.css.map | 2 +- src/static/css/theme/dark.scss | 68 ++++++++++++++++++++++++++- src/static/js/configurationTool.js | 36 +++++++------- src/templates/header.html | 9 ++-- src/templates/navbar.html | 1 + src/templates/settings.html | 44 +++++++++++++++++ src/templates/sidebar.html | 9 +--- 13 files changed, 218 insertions(+), 36 deletions(-) diff --git a/src/api.py b/src/api.py index 8fe189ab..442d6756 100644 --- a/src/api.py +++ b/src/api.py @@ -181,4 +181,14 @@ class manageConfiguration: return ret(status=False, reason="No [Interface] in configuration file") return ret(data=dict(conf['Interface'])) except FileNotFoundError as err: - return ret(status=False, reason=str(err)) \ No newline at end of file + return ret(status=False, reason=str(err)) + + +class settings: + def setTheme(self, theme, config, setConfig): + themes = ['light', 'dark'] + if theme not in themes: + return ret(status=False, reason="Theme does not exist") + config['Server']['dashboard_theme'] = theme + setConfig(config) + return ret() \ No newline at end of file diff --git a/src/dashboard.py b/src/dashboard.py index 2d07e4db..464cfd13 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -694,6 +694,7 @@ def auth_req(): g.cur = g.db.cursor() conf = get_dashboard_conf() req = conf.get("Server", "auth_req") + session['theme'] = conf.get("Server", "dashboard_theme") session['update'] = UPDATE session['updateInfo'] = updateInfo session['dashboard_version'] = DASHBOARD_VERSION @@ -1571,6 +1572,7 @@ def switch_display_mode(mode): # APIs import api +# TODO: Add configuration prefix to all configuration API @app.route('/api/getPeerDataUsage', methods=['POST']) def getPeerDataUsage(): @@ -1674,6 +1676,17 @@ def getConfigurationInfo(): return jsonify(api.notEnoughParameter) else: return api.manageConfiguration.getConfigurationInfo(api.manageConfiguration, data['configName'], WG_CONF_PATH) + +@app.route('/api/settings/setTheme', methods=['POST']) +def setTheme(): + data = request.get_json() + required = ['theme'] + if not checkJSONAllParameter(required, data): + return jsonify(api.notEnoughParameter) + else: + return api.settings.setTheme(api.settings, data['theme'], get_dashboard_conf(), set_dashboard_conf) + + """ @@ -1913,6 +1926,8 @@ def init_dashboard(): config['Server']['dashboard_refresh_interval'] = '60000' if 'dashboard_sort' not in config['Server']: config['Server']['dashboard_sort'] = 'status' + if 'dashboard_theme' not in config['Server']: + config['Server']['dashboard_theme'] = 'light' # Default dashboard peers setting if "Peers" not in config: config['Peers'] = {} diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 54a5f9ab..e23ec51c 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -922,4 +922,8 @@ pre.index-alert { .list-group-item{ transition: all 0.1s ease-in; +} + +.theme-switch-btn{ + width: 100%; } \ No newline at end of file diff --git a/src/static/css/theme/dark.css b/src/static/css/theme/dark.css index e7049471..f1a53888 100644 --- a/src/static/css/theme/dark.css +++ b/src/static/css/theme/dark.css @@ -47,6 +47,49 @@ body { border-color: hsl(120deg, 30%, 40%) !important; } +.list-group-item { + background-color: #272727; + border-color: #272727; + color: white; +} +.list-group-item:hover { + background-color: #333333; + border-color: #333333; + color: white; +} + +.delete-peer-bulk-badge.badge-danger { + background-color: hsl(0deg, 60%, 60%); +} +.delete-peer-bulk-badge.badge-danger:hover { + background-color: hsl(0deg, 60%, 50%); +} + +#delete_bulk_modal .list-group a.active { + background-color: hsl(0deg, 60%, 60%); + border: hsl(0deg, 60%, 60%); +} +#delete_bulk_modal .list-group a.active:hover { + background-color: hsl(0deg, 60%, 50%); + border: hsl(0deg, 60%, 50%); +} + +#available_ip_modal .list-group a.active { + background-color: hsl(235deg, 60%, 60%); + border: hsl(235deg, 60%, 60%); +} +#available_ip_modal .list-group a.active:hover { + background-color: hsl(235deg, 60%, 50%); + border: hsl(235deg, 60%, 50%); +} + +.available-ip-badge.badge-primary { + background-color: hsl(235deg, 60%, 60%); +} +.available-ip-badge.badge-primary:hover { + background-color: hsl(235deg, 60%, 50%); +} + .btn-outline-success { color: hsl(120deg, 30%, 50%) !important; border-color: hsl(120deg, 30%, 50%) !important; @@ -327,9 +370,12 @@ div.toast div.toast-progressbar { .bottomNav .bottomNavButton.active { color: hsl(235deg, 60%, 60%) !important; } - -.subNav { +.bottomNav .subNav { background-color: #272727 !important; } +.key:hover { + color: hsl(235deg, 60%, 60%); +} + /*# sourceMappingURL=dark.css.map */ diff --git a/src/static/css/theme/dark.css.map b/src/static/css/theme/dark.css.map index 4de8d027..ce5e2a6b 100644 --- a/src/static/css/theme/dark.css.map +++ b/src/static/css/theme/dark.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YAvCS;EAwCT,OAdS;;;AAkBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;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A;EACE;;AAIA;EACE,OA7WK;;AAgXT;EACE;;;AAIJ;EACE","file":"dark.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA;EACE;EACA;EACA;EACA;;;AAGF;EACE,YAvCS;EAwCT,OAdS;;;AAkBX;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE,kBAtFS;EAuFT,cAvFS;EAwFT;;AAEA;EACE,kBAxFO;EAyFP,cAzFO;EA0FP;;;AAMJ;EACE,kBAxFQ;;AAyFR;EACE,kBA3FM;;;AAiGN;EACE,kBAjGI;EAkGJ,QAlGI;;AAoGJ;EACE,kBAtGE;EAuGF,QAvGE;;;AA+GN;EACE,kBA5GK;EA6GL,QA7GK;;AA+GL;EACE,kBAjHG;EAkHH,QAlHG;;;AAwHX;EACE,kBAxHS;;AAyHT;EACE,kBA3HO;;;AA+HX;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EACE;EACA;;;AAIJ;EACE;EACA;EACA;;AAEA;EAEE;;AAGF;EACE;EACA;;AAGF;EACE;EACA;;;AAKF;EACE;;AACA;EACE;;AAIJ;EACE;;AAEA;EACE;;AAGF;EACE;;AAGF;EACE;;AAGF;EACE;;;AAKN;EACE;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAIA;EACE,OAhQO;;AAkQT;EACE,cAnQO;;;AAuQX;AAAA;EAEE,OAhQS;;AAkQT;AAAA;EACE,YA7RO;;;AAiSX;AAAA;AAAA;EAGE;EACA;;;AAGF;EACE,YAvSS;;;AA0SX;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE,cAzUU;;;AA4UZ;EACE;;;AAEF;EACE;EACA;;;AAGF;AAAA;EAEE;;;AAGF;EACE,cAjWS;;;AAoWX;EACE,kBAzWS;;;AA4WX;AAAA;EAEE,kBA/WS;EAgXT,cA3WS;;;AA8WX;EACE,OA5VY;;;AA+Vd;EACE,OA7VS;EA8VT;;AAEA;EACE,OAhWO;;;AAoWX;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;AAEA;EACE;EACA;EACA;;AAGF;EACE;EACA;;AAGF;EACE;;;AAIJ;AAAA;EAEE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;AAEA;AAAA;EAEE;;;AAKJ;EACE;;;AAIA;EACE;;AAIA;EACE,OAraK;;AAyaT;EACE;;AAGF;EACE;;;AAKJ;EACE,OA/bS","file":"dark.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.min.css b/src/static/css/theme/dark.min.css index ffb8183f..7d90d8bb 100644 --- a/src/static/css/theme/dark.min.css +++ b/src/static/css/theme/dark.min.css @@ -1 +1 @@ -:root{--green: hsl(120deg, 30%, 50%) !important;--blue: hsl(235deg, 60%, 60%) !important;--red: hsl(0deg, 60%, 60%) !important;--magenta: hsl(315deg, 60%, 60%) !important}body{background:#222;color:#ccc}.btn-primary{color:#e6e6e6 !important;border-color:#5c66d6 !important;background:#5c66d6 !important}.btn-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-outline-primary{color:#5c66d6 !important;border-color:#5c66d6 !important;background:rgba(0,0,0,0) !important}.btn-outline-primary:hover,.btn-outline-primary.active{color:#e6e6e6 !important}.btn-outline-primary.active{background-color:#5c66d6 !important;border-color:#5c66d6 !important}.btn-outline-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-success{color:#e6e6e6 !important;border-color:#59a659 !important;background:#59a659 !important}.btn-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-outline-success{color:#59a659 !important;border-color:#59a659 !important;background:rgba(0,0,0,0) !important}.btn-outline-success:hover,.btn-outline-success.active{color:#e6e6e6 !important}.btn-outline-success.active{background-color:#59a659 !important;border-color:#59a659 !important}.btn-outline-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-danger{color:#e6e6e6 !important;border-color:#d65c5c !important;background:#d65c5c !important}.btn-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-outline-danger{color:#d65c5c !important;border-color:#d65c5c !important;background:rgba(0,0,0,0) !important}.btn-outline-danger:hover,.btn-outline-danger.active{color:#e6e6e6 !important}.btn-outline-danger.active{background-color:#d65c5c !important;border-color:#d65c5c !important}.btn-outline-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-secondary{color:#e6e6e6 !important;border-color:#424242 !important;background:#424242 !important}.btn-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-outline-secondary{color:#424242 !important;border-color:#424242 !important;background:rgba(0,0,0,0) !important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:#e6e6e6 !important}.btn-outline-secondary.active{background-color:#424242 !important;border-color:#424242 !important}.btn-outline-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-control.btn-lock-peer.lock{color:#d65c5c !important}.btn-control.btn-lock-peer.lock:hover{color:#c33 !important}.btn-control:hover{background-color:rgba(0,0,0,0) !important}.btn-control:hover.btn-outline-primary{color:#3340cc !important}.btn-control:hover.btn-outline-success{color:#478547 !important}.btn-control:hover.btn-outline-danger{color:#c33 !important}.btn-control:hover.btn-outline-secondary{color:#383838 !important}.form-control{background-color:#2c2c2c !important;border-color:rgba(0,0,0,0) !important;color:#ccc !important}.form-control:disabled{color:#777 !important}.card .form-control{background:#2c2c2c !important}.conf_card a{color:#5c66d6}.conf_card:hover{border-color:#5c66d6}.sidebar .nav-link,.bottomNavContainer .nav-link{color:#ccc}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e !important;background:#1e1e1e !important}.card{background:#272727}.text-muted{color:gray !important}.text-danger{color:#d65c5c !important}.text-success{color:#59a659 !important}.text-primary{color:#5c66d6 !important}.text-info{color:#5cc2d6 !important}a.text-success:focus,a.text-success:hover{color:#478547 !important}a.text-danger:focus,a.text-danger:hover{color:#c33 !important}a.text-info:focus,a.text-info:hover{color:#33b3cc !important}.dot-running{background-color:#59a659 !important}.card-running{border-color:#59a659}.toggle--switch:checked+.toggleLabel::before{background-color:#5c66d6 !important}.toggle--switch:checked+.toggleLabel{background-color:#2e336b !important;border-color:#5c66d6 !important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:#5c66d6 !important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:#d65cb8}.close{color:#ccc;text-shadow:none}.close:hover{color:#b3b3b3}.chartContainer.fullScreen{background-color:#222 !important}.popover{background-color:#333 !important;border:none !important}.popover-body{color:#ccc !important}div.toast{background-color:#424242 !important}div.toast div.toast-header{background-color:#333 !important;color:#ccc !important;border-bottom-color:#424242 !important}div.toast div.toast-body{background-color:#383838 !important;color:#ccc !important}div.toast div.toast-progressbar{background-color:#5c66d6 !important}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{border-right-color:#333 !important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c !important}.setting_btn_menu a:hover{background-color:#333 !important}.table{color:#ccc !important}.table th,.table td{border-color:#333 !important}.btn-outline-primary.focus,.btn-outline-primary:focus,.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(144,153,255,.29) !important}.bottomNav{background-color:#272727 !important}.bottomNav .bottomNavButton{color:#999}.bottomNav .bottomNavButton.active{color:#5c66d6 !important}.subNav{background-color:#272727 !important}/*# sourceMappingURL=dark.min.css.map */ +:root{--green: hsl(120deg, 30%, 50%) !important;--blue: hsl(235deg, 60%, 60%) !important;--red: hsl(0deg, 60%, 60%) !important;--magenta: hsl(315deg, 60%, 60%) !important}body{background:#222;color:#ccc}.btn-primary{color:#e6e6e6 !important;border-color:#5c66d6 !important;background:#5c66d6 !important}.btn-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-outline-primary{color:#5c66d6 !important;border-color:#5c66d6 !important;background:rgba(0,0,0,0) !important}.btn-outline-primary:hover,.btn-outline-primary.active{color:#e6e6e6 !important}.btn-outline-primary.active{background-color:#5c66d6 !important;border-color:#5c66d6 !important}.btn-outline-primary:hover{background-color:#3340cc !important;border-color:#3340cc !important}.btn-success{color:#e6e6e6 !important;border-color:#59a659 !important;background:#59a659 !important}.btn-success:hover{background-color:#478547 !important;border-color:#478547 !important}.list-group-item{background-color:#272727;border-color:#272727;color:#fff}.list-group-item:hover{background-color:#333;border-color:#333;color:#fff}.delete-peer-bulk-badge.badge-danger{background-color:#d65c5c}.delete-peer-bulk-badge.badge-danger:hover{background-color:#c33}#delete_bulk_modal .list-group a.active{background-color:#d65c5c;border:#d65c5c}#delete_bulk_modal .list-group a.active:hover{background-color:#c33;border:#c33}#available_ip_modal .list-group a.active{background-color:#5c66d6;border:#5c66d6}#available_ip_modal .list-group a.active:hover{background-color:#3340cc;border:#3340cc}.available-ip-badge.badge-primary{background-color:#5c66d6}.available-ip-badge.badge-primary:hover{background-color:#3340cc}.btn-outline-success{color:#59a659 !important;border-color:#59a659 !important;background:rgba(0,0,0,0) !important}.btn-outline-success:hover,.btn-outline-success.active{color:#e6e6e6 !important}.btn-outline-success.active{background-color:#59a659 !important;border-color:#59a659 !important}.btn-outline-success:hover{background-color:#478547 !important;border-color:#478547 !important}.btn-danger{color:#e6e6e6 !important;border-color:#d65c5c !important;background:#d65c5c !important}.btn-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-outline-danger{color:#d65c5c !important;border-color:#d65c5c !important;background:rgba(0,0,0,0) !important}.btn-outline-danger:hover,.btn-outline-danger.active{color:#e6e6e6 !important}.btn-outline-danger.active{background-color:#d65c5c !important;border-color:#d65c5c !important}.btn-outline-danger:hover{background-color:#c33 !important;border-color:#c33 !important}.btn-secondary{color:#e6e6e6 !important;border-color:#424242 !important;background:#424242 !important}.btn-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-outline-secondary{color:#424242 !important;border-color:#424242 !important;background:rgba(0,0,0,0) !important}.btn-outline-secondary:hover,.btn-outline-secondary.active{color:#e6e6e6 !important}.btn-outline-secondary.active{background-color:#424242 !important;border-color:#424242 !important}.btn-outline-secondary:hover{background-color:#383838 !important;border-color:#383838 !important}.btn-control.btn-lock-peer.lock{color:#d65c5c !important}.btn-control.btn-lock-peer.lock:hover{color:#c33 !important}.btn-control:hover{background-color:rgba(0,0,0,0) !important}.btn-control:hover.btn-outline-primary{color:#3340cc !important}.btn-control:hover.btn-outline-success{color:#478547 !important}.btn-control:hover.btn-outline-danger{color:#c33 !important}.btn-control:hover.btn-outline-secondary{color:#383838 !important}.form-control{background-color:#2c2c2c !important;border-color:rgba(0,0,0,0) !important;color:#ccc !important}.form-control:disabled{color:#777 !important}.card .form-control{background:#2c2c2c !important}.conf_card a{color:#5c66d6}.conf_card:hover{border-color:#5c66d6}.sidebar .nav-link,.bottomNavContainer .nav-link{color:#ccc}.sidebar .nav-link:hover,.bottomNavContainer .nav-link:hover{background:#222}nav#sidebarMenu.col-md-3.col-lg-2.d-md-block.bg-light.sidebar.collapse,.navbar-brand,.bg-dark{background-color:#1e1e1e !important;background:#1e1e1e !important}.card{background:#272727}.text-muted{color:gray !important}.text-danger{color:#d65c5c !important}.text-success{color:#59a659 !important}.text-primary{color:#5c66d6 !important}.text-info{color:#5cc2d6 !important}a.text-success:focus,a.text-success:hover{color:#478547 !important}a.text-danger:focus,a.text-danger:hover{color:#c33 !important}a.text-info:focus,a.text-info:hover{color:#33b3cc !important}.dot-running{background-color:#59a659 !important}.card-running{border-color:#59a659}.toggle--switch:checked+.toggleLabel::before{background-color:#5c66d6 !important}.toggle--switch:checked+.toggleLabel{background-color:#2e336b !important;border-color:#5c66d6 !important}.sidebar .nav-link.active,.bottomNavContainer .nav-link.active{color:#5c66d6 !important}hr{border-color:#2e2e2e}.modal-content{background-color:#222}.modal-header,.modal-footer{background-color:#1e1e1e;border-color:#2e2e2e}code{color:#d65cb8}.close{color:#ccc;text-shadow:none}.close:hover{color:#b3b3b3}.chartContainer.fullScreen{background-color:#222 !important}.popover{background-color:#333 !important;border:none !important}.popover-body{color:#ccc !important}div.toast{background-color:#424242 !important}div.toast div.toast-header{background-color:#333 !important;color:#ccc !important;border-bottom-color:#424242 !important}div.toast div.toast-body{background-color:#383838 !important;color:#ccc !important}div.toast div.toast-progressbar{background-color:#5c66d6 !important}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{border-right-color:#333 !important}.btn-manage-group .setting_btn_menu{background-color:#2c2c2c !important}.setting_btn_menu a:hover{background-color:#333 !important}.table{color:#ccc !important}.table th,.table td{border-color:#333 !important}.btn-outline-primary.focus,.btn-outline-primary:focus,.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(144,153,255,.29) !important}.bottomNav{background-color:#272727 !important}.bottomNav .bottomNavButton{color:#999}.bottomNav .bottomNavButton.active{color:#5c66d6 !important}.bottomNav .subNav{background-color:#272727 !important}.key:hover{color:#5c66d6}/*# sourceMappingURL=dark.min.css.map */ diff --git a/src/static/css/theme/dark.min.css.map b/src/static/css/theme/dark.min.css.map index 4cb79dbf..16d0bd84 100644 --- a/src/static/css/theme/dark.min.css.map +++ b/src/static/css/theme/dark.min.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA,MACE,0CACA,yCACA,sCACA,4CAGF,KACE,WAvCS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ACE,oCAGF,0BACE,iCAGF,OACE,sBAEA,oBAEE,6BAKJ,4FACE,wDAIA,WACE,oCAIA,4BACE,MA7WK,KAgXT,mCACE,yBAIJ,QACE","file":"dark.min.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["dark.scss"],"names":[],"mappings":"AAgCA,MACE,0CACA,yCACA,sCACA,4CAGF,KACE,WAvCS,KAwCT,MAdS,KAkBX,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,aACE,yBACA,gCACA,8BAEA,mBACE,oCACA,gCAIJ,iBACE,iBAtFS,QAuFT,aAvFS,QAwFT,WAEA,uBACE,iBAxFO,KAyFP,aAzFO,KA0FP,WAMJ,qCACE,iBAxFQ,QAyFR,2CACE,iBA3FM,KAiGN,wCACE,iBAjGI,QAkGJ,OAlGI,QAoGJ,8CACE,iBAtGE,KAuGF,OAvGE,KA+GN,yCACE,iBA5GK,QA6GL,OA7GK,QA+GL,+CACE,iBAjHG,QAkHH,OAlHG,QAwHX,kCACE,iBAxHS,QAyHT,wCACE,iBA3HO,QA+HX,qBACE,yBACA,gCACA,oCAEA,uDAEE,yBAGF,4BACE,oCACA,gCAGF,2BACE,oCACA,gCAIJ,YACE,yBACA,gCACA,8BAEA,kBACE,iCACA,6BAIJ,oBACE,yBACA,gCACA,oCAEA,qDAEE,yBAGF,2BACE,oCACA,gCAGF,0BACE,iCACA,6BAIJ,eACE,yBACA,gCACA,8BAEA,qBACE,oCACA,gCAIJ,uBACE,yBACA,gCACA,oCAEA,2DAEE,yBAGF,8BACE,oCACA,gCAGF,6BACE,oCACA,gCAKF,gCACE,yBACA,sCACE,sBAIJ,mBACE,0CAEA,uCACE,yBAGF,uCACE,yBAGF,sCACE,sBAGF,yCACE,yBAKN,cACE,oCACA,sCACA,sBAGF,uBACE,sBAGF,oBACE,8BAIA,aACE,MAhQO,QAkQT,iBACE,aAnQO,QAuQX,iDAEE,MAhQS,KAkQT,6DACE,WA7RO,KAiSX,8FAGE,oCACA,8BAGF,MACE,WAvSS,QA0SX,YACE,sBAGF,aACE,yBAGF,cACE,yBAGF,cACE,yBAGF,WACE,yBAGF,0CAEE,yBAGF,wCAEE,sBAGF,oCAEE,yBAGF,aACE,oCAGF,cACE,aAzUU,QA4UZ,6CACE,oCAEF,qCACE,oCACA,gCAGF,+DAEE,yBAGF,GACE,aAjWS,QAoWX,eACE,iBAzWS,KA4WX,4BAEE,iBA/WS,QAgXT,aA3WS,QA8WX,KACE,MA5VY,QA+Vd,OACE,MA7VS,KA8VT,iBAEA,aACE,MAhWO,QAoWX,2BACE,iCAGF,SACE,iCACA,uBAGF,cACE,sBAGF,UACE,oCAEA,2BACE,iCACA,sBACA,uCAGF,yBACE,oCACA,sBAGF,gCACE,oCAIJ,mFAEE,mCAGF,oCACE,oCAGF,0BACE,iCAGF,OACE,sBAEA,oBAEE,6BAKJ,4FACE,wDAIA,WACE,oCAIA,4BACE,MAraK,KAyaT,mCACE,yBAGF,mBACE,oCAKJ,WACE,MA/bS","file":"dark.min.css"} \ No newline at end of file diff --git a/src/static/css/theme/dark.scss b/src/static/css/theme/dark.scss index b0ecc8be..f6b6d978 100644 --- a/src/static/css/theme/dark.scss +++ b/src/static/css/theme/dark.scss @@ -86,6 +86,62 @@ body { } } +.list-group-item{ + background-color: $grey-400; + border-color: $grey-400; + color: white; + + &:hover{ + background-color: $grey-700; + border-color: $grey-700; + color: white; + } +} + + + +.delete-peer-bulk-badge.badge-danger{ + background-color: $red-500; + &:hover{ + background-color: $red-400; + } +} + +#delete_bulk_modal{ + .list-group{ + a.active{ + background-color: $red-500; + border: $red-500; + + &:hover{ + background-color: $red-400; + border: $red-400; + } + } + } +} + +#available_ip_modal{ + .list-group{ + a.active{ + background-color: $blue-500; + border: $blue-500; + + &:hover{ + background-color: $blue-400; + border: $blue-400; + } + } + } +} + +.available-ip-badge.badge-primary{ + background-color: $blue-500; + &:hover{ + background-color: $blue-400; + } +} + .btn-outline-success { color: $green-500 !important; border-color: $green-500 !important; @@ -395,11 +451,19 @@ div.toast { color: $text-400; } } + .bottomNavButton.active{ color: $blue-500 !important; } + + .subNav{ + background-color: $grey-400 !important; + } + } -.subNav{ - background-color: $grey-400 !important; +.key:hover{ + color: $blue-500; } + + diff --git a/src/static/js/configurationTool.js b/src/static/js/configurationTool.js index 355b95ff..4eb59e9d 100644 --- a/src/static/js/configurationTool.js +++ b/src/static/js/configurationTool.js @@ -55,24 +55,26 @@ function loadPeerDataUsageChartDone(res){ configurations.peerDataUsageChartObj().data.datasets[1].data = []; console.log(res); let data = res.data; - 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; + 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(); } - configurations.peerDataUsageChartObj().update(); } } diff --git a/src/templates/header.html b/src/templates/header.html index bfb8e4fb..3834eb88 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -3,11 +3,10 @@ {{ title }} | WGDashboard - - - + + @@ -15,7 +14,9 @@ - + {% if session["theme"] == "dark" %} + + {% endif %} diff --git a/src/templates/navbar.html b/src/templates/navbar.html index 261dd19d..d489243e 100644 --- a/src/templates/navbar.html +++ b/src/templates/navbar.html @@ -4,6 +4,7 @@ data-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> --> +
diff --git a/src/templates/settings.html b/src/templates/settings.html index c7e2ebc7..881401a3 100644 --- a/src/templates/settings.html +++ b/src/templates/settings.html @@ -16,6 +16,26 @@ {% endif %}

Settings


+
+
Dashboard Theme
+
+
+
+ +
+
+ +
+
+
+
+
{% if required_auth == "true" %}
Peer Default Settings
@@ -201,5 +221,29 @@ $(".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(); + }else{ + $("head").append(''); + } + } + }); + } + }); + + \ No newline at end of file diff --git a/src/templates/sidebar.html b/src/templates/sidebar.html index 3f24d2bf..09d415f9 100644 --- a/src/templates/sidebar.html +++ b/src/templates/sidebar.html @@ -1,11 +1,9 @@
- -
',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent",customClass:"",sanitize:!0,sanitizeFn:null,whiteList:Qt,popperConfig:null},Zt={HIDE:"hide.bs.tooltip",HIDDEN:"hidden.bs.tooltip",SHOW:"show.bs.tooltip",SHOWN:"shown.bs.tooltip",INSERTED:"inserted.bs.tooltip",CLICK:"click.bs.tooltip",FOCUSIN:"focusin.bs.tooltip",FOCUSOUT:"focusout.bs.tooltip",MOUSEENTER:"mouseenter.bs.tooltip",MOUSELEAVE:"mouseleave.bs.tooltip"},te=function(){function t(t,e){if("undefined"==typeof It)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=t,this.config=this._getConfig(e),this.tip=null,this._setListeners()}var e=t.prototype;return e.enable=function(){this._isEnabled=!0},e.disable=function(){this._isEnabled=!1},e.toggleEnabled=function(){this._isEnabled=!this._isEnabled},e.toggle=function(t){if(this._isEnabled)if(t){var e=this.constructor.DATA_KEY,n=i.default(t.currentTarget).data(e);n||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),i.default(t.currentTarget).data(e,n)),n._activeTrigger.click=!n._activeTrigger.click,n._isWithActiveTrigger()?n._enter(null,n):n._leave(null,n)}else{if(i.default(this.getTipElement()).hasClass("show"))return void this._leave(null,this);this._enter(null,this)}},e.dispose=function(){clearTimeout(this._timeout),i.default.removeData(this.element,this.constructor.DATA_KEY),i.default(this.element).off(this.constructor.EVENT_KEY),i.default(this.element).closest(".modal").off("hide.bs.modal",this._hideModalHandler),this.tip&&i.default(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},e.show=function(){var t=this;if("none"===i.default(this.element).css("display"))throw new Error("Please use show on visible elements");var e=i.default.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){i.default(this.element).trigger(e);var n=l.findShadowRoot(this.element),o=i.default.contains(null!==n?n:this.element.ownerDocument.documentElement,this.element);if(e.isDefaultPrevented()||!o)return;var r=this.getTipElement(),a=l.getUID(this.constructor.NAME);r.setAttribute("id",a),this.element.setAttribute("aria-describedby",a),this.setContent(),this.config.animation&&i.default(r).addClass("fade");var s="function"==typeof this.config.placement?this.config.placement.call(this,r,this.element):this.config.placement,u=this._getAttachment(s);this.addAttachmentClass(u);var f=this._getContainer();i.default(r).data(this.constructor.DATA_KEY,this),i.default.contains(this.element.ownerDocument.documentElement,this.tip)||i.default(r).appendTo(f),i.default(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new It(this.element,r,this._getPopperConfig(u)),i.default(r).addClass("show"),i.default(r).addClass(this.config.customClass),"ontouchstart"in document.documentElement&&i.default(document.body).children().on("mouseover",null,i.default.noop);var d=function(){t.config.animation&&t._fixTransition();var e=t._hoverState;t._hoverState=null,i.default(t.element).trigger(t.constructor.Event.SHOWN),"out"===e&&t._leave(null,t)};if(i.default(this.tip).hasClass("fade")){var c=l.getTransitionDurationFromElement(this.tip);i.default(this.tip).one(l.TRANSITION_END,d).emulateTransitionEnd(c)}else d()}},e.hide=function(t){var e=this,n=this.getTipElement(),o=i.default.Event(this.constructor.Event.HIDE),r=function(){"show"!==e._hoverState&&n.parentNode&&n.parentNode.removeChild(n),e._cleanTipClass(),e.element.removeAttribute("aria-describedby"),i.default(e.element).trigger(e.constructor.Event.HIDDEN),null!==e._popper&&e._popper.destroy(),t&&t()};if(i.default(this.element).trigger(o),!o.isDefaultPrevented()){if(i.default(n).removeClass("show"),"ontouchstart"in document.documentElement&&i.default(document.body).children().off("mouseover",null,i.default.noop),this._activeTrigger.click=!1,this._activeTrigger.focus=!1,this._activeTrigger.hover=!1,i.default(this.tip).hasClass("fade")){var a=l.getTransitionDurationFromElement(n);i.default(n).one(l.TRANSITION_END,r).emulateTransitionEnd(a)}else r();this._hoverState=""}},e.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},e.isWithContent=function(){return Boolean(this.getTitle())},e.addAttachmentClass=function(t){i.default(this.getTipElement()).addClass("bs-tooltip-"+t)},e.getTipElement=function(){return this.tip=this.tip||i.default(this.config.template)[0],this.tip},e.setContent=function(){var t=this.getTipElement();this.setElementContent(i.default(t.querySelectorAll(".tooltip-inner")),this.getTitle()),i.default(t).removeClass("fade show")},e.setElementContent=function(t,e){"object"!=typeof e||!e.nodeType&&!e.jquery?this.config.html?(this.config.sanitize&&(e=Vt(e,this.config.whiteList,this.config.sanitizeFn)),t.html(e)):t.text(e):this.config.html?i.default(e).parent().is(t)||t.empty().append(e):t.text(i.default(e).text())},e.getTitle=function(){var t=this.element.getAttribute("data-original-title");return t||(t="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),t},e._getPopperConfig=function(t){var e=this;return a({},{placement:t,modifiers:{offset:this._getOffset(),flip:{behavior:this.config.fallbackPlacement},arrow:{element:".arrow"},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(t){t.originalPlacement!==t.placement&&e._handlePopperPlacementChange(t)},onUpdate:function(t){return e._handlePopperPlacementChange(t)}},this.config.popperConfig)},e._getOffset=function(){var t=this,e={};return"function"==typeof this.config.offset?e.fn=function(e){return e.offsets=a({},e.offsets,t.config.offset(e.offsets,t.element)||{}),e}:e.offset=this.config.offset,e},e._getContainer=function(){return!1===this.config.container?document.body:l.isElement(this.config.container)?i.default(this.config.container):i.default(document).find(this.config.container)},e._getAttachment=function(t){return $t[t.toUpperCase()]},e._setListeners=function(){var t=this;this.config.trigger.split(" ").forEach((function(e){if("click"===e)i.default(t.element).on(t.constructor.Event.CLICK,t.config.selector,(function(e){return t.toggle(e)}));else if("manual"!==e){var n="hover"===e?t.constructor.Event.MOUSEENTER:t.constructor.Event.FOCUSIN,o="hover"===e?t.constructor.Event.MOUSELEAVE:t.constructor.Event.FOCUSOUT;i.default(t.element).on(n,t.config.selector,(function(e){return t._enter(e)})).on(o,t.config.selector,(function(e){return t._leave(e)}))}})),this._hideModalHandler=function(){t.element&&t.hide()},i.default(this.element).closest(".modal").on("hide.bs.modal",this._hideModalHandler),this.config.selector?this.config=a({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},e._fixTitle=function(){var t=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==t)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},e._enter=function(t,e){var n=this.constructor.DATA_KEY;(e=e||i.default(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),i.default(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusin"===t.type?"focus":"hover"]=!0),i.default(e.getTipElement()).hasClass("show")||"show"===e._hoverState?e._hoverState="show":(clearTimeout(e._timeout),e._hoverState="show",e.config.delay&&e.config.delay.show?e._timeout=setTimeout((function(){"show"===e._hoverState&&e.show()}),e.config.delay.show):e.show())},e._leave=function(t,e){var n=this.constructor.DATA_KEY;(e=e||i.default(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),i.default(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusout"===t.type?"focus":"hover"]=!1),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState="out",e.config.delay&&e.config.delay.hide?e._timeout=setTimeout((function(){"out"===e._hoverState&&e.hide()}),e.config.delay.hide):e.hide())},e._isWithActiveTrigger=function(){for(var t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1},e._getConfig=function(t){var e=i.default(this.element).data();return Object.keys(e).forEach((function(t){-1!==Kt.indexOf(t)&&delete e[t]})),"number"==typeof(t=a({},this.constructor.Default,e,"object"==typeof t&&t?t:{})).delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),l.typeCheckConfig(Yt,t,this.constructor.DefaultType),t.sanitize&&(t.template=Vt(t.template,t.whiteList,t.sanitizeFn)),t},e._getDelegateConfig=function(){var t={};if(this.config)for(var e in this.config)this.constructor.Default[e]!==this.config[e]&&(t[e]=this.config[e]);return t},e._cleanTipClass=function(){var t=i.default(this.getTipElement()),e=t.attr("class").match(Xt);null!==e&&e.length&&t.removeClass(e.join(""))},e._handlePopperPlacementChange=function(t){this.tip=t.instance.popper,this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(t.placement))},e._fixTransition=function(){var t=this.getTipElement(),e=this.config.animation;null===t.getAttribute("x-placement")&&(i.default(t).removeClass("fade"),this.config.animation=!1,this.hide(),this.show(),this.config.animation=e)},t._jQueryInterface=function(e){return this.each((function(){var n=i.default(this),o=n.data("bs.tooltip"),r="object"==typeof e&&e;if((o||!/dispose|hide/.test(e))&&(o||(o=new t(this,r),n.data("bs.tooltip",o)),"string"==typeof e)){if("undefined"==typeof o[e])throw new TypeError('No method named "'+e+'"');o[e]()}}))},r(t,null,[{key:"VERSION",get:function(){return"4.6.0"}},{key:"Default",get:function(){return Jt}},{key:"NAME",get:function(){return Yt}},{key:"DATA_KEY",get:function(){return"bs.tooltip"}},{key:"Event",get:function(){return Zt}},{key:"EVENT_KEY",get:function(){return".bs.tooltip"}},{key:"DefaultType",get:function(){return Gt}}]),t}();i.default.fn[Yt]=te._jQueryInterface,i.default.fn[Yt].Constructor=te,i.default.fn[Yt].noConflict=function(){return i.default.fn[Yt]=zt,te._jQueryInterface};var ee="popover",ne=i.default.fn[ee],ie=new RegExp("(^|\\s)bs-popover\\S+","g"),oe=a({},te.Default,{placement:"right",trigger:"click",content:"",template:''}),re=a({},te.DefaultType,{content:"(string|element|function)"}),ae={HIDE:"hide.bs.popover",HIDDEN:"hidden.bs.popover",SHOW:"show.bs.popover",SHOWN:"shown.bs.popover",INSERTED:"inserted.bs.popover",CLICK:"click.bs.popover",FOCUSIN:"focusin.bs.popover",FOCUSOUT:"focusout.bs.popover",MOUSEENTER:"mouseenter.bs.popover",MOUSELEAVE:"mouseleave.bs.popover"},se=function(t){var e,n;function o(){return t.apply(this,arguments)||this}n=t,(e=o).prototype=Object.create(n.prototype),e.prototype.constructor=e,e.__proto__=n;var a=o.prototype;return a.isWithContent=function(){return this.getTitle()||this._getContent()},a.addAttachmentClass=function(t){i.default(this.getTipElement()).addClass("bs-popover-"+t)},a.getTipElement=function(){return this.tip=this.tip||i.default(this.config.template)[0],this.tip},a.setContent=function(){var t=i.default(this.getTipElement());this.setElementContent(t.find(".popover-header"),this.getTitle());var e=this._getContent();"function"==typeof e&&(e=e.call(this.element)),this.setElementContent(t.find(".popover-body"),e),t.removeClass("fade show")},a._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},a._cleanTipClass=function(){var t=i.default(this.getTipElement()),e=t.attr("class").match(ie);null!==e&&e.length>0&&t.removeClass(e.join(""))},o._jQueryInterface=function(t){return this.each((function(){var e=i.default(this).data("bs.popover"),n="object"==typeof t?t:null;if((e||!/dispose|hide/.test(t))&&(e||(e=new o(this,n),i.default(this).data("bs.popover",e)),"string"==typeof t)){if("undefined"==typeof e[t])throw new TypeError('No method named "'+t+'"');e[t]()}}))},r(o,null,[{key:"VERSION",get:function(){return"4.6.0"}},{key:"Default",get:function(){return oe}},{key:"NAME",get:function(){return ee}},{key:"DATA_KEY",get:function(){return"bs.popover"}},{key:"Event",get:function(){return ae}},{key:"EVENT_KEY",get:function(){return".bs.popover"}},{key:"DefaultType",get:function(){return re}}]),o}(te);i.default.fn[ee]=se._jQueryInterface,i.default.fn[ee].Constructor=se,i.default.fn[ee].noConflict=function(){return i.default.fn[ee]=ne,se._jQueryInterface};var le="scrollspy",ue=i.default.fn[le],fe={offset:10,method:"auto",target:""},de={offset:"number",method:"string",target:"(string|element)"},ce=function(){function t(t,e){var n=this;this._element=t,this._scrollElement="BODY"===t.tagName?window:t,this._config=this._getConfig(e),this._selector=this._config.target+" .nav-link,"+this._config.target+" .list-group-item,"+this._config.target+" .dropdown-item",this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,i.default(this._scrollElement).on("scroll.bs.scrollspy",(function(t){return n._process(t)})),this.refresh(),this._process()}var e=t.prototype;return e.refresh=function(){var t=this,e=this._scrollElement===this._scrollElement.window?"offset":"position",n="auto"===this._config.method?e:this._config.method,o="position"===n?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),[].slice.call(document.querySelectorAll(this._selector)).map((function(t){var e,r=l.getSelectorFromElement(t);if(r&&(e=document.querySelector(r)),e){var a=e.getBoundingClientRect();if(a.width||a.height)return[i.default(e)[n]().top+o,r]}return null})).filter((function(t){return t})).sort((function(t,e){return t[0]-e[0]})).forEach((function(e){t._offsets.push(e[0]),t._targets.push(e[1])}))},e.dispose=function(){i.default.removeData(this._element,"bs.scrollspy"),i.default(this._scrollElement).off(".bs.scrollspy"),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},e._getConfig=function(t){if("string"!=typeof(t=a({},fe,"object"==typeof t&&t?t:{})).target&&l.isElement(t.target)){var e=i.default(t.target).attr("id");e||(e=l.getUID(le),i.default(t.target).attr("id",e)),t.target="#"+e}return l.typeCheckConfig(le,t,de),t},e._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop},e._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},e._getOffsetHeight=function(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height},e._process=function(){var t=this._getScrollTop()+this._config.offset,e=this._getScrollHeight(),n=this._config.offset+e-this._getOffsetHeight();if(this._scrollHeight!==e&&this.refresh(),t>=n){var i=this._targets[this._targets.length-1];this._activeTarget!==i&&this._activate(i)}else{if(this._activeTarget&&t0)return this._activeTarget=null,void this._clear();for(var o=this._offsets.length;o--;){this._activeTarget!==this._targets[o]&&t>=this._offsets[o]&&("undefined"==typeof this._offsets[o+1]||t li > .active":".active";n=(n=i.default.makeArray(i.default(o).find(a)))[n.length-1]}var s=i.default.Event("hide.bs.tab",{relatedTarget:this._element}),u=i.default.Event("show.bs.tab",{relatedTarget:n});if(n&&i.default(n).trigger(s),i.default(this._element).trigger(u),!u.isDefaultPrevented()&&!s.isDefaultPrevented()){r&&(e=document.querySelector(r)),this._activate(this._element,o);var f=function(){var e=i.default.Event("hidden.bs.tab",{relatedTarget:t._element}),o=i.default.Event("shown.bs.tab",{relatedTarget:n});i.default(n).trigger(e),i.default(t._element).trigger(o)};e?this._activate(e,e.parentNode,f):f()}}},e.dispose=function(){i.default.removeData(this._element,"bs.tab"),this._element=null},e._activate=function(t,e,n){var o=this,r=(!e||"UL"!==e.nodeName&&"OL"!==e.nodeName?i.default(e).children(".active"):i.default(e).find("> li > .active"))[0],a=n&&r&&i.default(r).hasClass("fade"),s=function(){return o._transitionComplete(t,r,n)};if(r&&a){var u=l.getTransitionDurationFromElement(r);i.default(r).removeClass("show").one(l.TRANSITION_END,s).emulateTransitionEnd(u)}else s()},e._transitionComplete=function(t,e,n){if(e){i.default(e).removeClass("active");var o=i.default(e.parentNode).find("> .dropdown-menu .active")[0];o&&i.default(o).removeClass("active"),"tab"===e.getAttribute("role")&&e.setAttribute("aria-selected",!1)}if(i.default(t).addClass("active"),"tab"===t.getAttribute("role")&&t.setAttribute("aria-selected",!0),l.reflow(t),t.classList.contains("fade")&&t.classList.add("show"),t.parentNode&&i.default(t.parentNode).hasClass("dropdown-menu")){var r=i.default(t).closest(".dropdown")[0];if(r){var a=[].slice.call(r.querySelectorAll(".dropdown-toggle"));i.default(a).addClass("active")}t.setAttribute("aria-expanded",!0)}n&&n()},t._jQueryInterface=function(e){return this.each((function(){var n=i.default(this),o=n.data("bs.tab");if(o||(o=new t(this),n.data("bs.tab",o)),"string"==typeof e){if("undefined"==typeof o[e])throw new TypeError('No method named "'+e+'"');o[e]()}}))},r(t,null,[{key:"VERSION",get:function(){return"4.6.0"}}]),t}();i.default(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',(function(t){t.preventDefault(),pe._jQueryInterface.call(i.default(this),"show")})),i.default.fn.tab=pe._jQueryInterface,i.default.fn.tab.Constructor=pe,i.default.fn.tab.noConflict=function(){return i.default.fn.tab=he,pe._jQueryInterface};var me=i.default.fn.toast,ge={animation:"boolean",autohide:"boolean",delay:"number"},ve={animation:!0,autohide:!0,delay:500},_e=function(){function t(t,e){this._element=t,this._config=this._getConfig(e),this._timeout=null,this._setListeners()}var e=t.prototype;return e.show=function(){var t=this,e=i.default.Event("show.bs.toast");if(i.default(this._element).trigger(e),!e.isDefaultPrevented()){this._clearTimeout(),this._config.animation&&this._element.classList.add("fade");var n=function(){t._element.classList.remove("showing"),t._element.classList.add("show"),i.default(t._element).trigger("shown.bs.toast"),t._config.autohide&&(t._timeout=setTimeout((function(){t.hide()}),t._config.delay))};if(this._element.classList.remove("hide"),l.reflow(this._element),this._element.classList.add("showing"),this._config.animation){var o=l.getTransitionDurationFromElement(this._element);i.default(this._element).one(l.TRANSITION_END,n).emulateTransitionEnd(o)}else n()}},e.hide=function(){if(this._element.classList.contains("show")){var t=i.default.Event("hide.bs.toast");i.default(this._element).trigger(t),t.isDefaultPrevented()||this._close()}},e.dispose=function(){this._clearTimeout(),this._element.classList.contains("show")&&this._element.classList.remove("show"),i.default(this._element).off("click.dismiss.bs.toast"),i.default.removeData(this._element,"bs.toast"),this._element=null,this._config=null},e._getConfig=function(t){return t=a({},ve,i.default(this._element).data(),"object"==typeof t&&t?t:{}),l.typeCheckConfig("toast",t,this.constructor.DefaultType),t},e._setListeners=function(){var t=this;i.default(this._element).on("click.dismiss.bs.toast",'[data-dismiss="toast"]',(function(){return t.hide()}))},e._close=function(){var t=this,e=function(){t._element.classList.add("hide"),i.default(t._element).trigger("hidden.bs.toast")};if(this._element.classList.remove("show"),this._config.animation){var n=l.getTransitionDurationFromElement(this._element);i.default(this._element).one(l.TRANSITION_END,e).emulateTransitionEnd(n)}else e()},e._clearTimeout=function(){clearTimeout(this._timeout),this._timeout=null},t._jQueryInterface=function(e){return this.each((function(){var n=i.default(this),o=n.data("bs.toast");if(o||(o=new t(this,"object"==typeof e&&e),n.data("bs.toast",o)),"string"==typeof e){if("undefined"==typeof o[e])throw new TypeError('No method named "'+e+'"');o[e](this)}}))},r(t,null,[{key:"VERSION",get:function(){return"4.6.0"}},{key:"DefaultType",get:function(){return ge}},{key:"Default",get:function(){return ve}}]),t}();i.default.fn.toast=_e._jQueryInterface,i.default.fn.toast.Constructor=_e,i.default.fn.toast.noConflict=function(){return i.default.fn.toast=me,_e._jQueryInterface},t.Alert=d,t.Button=h,t.Carousel=y,t.Collapse=S,t.Dropdown=Ft,t.Modal=qt,t.Popover=se,t.Scrollspy=ce,t.Tab=pe,t.Toast=_e,t.Tooltip=te,t.Util=l,Object.defineProperty(t,"__esModule",{value:!0})})); -//# sourceMappingURL=bootstrap.bundle.min.js.map \ No newline at end of file diff --git a/src/static/js/bootstrap.bundle.min.js.map b/src/static/js/bootstrap.bundle.min.js.map deleted file mode 100644 index 7fcd06e5..00000000 --- a/src/static/js/bootstrap.bundle.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../js/src/util.js","../../js/src/alert.js","../../js/src/button.js","../../js/src/carousel.js","../../js/src/collapse.js","../../node_modules/popper.js/dist/esm/popper.js","../../js/src/dropdown.js","../../js/src/modal.js","../../js/src/tools/sanitizer.js","../../js/src/tooltip.js","../../js/src/popover.js","../../js/src/scrollspy.js","../../js/src/tab.js","../../js/src/toast.js"],"names":["transitionEndEmulator","duration","_this","this","called","$","one","Util","TRANSITION_END","setTimeout","triggerTransitionEnd","getUID","prefix","Math","random","document","getElementById","getSelectorFromElement","element","selector","getAttribute","hrefAttr","trim","querySelector","_","getTransitionDurationFromElement","transitionDuration","css","transitionDelay","floatTransitionDuration","parseFloat","floatTransitionDelay","split","reflow","offsetHeight","trigger","supportsTransitionEnd","Boolean","isElement","obj","nodeType","typeCheckConfig","componentName","config","configTypes","property","Object","prototype","hasOwnProperty","call","expectedTypes","value","valueType","toString","match","toLowerCase","RegExp","test","Error","toUpperCase","findShadowRoot","documentElement","attachShadow","getRootNode","root","ShadowRoot","parentNode","jQueryDetection","TypeError","version","fn","jquery","emulateTransitionEnd","event","special","bindType","delegateType","handle","target","is","handleObj","handler","apply","arguments","NAME","JQUERY_NO_CONFLICT","Alert","_element","close","rootElement","_getRootElement","_triggerCloseEvent","isDefaultPrevented","_removeElement","dispose","removeData","parent","closest","closeEvent","Event","removeClass","hasClass","_destroyElement","detach","remove","_jQueryInterface","each","$element","data","_handleDismiss","alertInstance","preventDefault","on","Constructor","noConflict","Button","shouldAvoidTriggerChange","toggle","triggerChangeEvent","addAriaPressed","input","type","checked","classList","contains","activeElement","focus","hasAttribute","setAttribute","toggleClass","avoidTriggerChange","button","initialButton","inputBtn","tagName","window","buttons","slice","querySelectorAll","i","len","length","add","EVENT_KEY","Default","interval","keyboard","slide","pause","wrap","touch","DefaultType","PointerType","TOUCH","PEN","Carousel","_items","_interval","_activeElement","_isPaused","_isSliding","touchTimeout","touchStartX","touchDeltaX","_config","_getConfig","_indicatorsElement","_touchSupported","navigator","maxTouchPoints","_pointerEvent","PointerEvent","MSPointerEvent","_addEventListeners","next","_slide","nextWhenVisible","hidden","prev","cycle","clearInterval","_updateInterval","setInterval","visibilityState","bind","to","index","activeIndex","_getItemIndex","direction","off","_extends","_handleSwipe","absDeltax","abs","_this2","_keydown","_addTouchEventListeners","_this3","start","originalEvent","pointerType","clientX","touches","end","clearTimeout","e","move","which","indexOf","_getItemByDirection","isNextDirection","isPrevDirection","lastItemIndex","itemIndex","_triggerSlideEvent","relatedTarget","eventDirectionName","targetIndex","fromIndex","slideEvent","from","_setActiveIndicatorElement","indicators","nextIndicator","children","addClass","elementInterval","parseInt","defaultInterval","directionalClassName","orderClassName","_this4","activeElementIndex","nextElement","nextElementIndex","isCycling","slidEvent","CLASS_NAME_ACTIVE","action","ride","_dataApiClickHandler","slideIndex","carousels","$carousel","Collapse","_isTransitioning","_triggerArray","id","toggleList","elem","filterElement","filter","foundElem","_selector","push","_parent","_getParent","_addAriaAndCollapsedClass","hide","show","actives","activesData","not","startEvent","dimension","_getDimension","style","attr","setTransitioning","scrollSize","CLASS_NAME_COLLAPSE","getBoundingClientRect","triggerArrayLength","isTransitioning","_getTargetFromElement","triggerArray","isOpen","currentTarget","$trigger","selectors","$target","isBrowser","timeoutDuration","longerTimeoutBrowsers","userAgent","debounce","Promise","resolve","then","scheduled","isFunction","functionToCheck","getStyleComputedProperty","ownerDocument","defaultView","getComputedStyle","getParentNode","nodeName","host","getScrollParent","body","_getStyleComputedProp","overflow","overflowX","overflowY","getReferenceNode","reference","referenceNode","isIE11","MSInputMethodContext","documentMode","isIE10","isIE","getOffsetParent","noOffsetParent","offsetParent","nextElementSibling","getRoot","node","findCommonOffsetParent","element1","element2","order","compareDocumentPosition","Node","DOCUMENT_POSITION_FOLLOWING","range","createRange","setStart","setEnd","commonAncestorContainer","firstElementChild","element1root","getScroll","side","undefined","upperSide","html","scrollingElement","includeScroll","rect","subtract","scrollTop","scrollLeft","modifier","top","bottom","left","right","getBordersSize","styles","axis","sideA","sideB","getSize","computedStyle","max","getWindowSizes","height","width","classCallCheck","instance","createClass","defineProperties","props","descriptor","enumerable","configurable","writable","defineProperty","key","protoProps","staticProps","assign","source","getClientRect","offsets","result","sizes","clientWidth","clientHeight","horizScrollbar","offsetWidth","vertScrollbar","getOffsetRectRelativeToArbitraryNode","fixedPosition","isHTML","childrenRect","parentRect","scrollParent","borderTopWidth","borderLeftWidth","marginTop","marginLeft","getViewportOffsetRectRelativeToArtbitraryNode","excludeScroll","relativeOffset","innerWidth","innerHeight","offset","isFixed","getFixedPositionOffsetParent","parentElement","el","getBoundaries","popper","padding","boundariesElement","boundaries","boundariesNode","_getWindowSizes","isPaddingNumber","getArea","_ref","computeAutoPlacement","placement","refRect","rects","sortedAreas","keys","map","area","sort","a","b","filteredAreas","_ref2","computedPlacement","variation","getReferenceOffsets","state","commonOffsetParent","getOuterSizes","x","marginBottom","y","marginRight","getOppositePlacement","hash","replace","matched","getPopperOffsets","referenceOffsets","popperRect","popperOffsets","isHoriz","mainSide","secondarySide","measurement","secondaryMeasurement","find","arr","check","Array","runModifiers","modifiers","ends","prop","findIndex","cur","forEach","console","warn","enabled","update","isDestroyed","arrowStyles","attributes","flipped","options","positionFixed","flip","originalPlacement","position","isCreated","onUpdate","onCreate","isModifierEnabled","modifierName","some","name","getSupportedPropertyName","prefixes","upperProp","charAt","toCheck","destroy","removeAttribute","willChange","disableEventListeners","removeOnDestroy","removeChild","getWindow","setupEventListeners","updateBound","addEventListener","passive","scrollElement","attachToScrollParents","callback","scrollParents","isBody","eventsEnabled","enableEventListeners","scheduleUpdate","cancelAnimationFrame","removeEventListener","isNumeric","n","isNaN","isFinite","setStyles","unit","isFirefox","isModifierRequired","requestingName","requestedName","requesting","isRequired","_requesting","requested","placements","validPlacements","clockwise","counter","concat","reverse","BEHAVIORS","parseOffset","basePlacement","useHeight","fragments","frag","divider","search","splitRegex","ops","op","mergeWithPrevious","reduce","str","toValue","index2","Defaults","shift","shiftvariation","_data$offsets","isVertical","shiftOffsets","preventOverflow","transformProp","popperStyles","transform","priority","primary","escapeWithReference","secondary","min","keepTogether","floor","opSide","arrow","_data$offsets$arrow","arrowElement","sideCapitalized","altSide","arrowElementSize","center","popperMarginSide","popperBorderSide","sideValue","round","placementOpposite","flipOrder","behavior","step","refOffsets","overlapsRef","overflowsLeft","overflowsRight","overflowsTop","overflowsBottom","overflowsBoundaries","flippedVariationByRef","flipVariations","flippedVariationByContent","flipVariationsByContent","flippedVariation","getOppositeVariation","inner","subtractLength","bound","computeStyle","legacyGpuAccelerationOption","gpuAcceleration","offsetParentRect","shouldRound","noRound","v","referenceWidth","popperWidth","isVariation","horizontalToInteger","verticalToInteger","getRoundedOffsets","devicePixelRatio","prefixedProperty","invertTop","invertLeft","x-placement","applyStyle","onLoad","modifierOptions","Popper","requestAnimationFrame","Utils","global","PopperUtils","REGEXP_KEYDOWN","ARROW_UP_KEYCODE","boundary","display","popperConfig","Dropdown","_popper","_menu","_getMenuElement","_inNavbar","_detectNavbar","disabled","isActive","_clearMenus","usePopper","showEvent","_getParentFromElement","referenceElement","_getPopperConfig","noop","hideEvent","stopPropagation","constructor","_getPlacement","$parentDropdown","_getOffset","toggles","context","clickEvent","dropdownMenu","_dataApiKeydownHandler","items","item","EVENT_CLICK_DATA_API","backdrop","Modal","_dialog","_backdrop","_isShown","_isBodyOverflowing","_ignoreBackdropClick","_scrollbarWidth","_checkScrollbar","_setScrollbar","_adjustDialog","_setEscapeEvent","_setResizeEvent","_showBackdrop","_showElement","transition","_hideModal","htmlElement","handleUpdate","_triggerBackdropTransition","hideEventPrevented","isModalOverflowing","scrollHeight","modalTransitionDuration","modalBody","ELEMENT_NODE","appendChild","_enforceFocus","shownEvent","transitionComplete","_this5","has","_this6","_this7","_this8","_resetAdjustments","_resetScrollbar","_removeBackdrop","_this9","animate","createElement","className","appendTo","backdropTransitionDuration","callbackRemove","paddingLeft","paddingRight","_getScrollbarWidth","_this10","fixedContent","stickyContent","actualPadding","calculatedPadding","actualMargin","calculatedMargin","elements","margin","scrollDiv","scrollbarWidth","_this11","uriAttrs","DefaultWhitelist","*","br","col","code","div","em","hr","h1","h2","h3","h4","h5","h6","img","li","ol","p","pre","s","small","span","sub","sup","strong","u","ul","SAFE_URL_PATTERN","DATA_URL_PATTERN","sanitizeHtml","unsafeHtml","whiteList","sanitizeFn","createdDocument","DOMParser","parseFromString","whitelistKeys","_loop","elName","attributeList","whitelistedAttributes","allowedAttributeList","attrName","nodeValue","regExp","attrRegex","allowedAttribute","innerHTML","BSCLS_PREFIX_REGEX","DISALLOWED_ATTRIBUTES","animation","template","title","delay","container","fallbackPlacement","customClass","sanitize","AttachmentMap","AUTO","TOP","RIGHT","BOTTOM","LEFT","HIDE","HIDDEN","SHOW","SHOWN","INSERTED","CLICK","FOCUSIN","FOCUSOUT","MOUSEENTER","MOUSELEAVE","Tooltip","_isEnabled","_timeout","_hoverState","_activeTrigger","tip","_setListeners","enable","disable","toggleEnabled","dataKey","DATA_KEY","_getDelegateConfig","click","_isWithActiveTrigger","_enter","_leave","getTipElement","_hideModalHandler","isWithContent","shadowRoot","isInTheDom","tipId","setContent","attachment","_getAttachment","addAttachmentClass","_getContainer","complete","_fixTransition","prevHoverState","_cleanTipClass","getTitle","CLASS_PREFIX","setElementContent","CLASS_NAME_FADE","content","text","empty","append","_handlePopperPlacementChange","eventIn","eventOut","_fixTitle","titleType","dataAttributes","dataAttr","$tip","tabClass","join","popperData","initConfigAnimation","Popover","_getContent","method","ScrollSpy","_scrollElement","_offsets","_targets","_activeTarget","_scrollHeight","_process","refresh","autoMethod","offsetMethod","offsetBase","_getScrollTop","_getScrollHeight","targetSelector","targetBCR","pageYOffset","_getOffsetHeight","maxScroll","_activate","_clear","queries","$link","parents","SELECTOR_NAV_LINKS","scrollSpys","$spy","Tab","previous","listElement","itemSelector","makeArray","hiddenEvent","active","_transitionComplete","dropdownChild","dropdownElement","dropdownToggleList","$this","autohide","Toast","_clearTimeout","_close"],"mappings":";;;;;wxBA0CA,SAASA,EAAsBC,GAAU,IAAAC,EAAAC,KACnCC,GAAS,EAYb,OAVAC,EAAAA,QAAEF,MAAMG,IAAIC,EAAKC,gBAAgB,WAC/BJ,GAAS,KAGXK,YAAW,WACJL,GACHG,EAAKG,qBAAqBR,KAE3BD,GAEIE,SAcHI,EAAO,CACXC,eAAgB,kBAEhBG,OAHW,SAGJC,GACL,GACEA,MA1DU,IA0DGC,KAAKC,gBACXC,SAASC,eAAeJ,IAEjC,OAAOA,GAGTK,uBAXW,SAWYC,GACrB,IAAIC,EAAWD,EAAQE,aAAa,eAEpC,IAAKD,GAAyB,MAAbA,EAAkB,CACjC,IAAME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QAKX7qB,iBAAP,SAAwB9D,GACtB,OAAOxC,KAAKuG,MAAK,WACf,IAAMC,EAAWtG,EAAAA,QAAEF,MACfyG,EAAOD,EAASC,KAnLT,YA2LX,GALKA,IACHA,EAAO,IAAIswB,EAAM/2B,KAHe,iBAAXwC,GAAuBA,GAI5CgE,EAASC,KAxLA,WAwLeA,IAGJ,iBAAXjE,EAAqB,CAC9B,GAA4B,oBAAjBiE,EAAKjE,GACd,MAAM,IAAIyB,UAAJ,oBAAkCzB,EAAlC,KAGRiE,EAAKjE,GAAQxC,mDAlJjB,MA/CY,4CAmDZ,OAAOoJ,mCAIP,OAAOP,SAnBLkuB,GAyKN72B,EAAAA,QAAEiE,GAAF,MAAa4yB,GAAMzwB,iBACnBpG,EAAAA,QAAEiE,GAAF,MAAW2C,YAAciwB,GACzB72B,EAAAA,QAAEiE,GAAF,MAAW4C,WAAa,WAEtB,OADA7G,EAAAA,QAAEiE,GAAF,MAAae,GACN6xB,GAAMzwB","sourcesContent":["/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): util.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\n\n/**\n * ------------------------------------------------------------------------\n * Private TransitionEnd Helpers\n * ------------------------------------------------------------------------\n */\n\nconst TRANSITION_END = 'transitionend'\nconst MAX_UID = 1000000\nconst MILLISECONDS_MULTIPLIER = 1000\n\n// Shoutout AngusCroll (https://goo.gl/pxwQGp)\nfunction toType(obj) {\n if (obj === null || typeof obj === 'undefined') {\n return `${obj}`\n }\n\n return {}.toString.call(obj).match(/\\s([a-z]+)/i)[1].toLowerCase()\n}\n\nfunction getSpecialTransitionEndEvent() {\n return {\n bindType: TRANSITION_END,\n delegateType: TRANSITION_END,\n handle(event) {\n if ($(event.target).is(this)) {\n return event.handleObj.handler.apply(this, arguments) // eslint-disable-line prefer-rest-params\n }\n\n return undefined\n }\n }\n}\n\nfunction transitionEndEmulator(duration) {\n let called = false\n\n $(this).one(Util.TRANSITION_END, () => {\n called = true\n })\n\n setTimeout(() => {\n if (!called) {\n Util.triggerTransitionEnd(this)\n }\n }, duration)\n\n return this\n}\n\nfunction setTransitionEndSupport() {\n $.fn.emulateTransitionEnd = transitionEndEmulator\n $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent()\n}\n\n/**\n * --------------------------------------------------------------------------\n * Public Util Api\n * --------------------------------------------------------------------------\n */\n\nconst Util = {\n TRANSITION_END: 'bsTransitionEnd',\n\n getUID(prefix) {\n do {\n prefix += ~~(Math.random() * MAX_UID) // \"~~\" acts like a faster Math.floor() here\n } while (document.getElementById(prefix))\n\n return prefix\n },\n\n getSelectorFromElement(element) {\n let selector = element.getAttribute('data-target')\n\n if (!selector || selector === '#') {\n const hrefAttr = element.getAttribute('href')\n selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : ''\n }\n\n try {\n return document.querySelector(selector) ? selector : null\n } catch (_) {\n return null\n }\n },\n\n getTransitionDurationFromElement(element) {\n if (!element) {\n return 0\n }\n\n // Get transition-duration of the element\n let transitionDuration = $(element).css('transition-duration')\n let transitionDelay = $(element).css('transition-delay')\n\n const floatTransitionDuration = parseFloat(transitionDuration)\n const floatTransitionDelay = parseFloat(transitionDelay)\n\n // Return 0 if element or transition duration is not found\n if (!floatTransitionDuration && !floatTransitionDelay) {\n return 0\n }\n\n // If multiple durations are defined, take the first\n transitionDuration = transitionDuration.split(',')[0]\n transitionDelay = transitionDelay.split(',')[0]\n\n return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER\n },\n\n reflow(element) {\n return element.offsetHeight\n },\n\n triggerTransitionEnd(element) {\n $(element).trigger(TRANSITION_END)\n },\n\n supportsTransitionEnd() {\n return Boolean(TRANSITION_END)\n },\n\n isElement(obj) {\n return (obj[0] || obj).nodeType\n },\n\n typeCheckConfig(componentName, config, configTypes) {\n for (const property in configTypes) {\n if (Object.prototype.hasOwnProperty.call(configTypes, property)) {\n const expectedTypes = configTypes[property]\n const value = config[property]\n const valueType = value && Util.isElement(value) ?\n 'element' : toType(value)\n\n if (!new RegExp(expectedTypes).test(valueType)) {\n throw new Error(\n `${componentName.toUpperCase()}: ` +\n `Option \"${property}\" provided type \"${valueType}\" ` +\n `but expected type \"${expectedTypes}\".`)\n }\n }\n }\n },\n\n findShadowRoot(element) {\n if (!document.documentElement.attachShadow) {\n return null\n }\n\n // Can find the shadow root otherwise it'll return the document\n if (typeof element.getRootNode === 'function') {\n const root = element.getRootNode()\n return root instanceof ShadowRoot ? root : null\n }\n\n if (element instanceof ShadowRoot) {\n return element\n }\n\n // when we don't find a shadow root\n if (!element.parentNode) {\n return null\n }\n\n return Util.findShadowRoot(element.parentNode)\n },\n\n jQueryDetection() {\n if (typeof $ === 'undefined') {\n throw new TypeError('Bootstrap\\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\\'s JavaScript.')\n }\n\n const version = $.fn.jquery.split(' ')[0].split('.')\n const minMajor = 1\n const ltMajor = 2\n const minMinor = 9\n const minPatch = 1\n const maxMajor = 4\n\n if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {\n throw new Error('Bootstrap\\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')\n }\n }\n}\n\nUtil.jQueryDetection()\nsetTransitionEndSupport()\n\nexport default Util\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): alert.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'alert'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.alert'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\n\nconst SELECTOR_DISMISS = '[data-dismiss=\"alert\"]'\n\nconst EVENT_CLOSE = `close${EVENT_KEY}`\nconst EVENT_CLOSED = `closed${EVENT_KEY}`\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_ALERT = 'alert'\nconst CLASS_NAME_FADE = 'fade'\nconst CLASS_NAME_SHOW = 'show'\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Alert {\n constructor(element) {\n this._element = element\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n // Public\n\n close(element) {\n let rootElement = this._element\n if (element) {\n rootElement = this._getRootElement(element)\n }\n\n const customEvent = this._triggerCloseEvent(rootElement)\n\n if (customEvent.isDefaultPrevented()) {\n return\n }\n\n this._removeElement(rootElement)\n }\n\n dispose() {\n $.removeData(this._element, DATA_KEY)\n this._element = null\n }\n\n // Private\n\n _getRootElement(element) {\n const selector = Util.getSelectorFromElement(element)\n let parent = false\n\n if (selector) {\n parent = document.querySelector(selector)\n }\n\n if (!parent) {\n parent = $(element).closest(`.${CLASS_NAME_ALERT}`)[0]\n }\n\n return parent\n }\n\n _triggerCloseEvent(element) {\n const closeEvent = $.Event(EVENT_CLOSE)\n\n $(element).trigger(closeEvent)\n return closeEvent\n }\n\n _removeElement(element) {\n $(element).removeClass(CLASS_NAME_SHOW)\n\n if (!$(element).hasClass(CLASS_NAME_FADE)) {\n this._destroyElement(element)\n return\n }\n\n const transitionDuration = Util.getTransitionDurationFromElement(element)\n\n $(element)\n .one(Util.TRANSITION_END, event => this._destroyElement(element, event))\n .emulateTransitionEnd(transitionDuration)\n }\n\n _destroyElement(element) {\n $(element)\n .detach()\n .trigger(EVENT_CLOSED)\n .remove()\n }\n\n // Static\n\n static _jQueryInterface(config) {\n return this.each(function () {\n const $element = $(this)\n let data = $element.data(DATA_KEY)\n\n if (!data) {\n data = new Alert(this)\n $element.data(DATA_KEY, data)\n }\n\n if (config === 'close') {\n data[config](this)\n }\n })\n }\n\n static _handleDismiss(alertInstance) {\n return function (event) {\n if (event) {\n event.preventDefault()\n }\n\n alertInstance.close(this)\n }\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document).on(\n EVENT_CLICK_DATA_API,\n SELECTOR_DISMISS,\n Alert._handleDismiss(new Alert())\n)\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Alert._jQueryInterface\n$.fn[NAME].Constructor = Alert\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Alert._jQueryInterface\n}\n\nexport default Alert\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): button.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'button'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.button'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\n\nconst CLASS_NAME_ACTIVE = 'active'\nconst CLASS_NAME_BUTTON = 'btn'\nconst CLASS_NAME_FOCUS = 'focus'\n\nconst SELECTOR_DATA_TOGGLE_CARROT = '[data-toggle^=\"button\"]'\nconst SELECTOR_DATA_TOGGLES = '[data-toggle=\"buttons\"]'\nconst SELECTOR_DATA_TOGGLE = '[data-toggle=\"button\"]'\nconst SELECTOR_DATA_TOGGLES_BUTTONS = '[data-toggle=\"buttons\"] .btn'\nconst SELECTOR_INPUT = 'input:not([type=\"hidden\"])'\nconst SELECTOR_ACTIVE = '.active'\nconst SELECTOR_BUTTON = '.btn'\n\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\nconst EVENT_FOCUS_BLUR_DATA_API = `focus${EVENT_KEY}${DATA_API_KEY} ` +\n `blur${EVENT_KEY}${DATA_API_KEY}`\nconst EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Button {\n constructor(element) {\n this._element = element\n this.shouldAvoidTriggerChange = false\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n // Public\n\n toggle() {\n let triggerChangeEvent = true\n let addAriaPressed = true\n const rootElement = $(this._element).closest(SELECTOR_DATA_TOGGLES)[0]\n\n if (rootElement) {\n const input = this._element.querySelector(SELECTOR_INPUT)\n\n if (input) {\n if (input.type === 'radio') {\n if (input.checked && this._element.classList.contains(CLASS_NAME_ACTIVE)) {\n triggerChangeEvent = false\n } else {\n const activeElement = rootElement.querySelector(SELECTOR_ACTIVE)\n\n if (activeElement) {\n $(activeElement).removeClass(CLASS_NAME_ACTIVE)\n }\n }\n }\n\n if (triggerChangeEvent) {\n // if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input\n if (input.type === 'checkbox' || input.type === 'radio') {\n input.checked = !this._element.classList.contains(CLASS_NAME_ACTIVE)\n }\n\n if (!this.shouldAvoidTriggerChange) {\n $(input).trigger('change')\n }\n }\n\n input.focus()\n addAriaPressed = false\n }\n }\n\n if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) {\n if (addAriaPressed) {\n this._element.setAttribute('aria-pressed', !this._element.classList.contains(CLASS_NAME_ACTIVE))\n }\n\n if (triggerChangeEvent) {\n $(this._element).toggleClass(CLASS_NAME_ACTIVE)\n }\n }\n }\n\n dispose() {\n $.removeData(this._element, DATA_KEY)\n this._element = null\n }\n\n // Static\n\n static _jQueryInterface(config, avoidTriggerChange) {\n return this.each(function () {\n const $element = $(this)\n let data = $element.data(DATA_KEY)\n\n if (!data) {\n data = new Button(this)\n $element.data(DATA_KEY, data)\n }\n\n data.shouldAvoidTriggerChange = avoidTriggerChange\n\n if (config === 'toggle') {\n data[config]()\n }\n })\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document)\n .on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, event => {\n let button = event.target\n const initialButton = button\n\n if (!$(button).hasClass(CLASS_NAME_BUTTON)) {\n button = $(button).closest(SELECTOR_BUTTON)[0]\n }\n\n if (!button || button.hasAttribute('disabled') || button.classList.contains('disabled')) {\n event.preventDefault() // work around Firefox bug #1540995\n } else {\n const inputBtn = button.querySelector(SELECTOR_INPUT)\n\n if (inputBtn && (inputBtn.hasAttribute('disabled') || inputBtn.classList.contains('disabled'))) {\n event.preventDefault() // work around Firefox bug #1540995\n return\n }\n\n if (initialButton.tagName === 'INPUT' || button.tagName !== 'LABEL') {\n Button._jQueryInterface.call($(button), 'toggle', initialButton.tagName === 'INPUT')\n }\n }\n })\n .on(EVENT_FOCUS_BLUR_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, event => {\n const button = $(event.target).closest(SELECTOR_BUTTON)[0]\n $(button).toggleClass(CLASS_NAME_FOCUS, /^focus(in)?$/.test(event.type))\n })\n\n$(window).on(EVENT_LOAD_DATA_API, () => {\n // ensure correct active class is set to match the controls' actual values/states\n\n // find all checkboxes/readio buttons inside data-toggle groups\n let buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLES_BUTTONS))\n for (let i = 0, len = buttons.length; i < len; i++) {\n const button = buttons[i]\n const input = button.querySelector(SELECTOR_INPUT)\n if (input.checked || input.hasAttribute('checked')) {\n button.classList.add(CLASS_NAME_ACTIVE)\n } else {\n button.classList.remove(CLASS_NAME_ACTIVE)\n }\n }\n\n // find all button toggles\n buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE))\n for (let i = 0, len = buttons.length; i < len; i++) {\n const button = buttons[i]\n if (button.getAttribute('aria-pressed') === 'true') {\n button.classList.add(CLASS_NAME_ACTIVE)\n } else {\n button.classList.remove(CLASS_NAME_ACTIVE)\n }\n }\n})\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Button._jQueryInterface\n$.fn[NAME].Constructor = Button\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Button._jQueryInterface\n}\n\nexport default Button\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): carousel.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'carousel'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.carousel'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\nconst ARROW_LEFT_KEYCODE = 37 // KeyboardEvent.which value for left arrow key\nconst ARROW_RIGHT_KEYCODE = 39 // KeyboardEvent.which value for right arrow key\nconst TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch\nconst SWIPE_THRESHOLD = 40\n\nconst Default = {\n interval: 5000,\n keyboard: true,\n slide: false,\n pause: 'hover',\n wrap: true,\n touch: true\n}\n\nconst DefaultType = {\n interval: '(number|boolean)',\n keyboard: 'boolean',\n slide: '(boolean|string)',\n pause: '(string|boolean)',\n wrap: 'boolean',\n touch: 'boolean'\n}\n\nconst DIRECTION_NEXT = 'next'\nconst DIRECTION_PREV = 'prev'\nconst DIRECTION_LEFT = 'left'\nconst DIRECTION_RIGHT = 'right'\n\nconst EVENT_SLIDE = `slide${EVENT_KEY}`\nconst EVENT_SLID = `slid${EVENT_KEY}`\nconst EVENT_KEYDOWN = `keydown${EVENT_KEY}`\nconst EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`\nconst EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`\nconst EVENT_TOUCHSTART = `touchstart${EVENT_KEY}`\nconst EVENT_TOUCHMOVE = `touchmove${EVENT_KEY}`\nconst EVENT_TOUCHEND = `touchend${EVENT_KEY}`\nconst EVENT_POINTERDOWN = `pointerdown${EVENT_KEY}`\nconst EVENT_POINTERUP = `pointerup${EVENT_KEY}`\nconst EVENT_DRAG_START = `dragstart${EVENT_KEY}`\nconst EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_CAROUSEL = 'carousel'\nconst CLASS_NAME_ACTIVE = 'active'\nconst CLASS_NAME_SLIDE = 'slide'\nconst CLASS_NAME_RIGHT = 'carousel-item-right'\nconst CLASS_NAME_LEFT = 'carousel-item-left'\nconst CLASS_NAME_NEXT = 'carousel-item-next'\nconst CLASS_NAME_PREV = 'carousel-item-prev'\nconst CLASS_NAME_POINTER_EVENT = 'pointer-event'\n\nconst SELECTOR_ACTIVE = '.active'\nconst SELECTOR_ACTIVE_ITEM = '.active.carousel-item'\nconst SELECTOR_ITEM = '.carousel-item'\nconst SELECTOR_ITEM_IMG = '.carousel-item img'\nconst SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'\nconst SELECTOR_INDICATORS = '.carousel-indicators'\nconst SELECTOR_DATA_SLIDE = '[data-slide], [data-slide-to]'\nconst SELECTOR_DATA_RIDE = '[data-ride=\"carousel\"]'\n\nconst PointerType = {\n TOUCH: 'touch',\n PEN: 'pen'\n}\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\nclass Carousel {\n constructor(element, config) {\n this._items = null\n this._interval = null\n this._activeElement = null\n this._isPaused = false\n this._isSliding = false\n this.touchTimeout = null\n this.touchStartX = 0\n this.touchDeltaX = 0\n\n this._config = this._getConfig(config)\n this._element = element\n this._indicatorsElement = this._element.querySelector(SELECTOR_INDICATORS)\n this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0\n this._pointerEvent = Boolean(window.PointerEvent || window.MSPointerEvent)\n\n this._addEventListeners()\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n // Public\n\n next() {\n if (!this._isSliding) {\n this._slide(DIRECTION_NEXT)\n }\n }\n\n nextWhenVisible() {\n const $element = $(this._element)\n // Don't call next when the page isn't visible\n // or the carousel or its parent isn't visible\n if (!document.hidden &&\n ($element.is(':visible') && $element.css('visibility') !== 'hidden')) {\n this.next()\n }\n }\n\n prev() {\n if (!this._isSliding) {\n this._slide(DIRECTION_PREV)\n }\n }\n\n pause(event) {\n if (!event) {\n this._isPaused = true\n }\n\n if (this._element.querySelector(SELECTOR_NEXT_PREV)) {\n Util.triggerTransitionEnd(this._element)\n this.cycle(true)\n }\n\n clearInterval(this._interval)\n this._interval = null\n }\n\n cycle(event) {\n if (!event) {\n this._isPaused = false\n }\n\n if (this._interval) {\n clearInterval(this._interval)\n this._interval = null\n }\n\n if (this._config.interval && !this._isPaused) {\n this._updateInterval()\n\n this._interval = setInterval(\n (document.visibilityState ? this.nextWhenVisible : this.next).bind(this),\n this._config.interval\n )\n }\n }\n\n to(index) {\n this._activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM)\n\n const activeIndex = this._getItemIndex(this._activeElement)\n\n if (index > this._items.length - 1 || index < 0) {\n return\n }\n\n if (this._isSliding) {\n $(this._element).one(EVENT_SLID, () => this.to(index))\n return\n }\n\n if (activeIndex === index) {\n this.pause()\n this.cycle()\n return\n }\n\n const direction = index > activeIndex ?\n DIRECTION_NEXT :\n DIRECTION_PREV\n\n this._slide(direction, this._items[index])\n }\n\n dispose() {\n $(this._element).off(EVENT_KEY)\n $.removeData(this._element, DATA_KEY)\n\n this._items = null\n this._config = null\n this._element = null\n this._interval = null\n this._isPaused = null\n this._isSliding = null\n this._activeElement = null\n this._indicatorsElement = null\n }\n\n // Private\n\n _getConfig(config) {\n config = {\n ...Default,\n ...config\n }\n Util.typeCheckConfig(NAME, config, DefaultType)\n return config\n }\n\n _handleSwipe() {\n const absDeltax = Math.abs(this.touchDeltaX)\n\n if (absDeltax <= SWIPE_THRESHOLD) {\n return\n }\n\n const direction = absDeltax / this.touchDeltaX\n\n this.touchDeltaX = 0\n\n // swipe left\n if (direction > 0) {\n this.prev()\n }\n\n // swipe right\n if (direction < 0) {\n this.next()\n }\n }\n\n _addEventListeners() {\n if (this._config.keyboard) {\n $(this._element).on(EVENT_KEYDOWN, event => this._keydown(event))\n }\n\n if (this._config.pause === 'hover') {\n $(this._element)\n .on(EVENT_MOUSEENTER, event => this.pause(event))\n .on(EVENT_MOUSELEAVE, event => this.cycle(event))\n }\n\n if (this._config.touch) {\n this._addTouchEventListeners()\n }\n }\n\n _addTouchEventListeners() {\n if (!this._touchSupported) {\n return\n }\n\n const start = event => {\n if (this._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) {\n this.touchStartX = event.originalEvent.clientX\n } else if (!this._pointerEvent) {\n this.touchStartX = event.originalEvent.touches[0].clientX\n }\n }\n\n const move = event => {\n // ensure swiping with one touch and not pinching\n if (event.originalEvent.touches && event.originalEvent.touches.length > 1) {\n this.touchDeltaX = 0\n } else {\n this.touchDeltaX = event.originalEvent.touches[0].clientX - this.touchStartX\n }\n }\n\n const end = event => {\n if (this._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) {\n this.touchDeltaX = event.originalEvent.clientX - this.touchStartX\n }\n\n this._handleSwipe()\n if (this._config.pause === 'hover') {\n // If it's a touch-enabled device, mouseenter/leave are fired as\n // part of the mouse compatibility events on first tap - the carousel\n // would stop cycling until user tapped out of it;\n // here, we listen for touchend, explicitly pause the carousel\n // (as if it's the second time we tap on it, mouseenter compat event\n // is NOT fired) and after a timeout (to allow for mouse compatibility\n // events to fire) we explicitly restart cycling\n\n this.pause()\n if (this.touchTimeout) {\n clearTimeout(this.touchTimeout)\n }\n\n this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval)\n }\n }\n\n $(this._element.querySelectorAll(SELECTOR_ITEM_IMG))\n .on(EVENT_DRAG_START, e => e.preventDefault())\n\n if (this._pointerEvent) {\n $(this._element).on(EVENT_POINTERDOWN, event => start(event))\n $(this._element).on(EVENT_POINTERUP, event => end(event))\n\n this._element.classList.add(CLASS_NAME_POINTER_EVENT)\n } else {\n $(this._element).on(EVENT_TOUCHSTART, event => start(event))\n $(this._element).on(EVENT_TOUCHMOVE, event => move(event))\n $(this._element).on(EVENT_TOUCHEND, event => end(event))\n }\n }\n\n _keydown(event) {\n if (/input|textarea/i.test(event.target.tagName)) {\n return\n }\n\n switch (event.which) {\n case ARROW_LEFT_KEYCODE:\n event.preventDefault()\n this.prev()\n break\n case ARROW_RIGHT_KEYCODE:\n event.preventDefault()\n this.next()\n break\n default:\n }\n }\n\n _getItemIndex(element) {\n this._items = element && element.parentNode ?\n [].slice.call(element.parentNode.querySelectorAll(SELECTOR_ITEM)) :\n []\n return this._items.indexOf(element)\n }\n\n _getItemByDirection(direction, activeElement) {\n const isNextDirection = direction === DIRECTION_NEXT\n const isPrevDirection = direction === DIRECTION_PREV\n const activeIndex = this._getItemIndex(activeElement)\n const lastItemIndex = this._items.length - 1\n const isGoingToWrap = isPrevDirection && activeIndex === 0 ||\n isNextDirection && activeIndex === lastItemIndex\n\n if (isGoingToWrap && !this._config.wrap) {\n return activeElement\n }\n\n const delta = direction === DIRECTION_PREV ? -1 : 1\n const itemIndex = (activeIndex + delta) % this._items.length\n\n return itemIndex === -1 ?\n this._items[this._items.length - 1] : this._items[itemIndex]\n }\n\n _triggerSlideEvent(relatedTarget, eventDirectionName) {\n const targetIndex = this._getItemIndex(relatedTarget)\n const fromIndex = this._getItemIndex(this._element.querySelector(SELECTOR_ACTIVE_ITEM))\n const slideEvent = $.Event(EVENT_SLIDE, {\n relatedTarget,\n direction: eventDirectionName,\n from: fromIndex,\n to: targetIndex\n })\n\n $(this._element).trigger(slideEvent)\n\n return slideEvent\n }\n\n _setActiveIndicatorElement(element) {\n if (this._indicatorsElement) {\n const indicators = [].slice.call(this._indicatorsElement.querySelectorAll(SELECTOR_ACTIVE))\n $(indicators).removeClass(CLASS_NAME_ACTIVE)\n\n const nextIndicator = this._indicatorsElement.children[\n this._getItemIndex(element)\n ]\n\n if (nextIndicator) {\n $(nextIndicator).addClass(CLASS_NAME_ACTIVE)\n }\n }\n }\n\n _updateInterval() {\n const element = this._activeElement || this._element.querySelector(SELECTOR_ACTIVE_ITEM)\n\n if (!element) {\n return\n }\n\n const elementInterval = parseInt(element.getAttribute('data-interval'), 10)\n\n if (elementInterval) {\n this._config.defaultInterval = this._config.defaultInterval || this._config.interval\n this._config.interval = elementInterval\n } else {\n this._config.interval = this._config.defaultInterval || this._config.interval\n }\n }\n\n _slide(direction, element) {\n const activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM)\n const activeElementIndex = this._getItemIndex(activeElement)\n const nextElement = element || activeElement &&\n this._getItemByDirection(direction, activeElement)\n const nextElementIndex = this._getItemIndex(nextElement)\n const isCycling = Boolean(this._interval)\n\n let directionalClassName\n let orderClassName\n let eventDirectionName\n\n if (direction === DIRECTION_NEXT) {\n directionalClassName = CLASS_NAME_LEFT\n orderClassName = CLASS_NAME_NEXT\n eventDirectionName = DIRECTION_LEFT\n } else {\n directionalClassName = CLASS_NAME_RIGHT\n orderClassName = CLASS_NAME_PREV\n eventDirectionName = DIRECTION_RIGHT\n }\n\n if (nextElement && $(nextElement).hasClass(CLASS_NAME_ACTIVE)) {\n this._isSliding = false\n return\n }\n\n const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName)\n if (slideEvent.isDefaultPrevented()) {\n return\n }\n\n if (!activeElement || !nextElement) {\n // Some weirdness is happening, so we bail\n return\n }\n\n this._isSliding = true\n\n if (isCycling) {\n this.pause()\n }\n\n this._setActiveIndicatorElement(nextElement)\n this._activeElement = nextElement\n\n const slidEvent = $.Event(EVENT_SLID, {\n relatedTarget: nextElement,\n direction: eventDirectionName,\n from: activeElementIndex,\n to: nextElementIndex\n })\n\n if ($(this._element).hasClass(CLASS_NAME_SLIDE)) {\n $(nextElement).addClass(orderClassName)\n\n Util.reflow(nextElement)\n\n $(activeElement).addClass(directionalClassName)\n $(nextElement).addClass(directionalClassName)\n\n const transitionDuration = Util.getTransitionDurationFromElement(activeElement)\n\n $(activeElement)\n .one(Util.TRANSITION_END, () => {\n $(nextElement)\n .removeClass(`${directionalClassName} ${orderClassName}`)\n .addClass(CLASS_NAME_ACTIVE)\n\n $(activeElement).removeClass(`${CLASS_NAME_ACTIVE} ${orderClassName} ${directionalClassName}`)\n\n this._isSliding = false\n\n setTimeout(() => $(this._element).trigger(slidEvent), 0)\n })\n .emulateTransitionEnd(transitionDuration)\n } else {\n $(activeElement).removeClass(CLASS_NAME_ACTIVE)\n $(nextElement).addClass(CLASS_NAME_ACTIVE)\n\n this._isSliding = false\n $(this._element).trigger(slidEvent)\n }\n\n if (isCycling) {\n this.cycle()\n }\n }\n\n // Static\n\n static _jQueryInterface(config) {\n return this.each(function () {\n let data = $(this).data(DATA_KEY)\n let _config = {\n ...Default,\n ...$(this).data()\n }\n\n if (typeof config === 'object') {\n _config = {\n ..._config,\n ...config\n }\n }\n\n const action = typeof config === 'string' ? config : _config.slide\n\n if (!data) {\n data = new Carousel(this, _config)\n $(this).data(DATA_KEY, data)\n }\n\n if (typeof config === 'number') {\n data.to(config)\n } else if (typeof action === 'string') {\n if (typeof data[action] === 'undefined') {\n throw new TypeError(`No method named \"${action}\"`)\n }\n\n data[action]()\n } else if (_config.interval && _config.ride) {\n data.pause()\n data.cycle()\n }\n })\n }\n\n static _dataApiClickHandler(event) {\n const selector = Util.getSelectorFromElement(this)\n\n if (!selector) {\n return\n }\n\n const target = $(selector)[0]\n\n if (!target || !$(target).hasClass(CLASS_NAME_CAROUSEL)) {\n return\n }\n\n const config = {\n ...$(target).data(),\n ...$(this).data()\n }\n const slideIndex = this.getAttribute('data-slide-to')\n\n if (slideIndex) {\n config.interval = false\n }\n\n Carousel._jQueryInterface.call($(target), config)\n\n if (slideIndex) {\n $(target).data(DATA_KEY).to(slideIndex)\n }\n\n event.preventDefault()\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, Carousel._dataApiClickHandler)\n\n$(window).on(EVENT_LOAD_DATA_API, () => {\n const carousels = [].slice.call(document.querySelectorAll(SELECTOR_DATA_RIDE))\n for (let i = 0, len = carousels.length; i < len; i++) {\n const $carousel = $(carousels[i])\n Carousel._jQueryInterface.call($carousel, $carousel.data())\n }\n})\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Carousel._jQueryInterface\n$.fn[NAME].Constructor = Carousel\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Carousel._jQueryInterface\n}\n\nexport default Carousel\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): collapse.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'collapse'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.collapse'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\n\nconst Default = {\n toggle: true,\n parent: ''\n}\n\nconst DefaultType = {\n toggle: 'boolean',\n parent: '(string|element)'\n}\n\nconst EVENT_SHOW = `show${EVENT_KEY}`\nconst EVENT_SHOWN = `shown${EVENT_KEY}`\nconst EVENT_HIDE = `hide${EVENT_KEY}`\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_SHOW = 'show'\nconst CLASS_NAME_COLLAPSE = 'collapse'\nconst CLASS_NAME_COLLAPSING = 'collapsing'\nconst CLASS_NAME_COLLAPSED = 'collapsed'\n\nconst DIMENSION_WIDTH = 'width'\nconst DIMENSION_HEIGHT = 'height'\n\nconst SELECTOR_ACTIVES = '.show, .collapsing'\nconst SELECTOR_DATA_TOGGLE = '[data-toggle=\"collapse\"]'\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Collapse {\n constructor(element, config) {\n this._isTransitioning = false\n this._element = element\n this._config = this._getConfig(config)\n this._triggerArray = [].slice.call(document.querySelectorAll(\n `[data-toggle=\"collapse\"][href=\"#${element.id}\"],` +\n `[data-toggle=\"collapse\"][data-target=\"#${element.id}\"]`\n ))\n\n const toggleList = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE))\n for (let i = 0, len = toggleList.length; i < len; i++) {\n const elem = toggleList[i]\n const selector = Util.getSelectorFromElement(elem)\n const filterElement = [].slice.call(document.querySelectorAll(selector))\n .filter(foundElem => foundElem === element)\n\n if (selector !== null && filterElement.length > 0) {\n this._selector = selector\n this._triggerArray.push(elem)\n }\n }\n\n this._parent = this._config.parent ? this._getParent() : null\n\n if (!this._config.parent) {\n this._addAriaAndCollapsedClass(this._element, this._triggerArray)\n }\n\n if (this._config.toggle) {\n this.toggle()\n }\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n // Public\n\n toggle() {\n if ($(this._element).hasClass(CLASS_NAME_SHOW)) {\n this.hide()\n } else {\n this.show()\n }\n }\n\n show() {\n if (this._isTransitioning ||\n $(this._element).hasClass(CLASS_NAME_SHOW)) {\n return\n }\n\n let actives\n let activesData\n\n if (this._parent) {\n actives = [].slice.call(this._parent.querySelectorAll(SELECTOR_ACTIVES))\n .filter(elem => {\n if (typeof this._config.parent === 'string') {\n return elem.getAttribute('data-parent') === this._config.parent\n }\n\n return elem.classList.contains(CLASS_NAME_COLLAPSE)\n })\n\n if (actives.length === 0) {\n actives = null\n }\n }\n\n if (actives) {\n activesData = $(actives).not(this._selector).data(DATA_KEY)\n if (activesData && activesData._isTransitioning) {\n return\n }\n }\n\n const startEvent = $.Event(EVENT_SHOW)\n $(this._element).trigger(startEvent)\n if (startEvent.isDefaultPrevented()) {\n return\n }\n\n if (actives) {\n Collapse._jQueryInterface.call($(actives).not(this._selector), 'hide')\n if (!activesData) {\n $(actives).data(DATA_KEY, null)\n }\n }\n\n const dimension = this._getDimension()\n\n $(this._element)\n .removeClass(CLASS_NAME_COLLAPSE)\n .addClass(CLASS_NAME_COLLAPSING)\n\n this._element.style[dimension] = 0\n\n if (this._triggerArray.length) {\n $(this._triggerArray)\n .removeClass(CLASS_NAME_COLLAPSED)\n .attr('aria-expanded', true)\n }\n\n this.setTransitioning(true)\n\n const complete = () => {\n $(this._element)\n .removeClass(CLASS_NAME_COLLAPSING)\n .addClass(`${CLASS_NAME_COLLAPSE} ${CLASS_NAME_SHOW}`)\n\n this._element.style[dimension] = ''\n\n this.setTransitioning(false)\n\n $(this._element).trigger(EVENT_SHOWN)\n }\n\n const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1)\n const scrollSize = `scroll${capitalizedDimension}`\n const transitionDuration = Util.getTransitionDurationFromElement(this._element)\n\n $(this._element)\n .one(Util.TRANSITION_END, complete)\n .emulateTransitionEnd(transitionDuration)\n\n this._element.style[dimension] = `${this._element[scrollSize]}px`\n }\n\n hide() {\n if (this._isTransitioning ||\n !$(this._element).hasClass(CLASS_NAME_SHOW)) {\n return\n }\n\n const startEvent = $.Event(EVENT_HIDE)\n $(this._element).trigger(startEvent)\n if (startEvent.isDefaultPrevented()) {\n return\n }\n\n const dimension = this._getDimension()\n\n this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`\n\n Util.reflow(this._element)\n\n $(this._element)\n .addClass(CLASS_NAME_COLLAPSING)\n .removeClass(`${CLASS_NAME_COLLAPSE} ${CLASS_NAME_SHOW}`)\n\n const triggerArrayLength = this._triggerArray.length\n if (triggerArrayLength > 0) {\n for (let i = 0; i < triggerArrayLength; i++) {\n const trigger = this._triggerArray[i]\n const selector = Util.getSelectorFromElement(trigger)\n\n if (selector !== null) {\n const $elem = $([].slice.call(document.querySelectorAll(selector)))\n if (!$elem.hasClass(CLASS_NAME_SHOW)) {\n $(trigger).addClass(CLASS_NAME_COLLAPSED)\n .attr('aria-expanded', false)\n }\n }\n }\n }\n\n this.setTransitioning(true)\n\n const complete = () => {\n this.setTransitioning(false)\n $(this._element)\n .removeClass(CLASS_NAME_COLLAPSING)\n .addClass(CLASS_NAME_COLLAPSE)\n .trigger(EVENT_HIDDEN)\n }\n\n this._element.style[dimension] = ''\n const transitionDuration = Util.getTransitionDurationFromElement(this._element)\n\n $(this._element)\n .one(Util.TRANSITION_END, complete)\n .emulateTransitionEnd(transitionDuration)\n }\n\n setTransitioning(isTransitioning) {\n this._isTransitioning = isTransitioning\n }\n\n dispose() {\n $.removeData(this._element, DATA_KEY)\n\n this._config = null\n this._parent = null\n this._element = null\n this._triggerArray = null\n this._isTransitioning = null\n }\n\n // Private\n\n _getConfig(config) {\n config = {\n ...Default,\n ...config\n }\n config.toggle = Boolean(config.toggle) // Coerce string values\n Util.typeCheckConfig(NAME, config, DefaultType)\n return config\n }\n\n _getDimension() {\n const hasWidth = $(this._element).hasClass(DIMENSION_WIDTH)\n return hasWidth ? DIMENSION_WIDTH : DIMENSION_HEIGHT\n }\n\n _getParent() {\n let parent\n\n if (Util.isElement(this._config.parent)) {\n parent = this._config.parent\n\n // It's a jQuery object\n if (typeof this._config.parent.jquery !== 'undefined') {\n parent = this._config.parent[0]\n }\n } else {\n parent = document.querySelector(this._config.parent)\n }\n\n const selector = `[data-toggle=\"collapse\"][data-parent=\"${this._config.parent}\"]`\n const children = [].slice.call(parent.querySelectorAll(selector))\n\n $(children).each((i, element) => {\n this._addAriaAndCollapsedClass(\n Collapse._getTargetFromElement(element),\n [element]\n )\n })\n\n return parent\n }\n\n _addAriaAndCollapsedClass(element, triggerArray) {\n const isOpen = $(element).hasClass(CLASS_NAME_SHOW)\n\n if (triggerArray.length) {\n $(triggerArray)\n .toggleClass(CLASS_NAME_COLLAPSED, !isOpen)\n .attr('aria-expanded', isOpen)\n }\n }\n\n // Static\n\n static _getTargetFromElement(element) {\n const selector = Util.getSelectorFromElement(element)\n return selector ? document.querySelector(selector) : null\n }\n\n static _jQueryInterface(config) {\n return this.each(function () {\n const $element = $(this)\n let data = $element.data(DATA_KEY)\n const _config = {\n ...Default,\n ...$element.data(),\n ...(typeof config === 'object' && config ? config : {})\n }\n\n if (!data && _config.toggle && typeof config === 'string' && /show|hide/.test(config)) {\n _config.toggle = false\n }\n\n if (!data) {\n data = new Collapse(this, _config)\n $element.data(DATA_KEY, data)\n }\n\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`)\n }\n\n data[config]()\n }\n })\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {\n // preventDefault only for elements (which change the URL) not inside the collapsible element\n if (event.currentTarget.tagName === 'A') {\n event.preventDefault()\n }\n\n const $trigger = $(this)\n const selector = Util.getSelectorFromElement(this)\n const selectors = [].slice.call(document.querySelectorAll(selector))\n\n $(selectors).each(function () {\n const $target = $(this)\n const data = $target.data(DATA_KEY)\n const config = data ? 'toggle' : $trigger.data()\n Collapse._jQueryInterface.call($target, config)\n })\n})\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Collapse._jQueryInterface\n$.fn[NAME].Constructor = Collapse\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Collapse._jQueryInterface\n}\n\nexport default Collapse\n","/**!\n * @fileOverview Kickass library to create and place poppers near their reference elements.\n * @version 1.16.1\n * @license\n * Copyright (c) 2016 Federico Zivolo and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nvar isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';\n\nvar timeoutDuration = function () {\n var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];\n for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {\n if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {\n return 1;\n }\n }\n return 0;\n}();\n\nfunction microtaskDebounce(fn) {\n var called = false;\n return function () {\n if (called) {\n return;\n }\n called = true;\n window.Promise.resolve().then(function () {\n called = false;\n fn();\n });\n };\n}\n\nfunction taskDebounce(fn) {\n var scheduled = false;\n return function () {\n if (!scheduled) {\n scheduled = true;\n setTimeout(function () {\n scheduled = false;\n fn();\n }, timeoutDuration);\n }\n };\n}\n\nvar supportsMicroTasks = isBrowser && window.Promise;\n\n/**\n* Create a debounced version of a method, that's asynchronously deferred\n* but called in the minimum time possible.\n*\n* @method\n* @memberof Popper.Utils\n* @argument {Function} fn\n* @returns {Function}\n*/\nvar debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;\n\n/**\n * Check if the given variable is a function\n * @method\n * @memberof Popper.Utils\n * @argument {Any} functionToCheck - variable to check\n * @returns {Boolean} answer to: is a function?\n */\nfunction isFunction(functionToCheck) {\n var getType = {};\n return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';\n}\n\n/**\n * Get CSS computed property of the given element\n * @method\n * @memberof Popper.Utils\n * @argument {Eement} element\n * @argument {String} property\n */\nfunction getStyleComputedProperty(element, property) {\n if (element.nodeType !== 1) {\n return [];\n }\n // NOTE: 1 DOM access here\n var window = element.ownerDocument.defaultView;\n var css = window.getComputedStyle(element, null);\n return property ? css[property] : css;\n}\n\n/**\n * Returns the parentNode or the host of the element\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @returns {Element} parent\n */\nfunction getParentNode(element) {\n if (element.nodeName === 'HTML') {\n return element;\n }\n return element.parentNode || element.host;\n}\n\n/**\n * Returns the scrolling parent of the given element\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @returns {Element} scroll parent\n */\nfunction getScrollParent(element) {\n // Return body, `getScroll` will take care to get the correct `scrollTop` from it\n if (!element) {\n return document.body;\n }\n\n switch (element.nodeName) {\n case 'HTML':\n case 'BODY':\n return element.ownerDocument.body;\n case '#document':\n return element.body;\n }\n\n // Firefox want us to check `-x` and `-y` variations as well\n\n var _getStyleComputedProp = getStyleComputedProperty(element),\n overflow = _getStyleComputedProp.overflow,\n overflowX = _getStyleComputedProp.overflowX,\n overflowY = _getStyleComputedProp.overflowY;\n\n if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {\n return element;\n }\n\n return getScrollParent(getParentNode(element));\n}\n\n/**\n * Returns the reference node of the reference object, or the reference object itself.\n * @method\n * @memberof Popper.Utils\n * @param {Element|Object} reference - the reference element (the popper will be relative to this)\n * @returns {Element} parent\n */\nfunction getReferenceNode(reference) {\n return reference && reference.referenceNode ? reference.referenceNode : reference;\n}\n\nvar isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);\nvar isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);\n\n/**\n * Determines if the browser is Internet Explorer\n * @method\n * @memberof Popper.Utils\n * @param {Number} version to check\n * @returns {Boolean} isIE\n */\nfunction isIE(version) {\n if (version === 11) {\n return isIE11;\n }\n if (version === 10) {\n return isIE10;\n }\n return isIE11 || isIE10;\n}\n\n/**\n * Returns the offset parent of the given element\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @returns {Element} offset parent\n */\nfunction getOffsetParent(element) {\n if (!element) {\n return document.documentElement;\n }\n\n var noOffsetParent = isIE(10) ? document.body : null;\n\n // NOTE: 1 DOM access here\n var offsetParent = element.offsetParent || null;\n // Skip hidden elements which don't have an offsetParent\n while (offsetParent === noOffsetParent && element.nextElementSibling) {\n offsetParent = (element = element.nextElementSibling).offsetParent;\n }\n\n var nodeName = offsetParent && offsetParent.nodeName;\n\n if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {\n return element ? element.ownerDocument.documentElement : document.documentElement;\n }\n\n // .offsetParent will return the closest TH, TD or TABLE in case\n // no offsetParent is present, I hate this job...\n if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {\n return getOffsetParent(offsetParent);\n }\n\n return offsetParent;\n}\n\nfunction isOffsetContainer(element) {\n var nodeName = element.nodeName;\n\n if (nodeName === 'BODY') {\n return false;\n }\n return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;\n}\n\n/**\n * Finds the root node (document, shadowDOM root) of the given element\n * @method\n * @memberof Popper.Utils\n * @argument {Element} node\n * @returns {Element} root node\n */\nfunction getRoot(node) {\n if (node.parentNode !== null) {\n return getRoot(node.parentNode);\n }\n\n return node;\n}\n\n/**\n * Finds the offset parent common to the two provided nodes\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element1\n * @argument {Element} element2\n * @returns {Element} common offset parent\n */\nfunction findCommonOffsetParent(element1, element2) {\n // This check is needed to avoid errors in case one of the elements isn't defined for any reason\n if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {\n return document.documentElement;\n }\n\n // Here we make sure to give as \"start\" the element that comes first in the DOM\n var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;\n var start = order ? element1 : element2;\n var end = order ? element2 : element1;\n\n // Get common ancestor container\n var range = document.createRange();\n range.setStart(start, 0);\n range.setEnd(end, 0);\n var commonAncestorContainer = range.commonAncestorContainer;\n\n // Both nodes are inside #document\n\n if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {\n if (isOffsetContainer(commonAncestorContainer)) {\n return commonAncestorContainer;\n }\n\n return getOffsetParent(commonAncestorContainer);\n }\n\n // one of the nodes is inside shadowDOM, find which one\n var element1root = getRoot(element1);\n if (element1root.host) {\n return findCommonOffsetParent(element1root.host, element2);\n } else {\n return findCommonOffsetParent(element1, getRoot(element2).host);\n }\n}\n\n/**\n * Gets the scroll value of the given element in the given side (top and left)\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @argument {String} side `top` or `left`\n * @returns {number} amount of scrolled pixels\n */\nfunction getScroll(element) {\n var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';\n\n var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';\n var nodeName = element.nodeName;\n\n if (nodeName === 'BODY' || nodeName === 'HTML') {\n var html = element.ownerDocument.documentElement;\n var scrollingElement = element.ownerDocument.scrollingElement || html;\n return scrollingElement[upperSide];\n }\n\n return element[upperSide];\n}\n\n/*\n * Sum or subtract the element scroll values (left and top) from a given rect object\n * @method\n * @memberof Popper.Utils\n * @param {Object} rect - Rect object you want to change\n * @param {HTMLElement} element - The element from the function reads the scroll values\n * @param {Boolean} subtract - set to true if you want to subtract the scroll values\n * @return {Object} rect - The modifier rect object\n */\nfunction includeScroll(rect, element) {\n var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n var scrollTop = getScroll(element, 'top');\n var scrollLeft = getScroll(element, 'left');\n var modifier = subtract ? -1 : 1;\n rect.top += scrollTop * modifier;\n rect.bottom += scrollTop * modifier;\n rect.left += scrollLeft * modifier;\n rect.right += scrollLeft * modifier;\n return rect;\n}\n\n/*\n * Helper to detect borders of a given element\n * @method\n * @memberof Popper.Utils\n * @param {CSSStyleDeclaration} styles\n * Result of `getStyleComputedProperty` on the given element\n * @param {String} axis - `x` or `y`\n * @return {number} borders - The borders size of the given axis\n */\n\nfunction getBordersSize(styles, axis) {\n var sideA = axis === 'x' ? 'Left' : 'Top';\n var sideB = sideA === 'Left' ? 'Right' : 'Bottom';\n\n return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']);\n}\n\nfunction getSize(axis, body, html, computedStyle) {\n return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);\n}\n\nfunction getWindowSizes(document) {\n var body = document.body;\n var html = document.documentElement;\n var computedStyle = isIE(10) && getComputedStyle(html);\n\n return {\n height: getSize('Height', body, html, computedStyle),\n width: getSize('Width', body, html, computedStyle)\n };\n}\n\nvar classCallCheck = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nvar createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\n\n\n\n\nvar defineProperty = function (obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n};\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\n/**\n * Given element offsets, generate an output similar to getBoundingClientRect\n * @method\n * @memberof Popper.Utils\n * @argument {Object} offsets\n * @returns {Object} ClientRect like output\n */\nfunction getClientRect(offsets) {\n return _extends({}, offsets, {\n right: offsets.left + offsets.width,\n bottom: offsets.top + offsets.height\n });\n}\n\n/**\n * Get bounding client rect of given element\n * @method\n * @memberof Popper.Utils\n * @param {HTMLElement} element\n * @return {Object} client rect\n */\nfunction getBoundingClientRect(element) {\n var rect = {};\n\n // IE10 10 FIX: Please, don't ask, the element isn't\n // considered in DOM in some circumstances...\n // This isn't reproducible in IE10 compatibility mode of IE11\n try {\n if (isIE(10)) {\n rect = element.getBoundingClientRect();\n var scrollTop = getScroll(element, 'top');\n var scrollLeft = getScroll(element, 'left');\n rect.top += scrollTop;\n rect.left += scrollLeft;\n rect.bottom += scrollTop;\n rect.right += scrollLeft;\n } else {\n rect = element.getBoundingClientRect();\n }\n } catch (e) {}\n\n var result = {\n left: rect.left,\n top: rect.top,\n width: rect.right - rect.left,\n height: rect.bottom - rect.top\n };\n\n // subtract scrollbar size from sizes\n var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};\n var width = sizes.width || element.clientWidth || result.width;\n var height = sizes.height || element.clientHeight || result.height;\n\n var horizScrollbar = element.offsetWidth - width;\n var vertScrollbar = element.offsetHeight - height;\n\n // if an hypothetical scrollbar is detected, we must be sure it's not a `border`\n // we make this check conditional for performance reasons\n if (horizScrollbar || vertScrollbar) {\n var styles = getStyleComputedProperty(element);\n horizScrollbar -= getBordersSize(styles, 'x');\n vertScrollbar -= getBordersSize(styles, 'y');\n\n result.width -= horizScrollbar;\n result.height -= vertScrollbar;\n }\n\n return getClientRect(result);\n}\n\nfunction getOffsetRectRelativeToArbitraryNode(children, parent) {\n var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n var isIE10 = isIE(10);\n var isHTML = parent.nodeName === 'HTML';\n var childrenRect = getBoundingClientRect(children);\n var parentRect = getBoundingClientRect(parent);\n var scrollParent = getScrollParent(children);\n\n var styles = getStyleComputedProperty(parent);\n var borderTopWidth = parseFloat(styles.borderTopWidth);\n var borderLeftWidth = parseFloat(styles.borderLeftWidth);\n\n // In cases where the parent is fixed, we must ignore negative scroll in offset calc\n if (fixedPosition && isHTML) {\n parentRect.top = Math.max(parentRect.top, 0);\n parentRect.left = Math.max(parentRect.left, 0);\n }\n var offsets = getClientRect({\n top: childrenRect.top - parentRect.top - borderTopWidth,\n left: childrenRect.left - parentRect.left - borderLeftWidth,\n width: childrenRect.width,\n height: childrenRect.height\n });\n offsets.marginTop = 0;\n offsets.marginLeft = 0;\n\n // Subtract margins of documentElement in case it's being used as parent\n // we do this only on HTML because it's the only element that behaves\n // differently when margins are applied to it. The margins are included in\n // the box of the documentElement, in the other cases not.\n if (!isIE10 && isHTML) {\n var marginTop = parseFloat(styles.marginTop);\n var marginLeft = parseFloat(styles.marginLeft);\n\n offsets.top -= borderTopWidth - marginTop;\n offsets.bottom -= borderTopWidth - marginTop;\n offsets.left -= borderLeftWidth - marginLeft;\n offsets.right -= borderLeftWidth - marginLeft;\n\n // Attach marginTop and marginLeft because in some circumstances we may need them\n offsets.marginTop = marginTop;\n offsets.marginLeft = marginLeft;\n }\n\n if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {\n offsets = includeScroll(offsets, parent);\n }\n\n return offsets;\n}\n\nfunction getViewportOffsetRectRelativeToArtbitraryNode(element) {\n var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var html = element.ownerDocument.documentElement;\n var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);\n var width = Math.max(html.clientWidth, window.innerWidth || 0);\n var height = Math.max(html.clientHeight, window.innerHeight || 0);\n\n var scrollTop = !excludeScroll ? getScroll(html) : 0;\n var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;\n\n var offset = {\n top: scrollTop - relativeOffset.top + relativeOffset.marginTop,\n left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,\n width: width,\n height: height\n };\n\n return getClientRect(offset);\n}\n\n/**\n * Check if the given element is fixed or is inside a fixed parent\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @argument {Element} customContainer\n * @returns {Boolean} answer to \"isFixed?\"\n */\nfunction isFixed(element) {\n var nodeName = element.nodeName;\n if (nodeName === 'BODY' || nodeName === 'HTML') {\n return false;\n }\n if (getStyleComputedProperty(element, 'position') === 'fixed') {\n return true;\n }\n var parentNode = getParentNode(element);\n if (!parentNode) {\n return false;\n }\n return isFixed(parentNode);\n}\n\n/**\n * Finds the first parent of an element that has a transformed property defined\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @returns {Element} first transformed parent or documentElement\n */\n\nfunction getFixedPositionOffsetParent(element) {\n // This check is needed to avoid errors in case one of the elements isn't defined for any reason\n if (!element || !element.parentElement || isIE()) {\n return document.documentElement;\n }\n var el = element.parentElement;\n while (el && getStyleComputedProperty(el, 'transform') === 'none') {\n el = el.parentElement;\n }\n return el || document.documentElement;\n}\n\n/**\n * Computed the boundaries limits and return them\n * @method\n * @memberof Popper.Utils\n * @param {HTMLElement} popper\n * @param {HTMLElement} reference\n * @param {number} padding\n * @param {HTMLElement} boundariesElement - Element used to define the boundaries\n * @param {Boolean} fixedPosition - Is in fixed position mode\n * @returns {Object} Coordinates of the boundaries\n */\nfunction getBoundaries(popper, reference, padding, boundariesElement) {\n var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;\n\n // NOTE: 1 DOM access here\n\n var boundaries = { top: 0, left: 0 };\n var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));\n\n // Handle viewport case\n if (boundariesElement === 'viewport') {\n boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);\n } else {\n // Handle other cases based on DOM element used as boundaries\n var boundariesNode = void 0;\n if (boundariesElement === 'scrollParent') {\n boundariesNode = getScrollParent(getParentNode(reference));\n if (boundariesNode.nodeName === 'BODY') {\n boundariesNode = popper.ownerDocument.documentElement;\n }\n } else if (boundariesElement === 'window') {\n boundariesNode = popper.ownerDocument.documentElement;\n } else {\n boundariesNode = boundariesElement;\n }\n\n var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);\n\n // In case of HTML, we need a different computation\n if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {\n var _getWindowSizes = getWindowSizes(popper.ownerDocument),\n height = _getWindowSizes.height,\n width = _getWindowSizes.width;\n\n boundaries.top += offsets.top - offsets.marginTop;\n boundaries.bottom = height + offsets.top;\n boundaries.left += offsets.left - offsets.marginLeft;\n boundaries.right = width + offsets.left;\n } else {\n // for all the other DOM elements, this one is good\n boundaries = offsets;\n }\n }\n\n // Add paddings\n padding = padding || 0;\n var isPaddingNumber = typeof padding === 'number';\n boundaries.left += isPaddingNumber ? padding : padding.left || 0;\n boundaries.top += isPaddingNumber ? padding : padding.top || 0;\n boundaries.right -= isPaddingNumber ? padding : padding.right || 0;\n boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;\n\n return boundaries;\n}\n\nfunction getArea(_ref) {\n var width = _ref.width,\n height = _ref.height;\n\n return width * height;\n}\n\n/**\n * Utility used to transform the `auto` placement to the placement with more\n * available space.\n * @method\n * @memberof Popper.Utils\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {\n var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;\n\n if (placement.indexOf('auto') === -1) {\n return placement;\n }\n\n var boundaries = getBoundaries(popper, reference, padding, boundariesElement);\n\n var rects = {\n top: {\n width: boundaries.width,\n height: refRect.top - boundaries.top\n },\n right: {\n width: boundaries.right - refRect.right,\n height: boundaries.height\n },\n bottom: {\n width: boundaries.width,\n height: boundaries.bottom - refRect.bottom\n },\n left: {\n width: refRect.left - boundaries.left,\n height: boundaries.height\n }\n };\n\n var sortedAreas = Object.keys(rects).map(function (key) {\n return _extends({\n key: key\n }, rects[key], {\n area: getArea(rects[key])\n });\n }).sort(function (a, b) {\n return b.area - a.area;\n });\n\n var filteredAreas = sortedAreas.filter(function (_ref2) {\n var width = _ref2.width,\n height = _ref2.height;\n return width >= popper.clientWidth && height >= popper.clientHeight;\n });\n\n var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;\n\n var variation = placement.split('-')[1];\n\n return computedPlacement + (variation ? '-' + variation : '');\n}\n\n/**\n * Get offsets to the reference element\n * @method\n * @memberof Popper.Utils\n * @param {Object} state\n * @param {Element} popper - the popper element\n * @param {Element} reference - the reference element (the popper will be relative to this)\n * @param {Element} fixedPosition - is in fixed position mode\n * @returns {Object} An object containing the offsets which will be applied to the popper\n */\nfunction getReferenceOffsets(state, popper, reference) {\n var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));\n return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);\n}\n\n/**\n * Get the outer sizes of the given element (offset size + margins)\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element\n * @returns {Object} object containing width and height properties\n */\nfunction getOuterSizes(element) {\n var window = element.ownerDocument.defaultView;\n var styles = window.getComputedStyle(element);\n var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);\n var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);\n var result = {\n width: element.offsetWidth + y,\n height: element.offsetHeight + x\n };\n return result;\n}\n\n/**\n * Get the opposite placement of the given one\n * @method\n * @memberof Popper.Utils\n * @argument {String} placement\n * @returns {String} flipped placement\n */\nfunction getOppositePlacement(placement) {\n var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}\n\n/**\n * Get offsets to the popper\n * @method\n * @memberof Popper.Utils\n * @param {Object} position - CSS position the Popper will get applied\n * @param {HTMLElement} popper - the popper element\n * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)\n * @param {String} placement - one of the valid placement options\n * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper\n */\nfunction getPopperOffsets(popper, referenceOffsets, placement) {\n placement = placement.split('-')[0];\n\n // Get popper node sizes\n var popperRect = getOuterSizes(popper);\n\n // Add position, width and height to our offsets object\n var popperOffsets = {\n width: popperRect.width,\n height: popperRect.height\n };\n\n // depending by the popper placement we have to compute its offsets slightly differently\n var isHoriz = ['right', 'left'].indexOf(placement) !== -1;\n var mainSide = isHoriz ? 'top' : 'left';\n var secondarySide = isHoriz ? 'left' : 'top';\n var measurement = isHoriz ? 'height' : 'width';\n var secondaryMeasurement = !isHoriz ? 'height' : 'width';\n\n popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;\n if (placement === secondarySide) {\n popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];\n } else {\n popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];\n }\n\n return popperOffsets;\n}\n\n/**\n * Mimics the `find` method of Array\n * @method\n * @memberof Popper.Utils\n * @argument {Array} arr\n * @argument prop\n * @argument value\n * @returns index or -1\n */\nfunction find(arr, check) {\n // use native find if supported\n if (Array.prototype.find) {\n return arr.find(check);\n }\n\n // use `filter` to obtain the same behavior of `find`\n return arr.filter(check)[0];\n}\n\n/**\n * Return the index of the matching object\n * @method\n * @memberof Popper.Utils\n * @argument {Array} arr\n * @argument prop\n * @argument value\n * @returns index or -1\n */\nfunction findIndex(arr, prop, value) {\n // use native findIndex if supported\n if (Array.prototype.findIndex) {\n return arr.findIndex(function (cur) {\n return cur[prop] === value;\n });\n }\n\n // use `find` + `indexOf` if `findIndex` isn't supported\n var match = find(arr, function (obj) {\n return obj[prop] === value;\n });\n return arr.indexOf(match);\n}\n\n/**\n * Loop trough the list of modifiers and run them in order,\n * each of them will then edit the data object.\n * @method\n * @memberof Popper.Utils\n * @param {dataObject} data\n * @param {Array} modifiers\n * @param {String} ends - Optional modifier name used as stopper\n * @returns {dataObject}\n */\nfunction runModifiers(modifiers, data, ends) {\n var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));\n\n modifiersToRun.forEach(function (modifier) {\n if (modifier['function']) {\n // eslint-disable-line dot-notation\n console.warn('`modifier.function` is deprecated, use `modifier.fn`!');\n }\n var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation\n if (modifier.enabled && isFunction(fn)) {\n // Add properties to offsets to make them a complete clientRect object\n // we do this before each modifier to make sure the previous one doesn't\n // mess with these values\n data.offsets.popper = getClientRect(data.offsets.popper);\n data.offsets.reference = getClientRect(data.offsets.reference);\n\n data = fn(data, modifier);\n }\n });\n\n return data;\n}\n\n/**\n * Updates the position of the popper, computing the new offsets and applying\n * the new style.
\n * Prefer `scheduleUpdate` over `update` because of performance reasons.\n * @method\n * @memberof Popper\n */\nfunction update() {\n // if popper is destroyed, don't perform any further update\n if (this.state.isDestroyed) {\n return;\n }\n\n var data = {\n instance: this,\n styles: {},\n arrowStyles: {},\n attributes: {},\n flipped: false,\n offsets: {}\n };\n\n // compute reference element offsets\n data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);\n\n // compute auto placement, store placement inside the data object,\n // modifiers will be able to edit `placement` if needed\n // and refer to originalPlacement to know the original value\n data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);\n\n // store the computed placement inside `originalPlacement`\n data.originalPlacement = data.placement;\n\n data.positionFixed = this.options.positionFixed;\n\n // compute the popper offsets\n data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);\n\n data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';\n\n // run the modifiers\n data = runModifiers(this.modifiers, data);\n\n // the first `update` will call `onCreate` callback\n // the other ones will call `onUpdate` callback\n if (!this.state.isCreated) {\n this.state.isCreated = true;\n this.options.onCreate(data);\n } else {\n this.options.onUpdate(data);\n }\n}\n\n/**\n * Helper used to know if the given modifier is enabled.\n * @method\n * @memberof Popper.Utils\n * @returns {Boolean}\n */\nfunction isModifierEnabled(modifiers, modifierName) {\n return modifiers.some(function (_ref) {\n var name = _ref.name,\n enabled = _ref.enabled;\n return enabled && name === modifierName;\n });\n}\n\n/**\n * Get the prefixed supported property name\n * @method\n * @memberof Popper.Utils\n * @argument {String} property (camelCase)\n * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)\n */\nfunction getSupportedPropertyName(property) {\n var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];\n var upperProp = property.charAt(0).toUpperCase() + property.slice(1);\n\n for (var i = 0; i < prefixes.length; i++) {\n var prefix = prefixes[i];\n var toCheck = prefix ? '' + prefix + upperProp : property;\n if (typeof document.body.style[toCheck] !== 'undefined') {\n return toCheck;\n }\n }\n return null;\n}\n\n/**\n * Destroys the popper.\n * @method\n * @memberof Popper\n */\nfunction destroy() {\n this.state.isDestroyed = true;\n\n // touch DOM only if `applyStyle` modifier is enabled\n if (isModifierEnabled(this.modifiers, 'applyStyle')) {\n this.popper.removeAttribute('x-placement');\n this.popper.style.position = '';\n this.popper.style.top = '';\n this.popper.style.left = '';\n this.popper.style.right = '';\n this.popper.style.bottom = '';\n this.popper.style.willChange = '';\n this.popper.style[getSupportedPropertyName('transform')] = '';\n }\n\n this.disableEventListeners();\n\n // remove the popper if user explicitly asked for the deletion on destroy\n // do not use `remove` because IE11 doesn't support it\n if (this.options.removeOnDestroy) {\n this.popper.parentNode.removeChild(this.popper);\n }\n return this;\n}\n\n/**\n * Get the window associated with the element\n * @argument {Element} element\n * @returns {Window}\n */\nfunction getWindow(element) {\n var ownerDocument = element.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView : window;\n}\n\nfunction attachToScrollParents(scrollParent, event, callback, scrollParents) {\n var isBody = scrollParent.nodeName === 'BODY';\n var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;\n target.addEventListener(event, callback, { passive: true });\n\n if (!isBody) {\n attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);\n }\n scrollParents.push(target);\n}\n\n/**\n * Setup needed event listeners used to update the popper position\n * @method\n * @memberof Popper.Utils\n * @private\n */\nfunction setupEventListeners(reference, options, state, updateBound) {\n // Resize event listener on window\n state.updateBound = updateBound;\n getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });\n\n // Scroll event listener on scroll parents\n var scrollElement = getScrollParent(reference);\n attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);\n state.scrollElement = scrollElement;\n state.eventsEnabled = true;\n\n return state;\n}\n\n/**\n * It will add resize/scroll events and start recalculating\n * position of the popper element when they are triggered.\n * @method\n * @memberof Popper\n */\nfunction enableEventListeners() {\n if (!this.state.eventsEnabled) {\n this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);\n }\n}\n\n/**\n * Remove event listeners used to update the popper position\n * @method\n * @memberof Popper.Utils\n * @private\n */\nfunction removeEventListeners(reference, state) {\n // Remove resize event listener on window\n getWindow(reference).removeEventListener('resize', state.updateBound);\n\n // Remove scroll event listener on scroll parents\n state.scrollParents.forEach(function (target) {\n target.removeEventListener('scroll', state.updateBound);\n });\n\n // Reset state\n state.updateBound = null;\n state.scrollParents = [];\n state.scrollElement = null;\n state.eventsEnabled = false;\n return state;\n}\n\n/**\n * It will remove resize/scroll events and won't recalculate popper position\n * when they are triggered. It also won't trigger `onUpdate` callback anymore,\n * unless you call `update` method manually.\n * @method\n * @memberof Popper\n */\nfunction disableEventListeners() {\n if (this.state.eventsEnabled) {\n cancelAnimationFrame(this.scheduleUpdate);\n this.state = removeEventListeners(this.reference, this.state);\n }\n}\n\n/**\n * Tells if a given input is a number\n * @method\n * @memberof Popper.Utils\n * @param {*} input to check\n * @return {Boolean}\n */\nfunction isNumeric(n) {\n return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);\n}\n\n/**\n * Set the style to the given popper\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element - Element to apply the style to\n * @argument {Object} styles\n * Object with a list of properties and values which will be applied to the element\n */\nfunction setStyles(element, styles) {\n Object.keys(styles).forEach(function (prop) {\n var unit = '';\n // add unit if the value is numeric and is one of the following\n if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {\n unit = 'px';\n }\n element.style[prop] = styles[prop] + unit;\n });\n}\n\n/**\n * Set the attributes to the given popper\n * @method\n * @memberof Popper.Utils\n * @argument {Element} element - Element to apply the attributes to\n * @argument {Object} styles\n * Object with a list of properties and values which will be applied to the element\n */\nfunction setAttributes(element, attributes) {\n Object.keys(attributes).forEach(function (prop) {\n var value = attributes[prop];\n if (value !== false) {\n element.setAttribute(prop, attributes[prop]);\n } else {\n element.removeAttribute(prop);\n }\n });\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Object} data.styles - List of style properties - values to apply to popper element\n * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The same data object\n */\nfunction applyStyle(data) {\n // any property present in `data.styles` will be applied to the popper,\n // in this way we can make the 3rd party modifiers add custom styles to it\n // Be aware, modifiers could override the properties defined in the previous\n // lines of this modifier!\n setStyles(data.instance.popper, data.styles);\n\n // any property present in `data.attributes` will be applied to the popper,\n // they will be set as HTML attributes of the element\n setAttributes(data.instance.popper, data.attributes);\n\n // if arrowElement is defined and arrowStyles has some properties\n if (data.arrowElement && Object.keys(data.arrowStyles).length) {\n setStyles(data.arrowElement, data.arrowStyles);\n }\n\n return data;\n}\n\n/**\n * Set the x-placement attribute before everything else because it could be used\n * to add margins to the popper margins needs to be calculated to get the\n * correct popper offsets.\n * @method\n * @memberof Popper.modifiers\n * @param {HTMLElement} reference - The reference element used to position the popper\n * @param {HTMLElement} popper - The HTML element used as popper\n * @param {Object} options - Popper.js options\n */\nfunction applyStyleOnLoad(reference, popper, options, modifierOptions, state) {\n // compute reference element offsets\n var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);\n\n // compute auto placement, store placement inside the data object,\n // modifiers will be able to edit `placement` if needed\n // and refer to originalPlacement to know the original value\n var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);\n\n popper.setAttribute('x-placement', placement);\n\n // Apply `position` to popper before anything else because\n // without the position applied we can't guarantee correct computations\n setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });\n\n return options;\n}\n\n/**\n * @function\n * @memberof Popper.Utils\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Boolean} shouldRound - If the offsets should be rounded at all\n * @returns {Object} The popper's position offsets rounded\n *\n * The tale of pixel-perfect positioning. It's still not 100% perfect, but as\n * good as it can be within reason.\n * Discussion here: https://github.com/FezVrasta/popper.js/pull/715\n *\n * Low DPI screens cause a popper to be blurry if not using full pixels (Safari\n * as well on High DPI screens).\n *\n * Firefox prefers no rounding for positioning and does not have blurriness on\n * high DPI screens.\n *\n * Only horizontal placement and left/right values need to be considered.\n */\nfunction getRoundedOffsets(data, shouldRound) {\n var _data$offsets = data.offsets,\n popper = _data$offsets.popper,\n reference = _data$offsets.reference;\n var round = Math.round,\n floor = Math.floor;\n\n var noRound = function noRound(v) {\n return v;\n };\n\n var referenceWidth = round(reference.width);\n var popperWidth = round(popper.width);\n\n var isVertical = ['left', 'right'].indexOf(data.placement) !== -1;\n var isVariation = data.placement.indexOf('-') !== -1;\n var sameWidthParity = referenceWidth % 2 === popperWidth % 2;\n var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;\n\n var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;\n var verticalToInteger = !shouldRound ? noRound : round;\n\n return {\n left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),\n top: verticalToInteger(popper.top),\n bottom: verticalToInteger(popper.bottom),\n right: horizontalToInteger(popper.right)\n };\n}\n\nvar isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction computeStyle(data, options) {\n var x = options.x,\n y = options.y;\n var popper = data.offsets.popper;\n\n // Remove this legacy support in Popper.js v2\n\n var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {\n return modifier.name === 'applyStyle';\n }).gpuAcceleration;\n if (legacyGpuAccelerationOption !== undefined) {\n console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');\n }\n var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;\n\n var offsetParent = getOffsetParent(data.instance.popper);\n var offsetParentRect = getBoundingClientRect(offsetParent);\n\n // Styles\n var styles = {\n position: popper.position\n };\n\n var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);\n\n var sideA = x === 'bottom' ? 'top' : 'bottom';\n var sideB = y === 'right' ? 'left' : 'right';\n\n // if gpuAcceleration is set to `true` and transform is supported,\n // we use `translate3d` to apply the position to the popper we\n // automatically use the supported prefixed version if needed\n var prefixedProperty = getSupportedPropertyName('transform');\n\n // now, let's make a step back and look at this code closely (wtf?)\n // If the content of the popper grows once it's been positioned, it\n // may happen that the popper gets misplaced because of the new content\n // overflowing its reference element\n // To avoid this problem, we provide two options (x and y), which allow\n // the consumer to define the offset origin.\n // If we position a popper on top of a reference element, we can set\n // `x` to `top` to make the popper grow towards its top instead of\n // its bottom.\n var left = void 0,\n top = void 0;\n if (sideA === 'bottom') {\n // when offsetParent is the positioning is relative to the bottom of the screen (excluding the scrollbar)\n // and not the bottom of the html element\n if (offsetParent.nodeName === 'HTML') {\n top = -offsetParent.clientHeight + offsets.bottom;\n } else {\n top = -offsetParentRect.height + offsets.bottom;\n }\n } else {\n top = offsets.top;\n }\n if (sideB === 'right') {\n if (offsetParent.nodeName === 'HTML') {\n left = -offsetParent.clientWidth + offsets.right;\n } else {\n left = -offsetParentRect.width + offsets.right;\n }\n } else {\n left = offsets.left;\n }\n if (gpuAcceleration && prefixedProperty) {\n styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';\n styles[sideA] = 0;\n styles[sideB] = 0;\n styles.willChange = 'transform';\n } else {\n // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties\n var invertTop = sideA === 'bottom' ? -1 : 1;\n var invertLeft = sideB === 'right' ? -1 : 1;\n styles[sideA] = top * invertTop;\n styles[sideB] = left * invertLeft;\n styles.willChange = sideA + ', ' + sideB;\n }\n\n // Attributes\n var attributes = {\n 'x-placement': data.placement\n };\n\n // Update `data` attributes, styles and arrowStyles\n data.attributes = _extends({}, attributes, data.attributes);\n data.styles = _extends({}, styles, data.styles);\n data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);\n\n return data;\n}\n\n/**\n * Helper used to know if the given modifier depends from another one.
\n * It checks if the needed modifier is listed and enabled.\n * @method\n * @memberof Popper.Utils\n * @param {Array} modifiers - list of modifiers\n * @param {String} requestingName - name of requesting modifier\n * @param {String} requestedName - name of requested modifier\n * @returns {Boolean}\n */\nfunction isModifierRequired(modifiers, requestingName, requestedName) {\n var requesting = find(modifiers, function (_ref) {\n var name = _ref.name;\n return name === requestingName;\n });\n\n var isRequired = !!requesting && modifiers.some(function (modifier) {\n return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;\n });\n\n if (!isRequired) {\n var _requesting = '`' + requestingName + '`';\n var requested = '`' + requestedName + '`';\n console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');\n }\n return isRequired;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction arrow(data, options) {\n var _data$offsets$arrow;\n\n // arrow depends on keepTogether in order to work\n if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {\n return data;\n }\n\n var arrowElement = options.element;\n\n // if arrowElement is a string, suppose it's a CSS selector\n if (typeof arrowElement === 'string') {\n arrowElement = data.instance.popper.querySelector(arrowElement);\n\n // if arrowElement is not found, don't run the modifier\n if (!arrowElement) {\n return data;\n }\n } else {\n // if the arrowElement isn't a query selector we must check that the\n // provided DOM node is child of its popper node\n if (!data.instance.popper.contains(arrowElement)) {\n console.warn('WARNING: `arrow.element` must be child of its popper element!');\n return data;\n }\n }\n\n var placement = data.placement.split('-')[0];\n var _data$offsets = data.offsets,\n popper = _data$offsets.popper,\n reference = _data$offsets.reference;\n\n var isVertical = ['left', 'right'].indexOf(placement) !== -1;\n\n var len = isVertical ? 'height' : 'width';\n var sideCapitalized = isVertical ? 'Top' : 'Left';\n var side = sideCapitalized.toLowerCase();\n var altSide = isVertical ? 'left' : 'top';\n var opSide = isVertical ? 'bottom' : 'right';\n var arrowElementSize = getOuterSizes(arrowElement)[len];\n\n //\n // extends keepTogether behavior making sure the popper and its\n // reference have enough pixels in conjunction\n //\n\n // top/left side\n if (reference[opSide] - arrowElementSize < popper[side]) {\n data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);\n }\n // bottom/right side\n if (reference[side] + arrowElementSize > popper[opSide]) {\n data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];\n }\n data.offsets.popper = getClientRect(data.offsets.popper);\n\n // compute center of the popper\n var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;\n\n // Compute the sideValue using the updated popper offsets\n // take popper margin in account because we don't have this info available\n var css = getStyleComputedProperty(data.instance.popper);\n var popperMarginSide = parseFloat(css['margin' + sideCapitalized]);\n var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width']);\n var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;\n\n // prevent arrowElement from being placed not contiguously to its popper\n sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);\n\n data.arrowElement = arrowElement;\n data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);\n\n return data;\n}\n\n/**\n * Get the opposite placement variation of the given one\n * @method\n * @memberof Popper.Utils\n * @argument {String} placement variation\n * @returns {String} flipped placement variation\n */\nfunction getOppositeVariation(variation) {\n if (variation === 'end') {\n return 'start';\n } else if (variation === 'start') {\n return 'end';\n }\n return variation;\n}\n\n/**\n * List of accepted placements to use as values of the `placement` option.
\n * Valid placements are:\n * - `auto`\n * - `top`\n * - `right`\n * - `bottom`\n * - `left`\n *\n * Each placement can have a variation from this list:\n * - `-start`\n * - `-end`\n *\n * Variations are interpreted easily if you think of them as the left to right\n * written languages. Horizontally (`top` and `bottom`), `start` is left and `end`\n * is right.
\n * Vertically (`left` and `right`), `start` is top and `end` is bottom.\n *\n * Some valid examples are:\n * - `top-end` (on top of reference, right aligned)\n * - `right-start` (on right of reference, top aligned)\n * - `bottom` (on bottom, centered)\n * - `auto-end` (on the side with more space available, alignment depends by placement)\n *\n * @static\n * @type {Array}\n * @enum {String}\n * @readonly\n * @method placements\n * @memberof Popper\n */\nvar placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];\n\n// Get rid of `auto` `auto-start` and `auto-end`\nvar validPlacements = placements.slice(3);\n\n/**\n * Given an initial placement, returns all the subsequent placements\n * clockwise (or counter-clockwise).\n *\n * @method\n * @memberof Popper.Utils\n * @argument {String} placement - A valid placement (it accepts variations)\n * @argument {Boolean} counter - Set to true to walk the placements counterclockwise\n * @returns {Array} placements including their variations\n */\nfunction clockwise(placement) {\n var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var index = validPlacements.indexOf(placement);\n var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));\n return counter ? arr.reverse() : arr;\n}\n\nvar BEHAVIORS = {\n FLIP: 'flip',\n CLOCKWISE: 'clockwise',\n COUNTERCLOCKWISE: 'counterclockwise'\n};\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction flip(data, options) {\n // if `inner` modifier is enabled, we can't use the `flip` modifier\n if (isModifierEnabled(data.instance.modifiers, 'inner')) {\n return data;\n }\n\n if (data.flipped && data.placement === data.originalPlacement) {\n // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides\n return data;\n }\n\n var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);\n\n var placement = data.placement.split('-')[0];\n var placementOpposite = getOppositePlacement(placement);\n var variation = data.placement.split('-')[1] || '';\n\n var flipOrder = [];\n\n switch (options.behavior) {\n case BEHAVIORS.FLIP:\n flipOrder = [placement, placementOpposite];\n break;\n case BEHAVIORS.CLOCKWISE:\n flipOrder = clockwise(placement);\n break;\n case BEHAVIORS.COUNTERCLOCKWISE:\n flipOrder = clockwise(placement, true);\n break;\n default:\n flipOrder = options.behavior;\n }\n\n flipOrder.forEach(function (step, index) {\n if (placement !== step || flipOrder.length === index + 1) {\n return data;\n }\n\n placement = data.placement.split('-')[0];\n placementOpposite = getOppositePlacement(placement);\n\n var popperOffsets = data.offsets.popper;\n var refOffsets = data.offsets.reference;\n\n // using floor because the reference offsets may contain decimals we are not going to consider here\n var floor = Math.floor;\n var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);\n\n var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);\n var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);\n var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);\n var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);\n\n var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;\n\n // flip the variation if required\n var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;\n\n // flips variation if reference element overflows boundaries\n var flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);\n\n // flips variation if popper content overflows boundaries\n var flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop);\n\n var flippedVariation = flippedVariationByRef || flippedVariationByContent;\n\n if (overlapsRef || overflowsBoundaries || flippedVariation) {\n // this boolean to detect any flip loop\n data.flipped = true;\n\n if (overlapsRef || overflowsBoundaries) {\n placement = flipOrder[index + 1];\n }\n\n if (flippedVariation) {\n variation = getOppositeVariation(variation);\n }\n\n data.placement = placement + (variation ? '-' + variation : '');\n\n // this object contains `position`, we want to preserve it along with\n // any additional property we may add in the future\n data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));\n\n data = runModifiers(data.instance.modifiers, data, 'flip');\n }\n });\n return data;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction keepTogether(data) {\n var _data$offsets = data.offsets,\n popper = _data$offsets.popper,\n reference = _data$offsets.reference;\n\n var placement = data.placement.split('-')[0];\n var floor = Math.floor;\n var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;\n var side = isVertical ? 'right' : 'bottom';\n var opSide = isVertical ? 'left' : 'top';\n var measurement = isVertical ? 'width' : 'height';\n\n if (popper[side] < floor(reference[opSide])) {\n data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];\n }\n if (popper[opSide] > floor(reference[side])) {\n data.offsets.popper[opSide] = floor(reference[side]);\n }\n\n return data;\n}\n\n/**\n * Converts a string containing value + unit into a px value number\n * @function\n * @memberof {modifiers~offset}\n * @private\n * @argument {String} str - Value + unit string\n * @argument {String} measurement - `height` or `width`\n * @argument {Object} popperOffsets\n * @argument {Object} referenceOffsets\n * @returns {Number|String}\n * Value in pixels, or original string if no values were extracted\n */\nfunction toValue(str, measurement, popperOffsets, referenceOffsets) {\n // separate value from unit\n var split = str.match(/((?:\\-|\\+)?\\d*\\.?\\d*)(.*)/);\n var value = +split[1];\n var unit = split[2];\n\n // If it's not a number it's an operator, I guess\n if (!value) {\n return str;\n }\n\n if (unit.indexOf('%') === 0) {\n var element = void 0;\n switch (unit) {\n case '%p':\n element = popperOffsets;\n break;\n case '%':\n case '%r':\n default:\n element = referenceOffsets;\n }\n\n var rect = getClientRect(element);\n return rect[measurement] / 100 * value;\n } else if (unit === 'vh' || unit === 'vw') {\n // if is a vh or vw, we calculate the size based on the viewport\n var size = void 0;\n if (unit === 'vh') {\n size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);\n } else {\n size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);\n }\n return size / 100 * value;\n } else {\n // if is an explicit pixel unit, we get rid of the unit and keep the value\n // if is an implicit unit, it's px, and we return just the value\n return value;\n }\n}\n\n/**\n * Parse an `offset` string to extrapolate `x` and `y` numeric offsets.\n * @function\n * @memberof {modifiers~offset}\n * @private\n * @argument {String} offset\n * @argument {Object} popperOffsets\n * @argument {Object} referenceOffsets\n * @argument {String} basePlacement\n * @returns {Array} a two cells array with x and y offsets in numbers\n */\nfunction parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {\n var offsets = [0, 0];\n\n // Use height if placement is left or right and index is 0 otherwise use width\n // in this way the first offset will use an axis and the second one\n // will use the other one\n var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;\n\n // Split the offset string to obtain a list of values and operands\n // The regex addresses values with the plus or minus sign in front (+10, -20, etc)\n var fragments = offset.split(/(\\+|\\-)/).map(function (frag) {\n return frag.trim();\n });\n\n // Detect if the offset string contains a pair of values or a single one\n // they could be separated by comma or space\n var divider = fragments.indexOf(find(fragments, function (frag) {\n return frag.search(/,|\\s/) !== -1;\n }));\n\n if (fragments[divider] && fragments[divider].indexOf(',') === -1) {\n console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');\n }\n\n // If divider is found, we divide the list of values and operands to divide\n // them by ofset X and Y.\n var splitRegex = /\\s*,\\s*|\\s+/;\n var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];\n\n // Convert the values with units to absolute pixels to allow our computations\n ops = ops.map(function (op, index) {\n // Most of the units rely on the orientation of the popper\n var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';\n var mergeWithPrevious = false;\n return op\n // This aggregates any `+` or `-` sign that aren't considered operators\n // e.g.: 10 + +5 => [10, +, +5]\n .reduce(function (a, b) {\n if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {\n a[a.length - 1] = b;\n mergeWithPrevious = true;\n return a;\n } else if (mergeWithPrevious) {\n a[a.length - 1] += b;\n mergeWithPrevious = false;\n return a;\n } else {\n return a.concat(b);\n }\n }, [])\n // Here we convert the string values into number values (in px)\n .map(function (str) {\n return toValue(str, measurement, popperOffsets, referenceOffsets);\n });\n });\n\n // Loop trough the offsets arrays and execute the operations\n ops.forEach(function (op, index) {\n op.forEach(function (frag, index2) {\n if (isNumeric(frag)) {\n offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);\n }\n });\n });\n return offsets;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @argument {Number|String} options.offset=0\n * The offset value as described in the modifier description\n * @returns {Object} The data object, properly modified\n */\nfunction offset(data, _ref) {\n var offset = _ref.offset;\n var placement = data.placement,\n _data$offsets = data.offsets,\n popper = _data$offsets.popper,\n reference = _data$offsets.reference;\n\n var basePlacement = placement.split('-')[0];\n\n var offsets = void 0;\n if (isNumeric(+offset)) {\n offsets = [+offset, 0];\n } else {\n offsets = parseOffset(offset, popper, reference, basePlacement);\n }\n\n if (basePlacement === 'left') {\n popper.top += offsets[0];\n popper.left -= offsets[1];\n } else if (basePlacement === 'right') {\n popper.top += offsets[0];\n popper.left += offsets[1];\n } else if (basePlacement === 'top') {\n popper.left += offsets[0];\n popper.top -= offsets[1];\n } else if (basePlacement === 'bottom') {\n popper.left += offsets[0];\n popper.top += offsets[1];\n }\n\n data.popper = popper;\n return data;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction preventOverflow(data, options) {\n var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);\n\n // If offsetParent is the reference element, we really want to\n // go one step up and use the next offsetParent as reference to\n // avoid to make this modifier completely useless and look like broken\n if (data.instance.reference === boundariesElement) {\n boundariesElement = getOffsetParent(boundariesElement);\n }\n\n // NOTE: DOM access here\n // resets the popper's position so that the document size can be calculated excluding\n // the size of the popper element itself\n var transformProp = getSupportedPropertyName('transform');\n var popperStyles = data.instance.popper.style; // assignment to help minification\n var top = popperStyles.top,\n left = popperStyles.left,\n transform = popperStyles[transformProp];\n\n popperStyles.top = '';\n popperStyles.left = '';\n popperStyles[transformProp] = '';\n\n var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);\n\n // NOTE: DOM access here\n // restores the original style properties after the offsets have been computed\n popperStyles.top = top;\n popperStyles.left = left;\n popperStyles[transformProp] = transform;\n\n options.boundaries = boundaries;\n\n var order = options.priority;\n var popper = data.offsets.popper;\n\n var check = {\n primary: function primary(placement) {\n var value = popper[placement];\n if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {\n value = Math.max(popper[placement], boundaries[placement]);\n }\n return defineProperty({}, placement, value);\n },\n secondary: function secondary(placement) {\n var mainSide = placement === 'right' ? 'left' : 'top';\n var value = popper[mainSide];\n if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {\n value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));\n }\n return defineProperty({}, mainSide, value);\n }\n };\n\n order.forEach(function (placement) {\n var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';\n popper = _extends({}, popper, check[side](placement));\n });\n\n data.offsets.popper = popper;\n\n return data;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction shift(data) {\n var placement = data.placement;\n var basePlacement = placement.split('-')[0];\n var shiftvariation = placement.split('-')[1];\n\n // if shift shiftvariation is specified, run the modifier\n if (shiftvariation) {\n var _data$offsets = data.offsets,\n reference = _data$offsets.reference,\n popper = _data$offsets.popper;\n\n var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;\n var side = isVertical ? 'left' : 'top';\n var measurement = isVertical ? 'width' : 'height';\n\n var shiftOffsets = {\n start: defineProperty({}, side, reference[side]),\n end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement])\n };\n\n data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);\n }\n\n return data;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by update method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction hide(data) {\n if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {\n return data;\n }\n\n var refRect = data.offsets.reference;\n var bound = find(data.instance.modifiers, function (modifier) {\n return modifier.name === 'preventOverflow';\n }).boundaries;\n\n if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {\n // Avoid unnecessary DOM access if visibility hasn't changed\n if (data.hide === true) {\n return data;\n }\n\n data.hide = true;\n data.attributes['x-out-of-boundaries'] = '';\n } else {\n // Avoid unnecessary DOM access if visibility hasn't changed\n if (data.hide === false) {\n return data;\n }\n\n data.hide = false;\n data.attributes['x-out-of-boundaries'] = false;\n }\n\n return data;\n}\n\n/**\n * @function\n * @memberof Modifiers\n * @argument {Object} data - The data object generated by `update` method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {Object} The data object, properly modified\n */\nfunction inner(data) {\n var placement = data.placement;\n var basePlacement = placement.split('-')[0];\n var _data$offsets = data.offsets,\n popper = _data$offsets.popper,\n reference = _data$offsets.reference;\n\n var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;\n\n var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;\n\n popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);\n\n data.placement = getOppositePlacement(placement);\n data.offsets.popper = getClientRect(popper);\n\n return data;\n}\n\n/**\n * Modifier function, each modifier can have a function of this type assigned\n * to its `fn` property.
\n * These functions will be called on each update, this means that you must\n * make sure they are performant enough to avoid performance bottlenecks.\n *\n * @function ModifierFn\n * @argument {dataObject} data - The data object generated by `update` method\n * @argument {Object} options - Modifiers configuration and options\n * @returns {dataObject} The data object, properly modified\n */\n\n/**\n * Modifiers are plugins used to alter the behavior of your poppers.
\n * Popper.js uses a set of 9 modifiers to provide all the basic functionalities\n * needed by the library.\n *\n * Usually you don't want to override the `order`, `fn` and `onLoad` props.\n * All the other properties are configurations that could be tweaked.\n * @namespace modifiers\n */\nvar modifiers = {\n /**\n * Modifier used to shift the popper on the start or end of its reference\n * element.
\n * It will read the variation of the `placement` property.
\n * It can be one either `-end` or `-start`.\n * @memberof modifiers\n * @inner\n */\n shift: {\n /** @prop {number} order=100 - Index used to define the order of execution */\n order: 100,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: shift\n },\n\n /**\n * The `offset` modifier can shift your popper on both its axis.\n *\n * It accepts the following units:\n * - `px` or unit-less, interpreted as pixels\n * - `%` or `%r`, percentage relative to the length of the reference element\n * - `%p`, percentage relative to the length of the popper element\n * - `vw`, CSS viewport width unit\n * - `vh`, CSS viewport height unit\n *\n * For length is intended the main axis relative to the placement of the popper.
\n * This means that if the placement is `top` or `bottom`, the length will be the\n * `width`. In case of `left` or `right`, it will be the `height`.\n *\n * You can provide a single value (as `Number` or `String`), or a pair of values\n * as `String` divided by a comma or one (or more) white spaces.
\n * The latter is a deprecated method because it leads to confusion and will be\n * removed in v2.
\n * Additionally, it accepts additions and subtractions between different units.\n * Note that multiplications and divisions aren't supported.\n *\n * Valid examples are:\n * ```\n * 10\n * '10%'\n * '10, 10'\n * '10%, 10'\n * '10 + 10%'\n * '10 - 5vh + 3%'\n * '-10px + 5vh, 5px - 6%'\n * ```\n * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap\n * > with their reference element, unfortunately, you will have to disable the `flip` modifier.\n * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).\n *\n * @memberof modifiers\n * @inner\n */\n offset: {\n /** @prop {number} order=200 - Index used to define the order of execution */\n order: 200,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: offset,\n /** @prop {Number|String} offset=0\n * The offset value as described in the modifier description\n */\n offset: 0\n },\n\n /**\n * Modifier used to prevent the popper from being positioned outside the boundary.\n *\n * A scenario exists where the reference itself is not within the boundaries.
\n * We can say it has \"escaped the boundaries\" — or just \"escaped\".
\n * In this case we need to decide whether the popper should either:\n *\n * - detach from the reference and remain \"trapped\" in the boundaries, or\n * - if it should ignore the boundary and \"escape with its reference\"\n *\n * When `escapeWithReference` is set to`true` and reference is completely\n * outside its boundaries, the popper will overflow (or completely leave)\n * the boundaries in order to remain attached to the edge of the reference.\n *\n * @memberof modifiers\n * @inner\n */\n preventOverflow: {\n /** @prop {number} order=300 - Index used to define the order of execution */\n order: 300,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: preventOverflow,\n /**\n * @prop {Array} [priority=['left','right','top','bottom']]\n * Popper will try to prevent overflow following these priorities by default,\n * then, it could overflow on the left and on top of the `boundariesElement`\n */\n priority: ['left', 'right', 'top', 'bottom'],\n /**\n * @prop {number} padding=5\n * Amount of pixel used to define a minimum distance between the boundaries\n * and the popper. This makes sure the popper always has a little padding\n * between the edges of its container\n */\n padding: 5,\n /**\n * @prop {String|HTMLElement} boundariesElement='scrollParent'\n * Boundaries used by the modifier. Can be `scrollParent`, `window`,\n * `viewport` or any DOM element.\n */\n boundariesElement: 'scrollParent'\n },\n\n /**\n * Modifier used to make sure the reference and its popper stay near each other\n * without leaving any gap between the two. Especially useful when the arrow is\n * enabled and you want to ensure that it points to its reference element.\n * It cares only about the first axis. You can still have poppers with margin\n * between the popper and its reference element.\n * @memberof modifiers\n * @inner\n */\n keepTogether: {\n /** @prop {number} order=400 - Index used to define the order of execution */\n order: 400,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: keepTogether\n },\n\n /**\n * This modifier is used to move the `arrowElement` of the popper to make\n * sure it is positioned between the reference element and its popper element.\n * It will read the outer size of the `arrowElement` node to detect how many\n * pixels of conjunction are needed.\n *\n * It has no effect if no `arrowElement` is provided.\n * @memberof modifiers\n * @inner\n */\n arrow: {\n /** @prop {number} order=500 - Index used to define the order of execution */\n order: 500,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: arrow,\n /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */\n element: '[x-arrow]'\n },\n\n /**\n * Modifier used to flip the popper's placement when it starts to overlap its\n * reference element.\n *\n * Requires the `preventOverflow` modifier before it in order to work.\n *\n * **NOTE:** this modifier will interrupt the current update cycle and will\n * restart it if it detects the need to flip the placement.\n * @memberof modifiers\n * @inner\n */\n flip: {\n /** @prop {number} order=600 - Index used to define the order of execution */\n order: 600,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: flip,\n /**\n * @prop {String|Array} behavior='flip'\n * The behavior used to change the popper's placement. It can be one of\n * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid\n * placements (with optional variations)\n */\n behavior: 'flip',\n /**\n * @prop {number} padding=5\n * The popper will flip if it hits the edges of the `boundariesElement`\n */\n padding: 5,\n /**\n * @prop {String|HTMLElement} boundariesElement='viewport'\n * The element which will define the boundaries of the popper position.\n * The popper will never be placed outside of the defined boundaries\n * (except if `keepTogether` is enabled)\n */\n boundariesElement: 'viewport',\n /**\n * @prop {Boolean} flipVariations=false\n * The popper will switch placement variation between `-start` and `-end` when\n * the reference element overlaps its boundaries.\n *\n * The original placement should have a set variation.\n */\n flipVariations: false,\n /**\n * @prop {Boolean} flipVariationsByContent=false\n * The popper will switch placement variation between `-start` and `-end` when\n * the popper element overlaps its reference boundaries.\n *\n * The original placement should have a set variation.\n */\n flipVariationsByContent: false\n },\n\n /**\n * Modifier used to make the popper flow toward the inner of the reference element.\n * By default, when this modifier is disabled, the popper will be placed outside\n * the reference element.\n * @memberof modifiers\n * @inner\n */\n inner: {\n /** @prop {number} order=700 - Index used to define the order of execution */\n order: 700,\n /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */\n enabled: false,\n /** @prop {ModifierFn} */\n fn: inner\n },\n\n /**\n * Modifier used to hide the popper when its reference element is outside of the\n * popper boundaries. It will set a `x-out-of-boundaries` attribute which can\n * be used to hide with a CSS selector the popper when its reference is\n * out of boundaries.\n *\n * Requires the `preventOverflow` modifier before it in order to work.\n * @memberof modifiers\n * @inner\n */\n hide: {\n /** @prop {number} order=800 - Index used to define the order of execution */\n order: 800,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: hide\n },\n\n /**\n * Computes the style that will be applied to the popper element to gets\n * properly positioned.\n *\n * Note that this modifier will not touch the DOM, it just prepares the styles\n * so that `applyStyle` modifier can apply it. This separation is useful\n * in case you need to replace `applyStyle` with a custom implementation.\n *\n * This modifier has `850` as `order` value to maintain backward compatibility\n * with previous versions of Popper.js. Expect the modifiers ordering method\n * to change in future major versions of the library.\n *\n * @memberof modifiers\n * @inner\n */\n computeStyle: {\n /** @prop {number} order=850 - Index used to define the order of execution */\n order: 850,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: computeStyle,\n /**\n * @prop {Boolean} gpuAcceleration=true\n * If true, it uses the CSS 3D transformation to position the popper.\n * Otherwise, it will use the `top` and `left` properties\n */\n gpuAcceleration: true,\n /**\n * @prop {string} [x='bottom']\n * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.\n * Change this if your popper should grow in a direction different from `bottom`\n */\n x: 'bottom',\n /**\n * @prop {string} [x='left']\n * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.\n * Change this if your popper should grow in a direction different from `right`\n */\n y: 'right'\n },\n\n /**\n * Applies the computed styles to the popper element.\n *\n * All the DOM manipulations are limited to this modifier. This is useful in case\n * you want to integrate Popper.js inside a framework or view library and you\n * want to delegate all the DOM manipulations to it.\n *\n * Note that if you disable this modifier, you must make sure the popper element\n * has its position set to `absolute` before Popper.js can do its work!\n *\n * Just disable this modifier and define your own to achieve the desired effect.\n *\n * @memberof modifiers\n * @inner\n */\n applyStyle: {\n /** @prop {number} order=900 - Index used to define the order of execution */\n order: 900,\n /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */\n enabled: true,\n /** @prop {ModifierFn} */\n fn: applyStyle,\n /** @prop {Function} */\n onLoad: applyStyleOnLoad,\n /**\n * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier\n * @prop {Boolean} gpuAcceleration=true\n * If true, it uses the CSS 3D transformation to position the popper.\n * Otherwise, it will use the `top` and `left` properties\n */\n gpuAcceleration: undefined\n }\n};\n\n/**\n * The `dataObject` is an object containing all the information used by Popper.js.\n * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.\n * @name dataObject\n * @property {Object} data.instance The Popper.js instance\n * @property {String} data.placement Placement applied to popper\n * @property {String} data.originalPlacement Placement originally defined on init\n * @property {Boolean} data.flipped True if popper has been flipped by flip modifier\n * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper\n * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier\n * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)\n * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)\n * @property {Object} data.boundaries Offsets of the popper boundaries\n * @property {Object} data.offsets The measurements of popper, reference and arrow elements\n * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values\n * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values\n * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0\n */\n\n/**\n * Default options provided to Popper.js constructor.
\n * These can be overridden using the `options` argument of Popper.js.
\n * To override an option, simply pass an object with the same\n * structure of the `options` object, as the 3rd argument. For example:\n * ```\n * new Popper(ref, pop, {\n * modifiers: {\n * preventOverflow: { enabled: false }\n * }\n * })\n * ```\n * @type {Object}\n * @static\n * @memberof Popper\n */\nvar Defaults = {\n /**\n * Popper's placement.\n * @prop {Popper.placements} placement='bottom'\n */\n placement: 'bottom',\n\n /**\n * Set this to true if you want popper to position it self in 'fixed' mode\n * @prop {Boolean} positionFixed=false\n */\n positionFixed: false,\n\n /**\n * Whether events (resize, scroll) are initially enabled.\n * @prop {Boolean} eventsEnabled=true\n */\n eventsEnabled: true,\n\n /**\n * Set to true if you want to automatically remove the popper when\n * you call the `destroy` method.\n * @prop {Boolean} removeOnDestroy=false\n */\n removeOnDestroy: false,\n\n /**\n * Callback called when the popper is created.
\n * By default, it is set to no-op.
\n * Access Popper.js instance with `data.instance`.\n * @prop {onCreate}\n */\n onCreate: function onCreate() {},\n\n /**\n * Callback called when the popper is updated. This callback is not called\n * on the initialization/creation of the popper, but only on subsequent\n * updates.
\n * By default, it is set to no-op.
\n * Access Popper.js instance with `data.instance`.\n * @prop {onUpdate}\n */\n onUpdate: function onUpdate() {},\n\n /**\n * List of modifiers used to modify the offsets before they are applied to the popper.\n * They provide most of the functionalities of Popper.js.\n * @prop {modifiers}\n */\n modifiers: modifiers\n};\n\n/**\n * @callback onCreate\n * @param {dataObject} data\n */\n\n/**\n * @callback onUpdate\n * @param {dataObject} data\n */\n\n// Utils\n// Methods\nvar Popper = function () {\n /**\n * Creates a new Popper.js instance.\n * @class Popper\n * @param {Element|referenceObject} reference - The reference element used to position the popper\n * @param {Element} popper - The HTML / XML element used as the popper\n * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)\n * @return {Object} instance - The generated Popper.js instance\n */\n function Popper(reference, popper) {\n var _this = this;\n\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n classCallCheck(this, Popper);\n\n this.scheduleUpdate = function () {\n return requestAnimationFrame(_this.update);\n };\n\n // make update() debounced, so that it only runs at most once-per-tick\n this.update = debounce(this.update.bind(this));\n\n // with {} we create a new object with the options inside it\n this.options = _extends({}, Popper.Defaults, options);\n\n // init state\n this.state = {\n isDestroyed: false,\n isCreated: false,\n scrollParents: []\n };\n\n // get reference and popper elements (allow jQuery wrappers)\n this.reference = reference && reference.jquery ? reference[0] : reference;\n this.popper = popper && popper.jquery ? popper[0] : popper;\n\n // Deep merge modifiers options\n this.options.modifiers = {};\n Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {\n _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});\n });\n\n // Refactoring modifiers' list (Object => Array)\n this.modifiers = Object.keys(this.options.modifiers).map(function (name) {\n return _extends({\n name: name\n }, _this.options.modifiers[name]);\n })\n // sort the modifiers by order\n .sort(function (a, b) {\n return a.order - b.order;\n });\n\n // modifiers have the ability to execute arbitrary code when Popper.js get inited\n // such code is executed in the same order of its modifier\n // they could add new properties to their options configuration\n // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!\n this.modifiers.forEach(function (modifierOptions) {\n if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {\n modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);\n }\n });\n\n // fire the first update to position the popper in the right place\n this.update();\n\n var eventsEnabled = this.options.eventsEnabled;\n if (eventsEnabled) {\n // setup event listeners, they will take care of update the position in specific situations\n this.enableEventListeners();\n }\n\n this.state.eventsEnabled = eventsEnabled;\n }\n\n // We can't use class properties because they don't get listed in the\n // class prototype and break stuff like Sinon stubs\n\n\n createClass(Popper, [{\n key: 'update',\n value: function update$$1() {\n return update.call(this);\n }\n }, {\n key: 'destroy',\n value: function destroy$$1() {\n return destroy.call(this);\n }\n }, {\n key: 'enableEventListeners',\n value: function enableEventListeners$$1() {\n return enableEventListeners.call(this);\n }\n }, {\n key: 'disableEventListeners',\n value: function disableEventListeners$$1() {\n return disableEventListeners.call(this);\n }\n\n /**\n * Schedules an update. It will run on the next UI update available.\n * @method scheduleUpdate\n * @memberof Popper\n */\n\n\n /**\n * Collection of utilities useful when writing custom modifiers.\n * Starting from version 1.7, this method is available only if you\n * include `popper-utils.js` before `popper.js`.\n *\n * **DEPRECATION**: This way to access PopperUtils is deprecated\n * and will be removed in v2! Use the PopperUtils module directly instead.\n * Due to the high instability of the methods contained in Utils, we can't\n * guarantee them to follow semver. Use them at your own risk!\n * @static\n * @private\n * @type {Object}\n * @deprecated since version 1.8\n * @member Utils\n * @memberof Popper\n */\n\n }]);\n return Popper;\n}();\n\n/**\n * The `referenceObject` is an object that provides an interface compatible with Popper.js\n * and lets you use it as replacement of a real DOM node.
\n * You can use this method to position a popper relatively to a set of coordinates\n * in case you don't have a DOM node to use as reference.\n *\n * ```\n * new Popper(referenceObject, popperNode);\n * ```\n *\n * NB: This feature isn't supported in Internet Explorer 10.\n * @name referenceObject\n * @property {Function} data.getBoundingClientRect\n * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.\n * @property {number} data.clientWidth\n * An ES6 getter that will return the width of the virtual reference element.\n * @property {number} data.clientHeight\n * An ES6 getter that will return the height of the virtual reference element.\n */\n\n\nPopper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;\nPopper.placements = placements;\nPopper.Defaults = Defaults;\n\nexport default Popper;\n//# sourceMappingURL=popper.js.map\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): dropdown.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Popper from 'popper.js'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'dropdown'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.dropdown'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\nconst ESCAPE_KEYCODE = 27 // KeyboardEvent.which value for Escape (Esc) key\nconst SPACE_KEYCODE = 32 // KeyboardEvent.which value for space key\nconst TAB_KEYCODE = 9 // KeyboardEvent.which value for tab key\nconst ARROW_UP_KEYCODE = 38 // KeyboardEvent.which value for up arrow key\nconst ARROW_DOWN_KEYCODE = 40 // KeyboardEvent.which value for down arrow key\nconst RIGHT_MOUSE_BUTTON_WHICH = 3 // MouseEvent.which value for the right button (assuming a right-handed mouse)\nconst REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEYCODE}|${ARROW_DOWN_KEYCODE}|${ESCAPE_KEYCODE}`)\n\nconst EVENT_HIDE = `hide${EVENT_KEY}`\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`\nconst EVENT_SHOW = `show${EVENT_KEY}`\nconst EVENT_SHOWN = `shown${EVENT_KEY}`\nconst EVENT_CLICK = `click${EVENT_KEY}`\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\nconst EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY}${DATA_API_KEY}`\nconst EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_DISABLED = 'disabled'\nconst CLASS_NAME_SHOW = 'show'\nconst CLASS_NAME_DROPUP = 'dropup'\nconst CLASS_NAME_DROPRIGHT = 'dropright'\nconst CLASS_NAME_DROPLEFT = 'dropleft'\nconst CLASS_NAME_MENURIGHT = 'dropdown-menu-right'\nconst CLASS_NAME_POSITION_STATIC = 'position-static'\n\nconst SELECTOR_DATA_TOGGLE = '[data-toggle=\"dropdown\"]'\nconst SELECTOR_FORM_CHILD = '.dropdown form'\nconst SELECTOR_MENU = '.dropdown-menu'\nconst SELECTOR_NAVBAR_NAV = '.navbar-nav'\nconst SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'\n\nconst PLACEMENT_TOP = 'top-start'\nconst PLACEMENT_TOPEND = 'top-end'\nconst PLACEMENT_BOTTOM = 'bottom-start'\nconst PLACEMENT_BOTTOMEND = 'bottom-end'\nconst PLACEMENT_RIGHT = 'right-start'\nconst PLACEMENT_LEFT = 'left-start'\n\nconst Default = {\n offset: 0,\n flip: true,\n boundary: 'scrollParent',\n reference: 'toggle',\n display: 'dynamic',\n popperConfig: null\n}\n\nconst DefaultType = {\n offset: '(number|string|function)',\n flip: 'boolean',\n boundary: '(string|element)',\n reference: '(string|element)',\n display: 'string',\n popperConfig: '(null|object)'\n}\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Dropdown {\n constructor(element, config) {\n this._element = element\n this._popper = null\n this._config = this._getConfig(config)\n this._menu = this._getMenuElement()\n this._inNavbar = this._detectNavbar()\n\n this._addEventListeners()\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n static get DefaultType() {\n return DefaultType\n }\n\n // Public\n\n toggle() {\n if (this._element.disabled || $(this._element).hasClass(CLASS_NAME_DISABLED)) {\n return\n }\n\n const isActive = $(this._menu).hasClass(CLASS_NAME_SHOW)\n\n Dropdown._clearMenus()\n\n if (isActive) {\n return\n }\n\n this.show(true)\n }\n\n show(usePopper = false) {\n if (this._element.disabled || $(this._element).hasClass(CLASS_NAME_DISABLED) || $(this._menu).hasClass(CLASS_NAME_SHOW)) {\n return\n }\n\n const relatedTarget = {\n relatedTarget: this._element\n }\n const showEvent = $.Event(EVENT_SHOW, relatedTarget)\n const parent = Dropdown._getParentFromElement(this._element)\n\n $(parent).trigger(showEvent)\n\n if (showEvent.isDefaultPrevented()) {\n return\n }\n\n // Totally disable Popper for Dropdowns in Navbar\n if (!this._inNavbar && usePopper) {\n /**\n * Check for Popper dependency\n * Popper - https://popper.js.org\n */\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s dropdowns require Popper (https://popper.js.org)')\n }\n\n let referenceElement = this._element\n\n if (this._config.reference === 'parent') {\n referenceElement = parent\n } else if (Util.isElement(this._config.reference)) {\n referenceElement = this._config.reference\n\n // Check if it's jQuery element\n if (typeof this._config.reference.jquery !== 'undefined') {\n referenceElement = this._config.reference[0]\n }\n }\n\n // If boundary is not `scrollParent`, then set position to `static`\n // to allow the menu to \"escape\" the scroll parent's boundaries\n // https://github.com/twbs/bootstrap/issues/24251\n if (this._config.boundary !== 'scrollParent') {\n $(parent).addClass(CLASS_NAME_POSITION_STATIC)\n }\n\n this._popper = new Popper(referenceElement, this._menu, this._getPopperConfig())\n }\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement &&\n $(parent).closest(SELECTOR_NAVBAR_NAV).length === 0) {\n $(document.body).children().on('mouseover', null, $.noop)\n }\n\n this._element.focus()\n this._element.setAttribute('aria-expanded', true)\n\n $(this._menu).toggleClass(CLASS_NAME_SHOW)\n $(parent)\n .toggleClass(CLASS_NAME_SHOW)\n .trigger($.Event(EVENT_SHOWN, relatedTarget))\n }\n\n hide() {\n if (this._element.disabled || $(this._element).hasClass(CLASS_NAME_DISABLED) || !$(this._menu).hasClass(CLASS_NAME_SHOW)) {\n return\n }\n\n const relatedTarget = {\n relatedTarget: this._element\n }\n const hideEvent = $.Event(EVENT_HIDE, relatedTarget)\n const parent = Dropdown._getParentFromElement(this._element)\n\n $(parent).trigger(hideEvent)\n\n if (hideEvent.isDefaultPrevented()) {\n return\n }\n\n if (this._popper) {\n this._popper.destroy()\n }\n\n $(this._menu).toggleClass(CLASS_NAME_SHOW)\n $(parent)\n .toggleClass(CLASS_NAME_SHOW)\n .trigger($.Event(EVENT_HIDDEN, relatedTarget))\n }\n\n dispose() {\n $.removeData(this._element, DATA_KEY)\n $(this._element).off(EVENT_KEY)\n this._element = null\n this._menu = null\n if (this._popper !== null) {\n this._popper.destroy()\n this._popper = null\n }\n }\n\n update() {\n this._inNavbar = this._detectNavbar()\n if (this._popper !== null) {\n this._popper.scheduleUpdate()\n }\n }\n\n // Private\n\n _addEventListeners() {\n $(this._element).on(EVENT_CLICK, event => {\n event.preventDefault()\n event.stopPropagation()\n this.toggle()\n })\n }\n\n _getConfig(config) {\n config = {\n ...this.constructor.Default,\n ...$(this._element).data(),\n ...config\n }\n\n Util.typeCheckConfig(\n NAME,\n config,\n this.constructor.DefaultType\n )\n\n return config\n }\n\n _getMenuElement() {\n if (!this._menu) {\n const parent = Dropdown._getParentFromElement(this._element)\n\n if (parent) {\n this._menu = parent.querySelector(SELECTOR_MENU)\n }\n }\n\n return this._menu\n }\n\n _getPlacement() {\n const $parentDropdown = $(this._element.parentNode)\n let placement = PLACEMENT_BOTTOM\n\n // Handle dropup\n if ($parentDropdown.hasClass(CLASS_NAME_DROPUP)) {\n placement = $(this._menu).hasClass(CLASS_NAME_MENURIGHT) ?\n PLACEMENT_TOPEND :\n PLACEMENT_TOP\n } else if ($parentDropdown.hasClass(CLASS_NAME_DROPRIGHT)) {\n placement = PLACEMENT_RIGHT\n } else if ($parentDropdown.hasClass(CLASS_NAME_DROPLEFT)) {\n placement = PLACEMENT_LEFT\n } else if ($(this._menu).hasClass(CLASS_NAME_MENURIGHT)) {\n placement = PLACEMENT_BOTTOMEND\n }\n\n return placement\n }\n\n _detectNavbar() {\n return $(this._element).closest('.navbar').length > 0\n }\n\n _getOffset() {\n const offset = {}\n\n if (typeof this._config.offset === 'function') {\n offset.fn = data => {\n data.offsets = {\n ...data.offsets,\n ...(this._config.offset(data.offsets, this._element) || {})\n }\n\n return data\n }\n } else {\n offset.offset = this._config.offset\n }\n\n return offset\n }\n\n _getPopperConfig() {\n const popperConfig = {\n placement: this._getPlacement(),\n modifiers: {\n offset: this._getOffset(),\n flip: {\n enabled: this._config.flip\n },\n preventOverflow: {\n boundariesElement: this._config.boundary\n }\n }\n }\n\n // Disable Popper if we have a static display\n if (this._config.display === 'static') {\n popperConfig.modifiers.applyStyle = {\n enabled: false\n }\n }\n\n return {\n ...popperConfig,\n ...this._config.popperConfig\n }\n }\n\n // Static\n\n static _jQueryInterface(config) {\n return this.each(function () {\n let data = $(this).data(DATA_KEY)\n const _config = typeof config === 'object' ? config : null\n\n if (!data) {\n data = new Dropdown(this, _config)\n $(this).data(DATA_KEY, data)\n }\n\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`)\n }\n\n data[config]()\n }\n })\n }\n\n static _clearMenus(event) {\n if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||\n event.type === 'keyup' && event.which !== TAB_KEYCODE)) {\n return\n }\n\n const toggles = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE))\n\n for (let i = 0, len = toggles.length; i < len; i++) {\n const parent = Dropdown._getParentFromElement(toggles[i])\n const context = $(toggles[i]).data(DATA_KEY)\n const relatedTarget = {\n relatedTarget: toggles[i]\n }\n\n if (event && event.type === 'click') {\n relatedTarget.clickEvent = event\n }\n\n if (!context) {\n continue\n }\n\n const dropdownMenu = context._menu\n if (!$(parent).hasClass(CLASS_NAME_SHOW)) {\n continue\n }\n\n if (event && (event.type === 'click' &&\n /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) &&\n $.contains(parent, event.target)) {\n continue\n }\n\n const hideEvent = $.Event(EVENT_HIDE, relatedTarget)\n $(parent).trigger(hideEvent)\n if (hideEvent.isDefaultPrevented()) {\n continue\n }\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n $(document.body).children().off('mouseover', null, $.noop)\n }\n\n toggles[i].setAttribute('aria-expanded', 'false')\n\n if (context._popper) {\n context._popper.destroy()\n }\n\n $(dropdownMenu).removeClass(CLASS_NAME_SHOW)\n $(parent)\n .removeClass(CLASS_NAME_SHOW)\n .trigger($.Event(EVENT_HIDDEN, relatedTarget))\n }\n }\n\n static _getParentFromElement(element) {\n let parent\n const selector = Util.getSelectorFromElement(element)\n\n if (selector) {\n parent = document.querySelector(selector)\n }\n\n return parent || element.parentNode\n }\n\n // eslint-disable-next-line complexity\n static _dataApiKeydownHandler(event) {\n // If not input/textarea:\n // - And not a key in REGEXP_KEYDOWN => not a dropdown command\n // If input/textarea:\n // - If space key => not a dropdown command\n // - If key is other than escape\n // - If key is not up or down => not a dropdown command\n // - If trigger inside the menu => not a dropdown command\n if (/input|textarea/i.test(event.target.tagName) ?\n event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE &&\n (event.which !== ARROW_DOWN_KEYCODE && event.which !== ARROW_UP_KEYCODE ||\n $(event.target).closest(SELECTOR_MENU).length) : !REGEXP_KEYDOWN.test(event.which)) {\n return\n }\n\n if (this.disabled || $(this).hasClass(CLASS_NAME_DISABLED)) {\n return\n }\n\n const parent = Dropdown._getParentFromElement(this)\n const isActive = $(parent).hasClass(CLASS_NAME_SHOW)\n\n if (!isActive && event.which === ESCAPE_KEYCODE) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (!isActive || (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {\n if (event.which === ESCAPE_KEYCODE) {\n $(parent.querySelector(SELECTOR_DATA_TOGGLE)).trigger('focus')\n }\n\n $(this).trigger('click')\n return\n }\n\n const items = [].slice.call(parent.querySelectorAll(SELECTOR_VISIBLE_ITEMS))\n .filter(item => $(item).is(':visible'))\n\n if (items.length === 0) {\n return\n }\n\n let index = items.indexOf(event.target)\n\n if (event.which === ARROW_UP_KEYCODE && index > 0) { // Up\n index--\n }\n\n if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // Down\n index++\n }\n\n if (index < 0) {\n index = 0\n }\n\n items[index].focus()\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document)\n .on(EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE, Dropdown._dataApiKeydownHandler)\n .on(EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown._dataApiKeydownHandler)\n .on(`${EVENT_CLICK_DATA_API} ${EVENT_KEYUP_DATA_API}`, Dropdown._clearMenus)\n .on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {\n event.preventDefault()\n event.stopPropagation()\n Dropdown._jQueryInterface.call($(this), 'toggle')\n })\n .on(EVENT_CLICK_DATA_API, SELECTOR_FORM_CHILD, e => {\n e.stopPropagation()\n })\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Dropdown._jQueryInterface\n$.fn[NAME].Constructor = Dropdown\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Dropdown._jQueryInterface\n}\n\nexport default Dropdown\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): modal.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'modal'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.modal'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\nconst ESCAPE_KEYCODE = 27 // KeyboardEvent.which value for Escape (Esc) key\n\nconst Default = {\n backdrop: true,\n keyboard: true,\n focus: true,\n show: true\n}\n\nconst DefaultType = {\n backdrop: '(boolean|string)',\n keyboard: 'boolean',\n focus: 'boolean',\n show: 'boolean'\n}\n\nconst EVENT_HIDE = `hide${EVENT_KEY}`\nconst EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY}`\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`\nconst EVENT_SHOW = `show${EVENT_KEY}`\nconst EVENT_SHOWN = `shown${EVENT_KEY}`\nconst EVENT_FOCUSIN = `focusin${EVENT_KEY}`\nconst EVENT_RESIZE = `resize${EVENT_KEY}`\nconst EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY}`\nconst EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`\nconst EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY}`\nconst EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY}`\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_SCROLLABLE = 'modal-dialog-scrollable'\nconst CLASS_NAME_SCROLLBAR_MEASURER = 'modal-scrollbar-measure'\nconst CLASS_NAME_BACKDROP = 'modal-backdrop'\nconst CLASS_NAME_OPEN = 'modal-open'\nconst CLASS_NAME_FADE = 'fade'\nconst CLASS_NAME_SHOW = 'show'\nconst CLASS_NAME_STATIC = 'modal-static'\n\nconst SELECTOR_DIALOG = '.modal-dialog'\nconst SELECTOR_MODAL_BODY = '.modal-body'\nconst SELECTOR_DATA_TOGGLE = '[data-toggle=\"modal\"]'\nconst SELECTOR_DATA_DISMISS = '[data-dismiss=\"modal\"]'\nconst SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'\nconst SELECTOR_STICKY_CONTENT = '.sticky-top'\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Modal {\n constructor(element, config) {\n this._config = this._getConfig(config)\n this._element = element\n this._dialog = element.querySelector(SELECTOR_DIALOG)\n this._backdrop = null\n this._isShown = false\n this._isBodyOverflowing = false\n this._ignoreBackdropClick = false\n this._isTransitioning = false\n this._scrollbarWidth = 0\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n // Public\n\n toggle(relatedTarget) {\n return this._isShown ? this.hide() : this.show(relatedTarget)\n }\n\n show(relatedTarget) {\n if (this._isShown || this._isTransitioning) {\n return\n }\n\n if ($(this._element).hasClass(CLASS_NAME_FADE)) {\n this._isTransitioning = true\n }\n\n const showEvent = $.Event(EVENT_SHOW, {\n relatedTarget\n })\n\n $(this._element).trigger(showEvent)\n\n if (this._isShown || showEvent.isDefaultPrevented()) {\n return\n }\n\n this._isShown = true\n\n this._checkScrollbar()\n this._setScrollbar()\n\n this._adjustDialog()\n\n this._setEscapeEvent()\n this._setResizeEvent()\n\n $(this._element).on(\n EVENT_CLICK_DISMISS,\n SELECTOR_DATA_DISMISS,\n event => this.hide(event)\n )\n\n $(this._dialog).on(EVENT_MOUSEDOWN_DISMISS, () => {\n $(this._element).one(EVENT_MOUSEUP_DISMISS, event => {\n if ($(event.target).is(this._element)) {\n this._ignoreBackdropClick = true\n }\n })\n })\n\n this._showBackdrop(() => this._showElement(relatedTarget))\n }\n\n hide(event) {\n if (event) {\n event.preventDefault()\n }\n\n if (!this._isShown || this._isTransitioning) {\n return\n }\n\n const hideEvent = $.Event(EVENT_HIDE)\n\n $(this._element).trigger(hideEvent)\n\n if (!this._isShown || hideEvent.isDefaultPrevented()) {\n return\n }\n\n this._isShown = false\n const transition = $(this._element).hasClass(CLASS_NAME_FADE)\n\n if (transition) {\n this._isTransitioning = true\n }\n\n this._setEscapeEvent()\n this._setResizeEvent()\n\n $(document).off(EVENT_FOCUSIN)\n\n $(this._element).removeClass(CLASS_NAME_SHOW)\n\n $(this._element).off(EVENT_CLICK_DISMISS)\n $(this._dialog).off(EVENT_MOUSEDOWN_DISMISS)\n\n if (transition) {\n const transitionDuration = Util.getTransitionDurationFromElement(this._element)\n\n $(this._element)\n .one(Util.TRANSITION_END, event => this._hideModal(event))\n .emulateTransitionEnd(transitionDuration)\n } else {\n this._hideModal()\n }\n }\n\n dispose() {\n [window, this._element, this._dialog]\n .forEach(htmlElement => $(htmlElement).off(EVENT_KEY))\n\n /**\n * `document` has 2 events `EVENT_FOCUSIN` and `EVENT_CLICK_DATA_API`\n * Do not move `document` in `htmlElements` array\n * It will remove `EVENT_CLICK_DATA_API` event that should remain\n */\n $(document).off(EVENT_FOCUSIN)\n\n $.removeData(this._element, DATA_KEY)\n\n this._config = null\n this._element = null\n this._dialog = null\n this._backdrop = null\n this._isShown = null\n this._isBodyOverflowing = null\n this._ignoreBackdropClick = null\n this._isTransitioning = null\n this._scrollbarWidth = null\n }\n\n handleUpdate() {\n this._adjustDialog()\n }\n\n // Private\n\n _getConfig(config) {\n config = {\n ...Default,\n ...config\n }\n Util.typeCheckConfig(NAME, config, DefaultType)\n return config\n }\n\n _triggerBackdropTransition() {\n const hideEventPrevented = $.Event(EVENT_HIDE_PREVENTED)\n\n $(this._element).trigger(hideEventPrevented)\n if (hideEventPrevented.isDefaultPrevented()) {\n return\n }\n\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight\n\n if (!isModalOverflowing) {\n this._element.style.overflowY = 'hidden'\n }\n\n this._element.classList.add(CLASS_NAME_STATIC)\n\n const modalTransitionDuration = Util.getTransitionDurationFromElement(this._dialog)\n $(this._element).off(Util.TRANSITION_END)\n\n $(this._element).one(Util.TRANSITION_END, () => {\n this._element.classList.remove(CLASS_NAME_STATIC)\n if (!isModalOverflowing) {\n $(this._element).one(Util.TRANSITION_END, () => {\n this._element.style.overflowY = ''\n })\n .emulateTransitionEnd(this._element, modalTransitionDuration)\n }\n })\n .emulateTransitionEnd(modalTransitionDuration)\n this._element.focus()\n }\n\n _showElement(relatedTarget) {\n const transition = $(this._element).hasClass(CLASS_NAME_FADE)\n const modalBody = this._dialog ? this._dialog.querySelector(SELECTOR_MODAL_BODY) : null\n\n if (!this._element.parentNode ||\n this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {\n // Don't move modal's DOM position\n document.body.appendChild(this._element)\n }\n\n this._element.style.display = 'block'\n this._element.removeAttribute('aria-hidden')\n this._element.setAttribute('aria-modal', true)\n this._element.setAttribute('role', 'dialog')\n\n if ($(this._dialog).hasClass(CLASS_NAME_SCROLLABLE) && modalBody) {\n modalBody.scrollTop = 0\n } else {\n this._element.scrollTop = 0\n }\n\n if (transition) {\n Util.reflow(this._element)\n }\n\n $(this._element).addClass(CLASS_NAME_SHOW)\n\n if (this._config.focus) {\n this._enforceFocus()\n }\n\n const shownEvent = $.Event(EVENT_SHOWN, {\n relatedTarget\n })\n\n const transitionComplete = () => {\n if (this._config.focus) {\n this._element.focus()\n }\n\n this._isTransitioning = false\n $(this._element).trigger(shownEvent)\n }\n\n if (transition) {\n const transitionDuration = Util.getTransitionDurationFromElement(this._dialog)\n\n $(this._dialog)\n .one(Util.TRANSITION_END, transitionComplete)\n .emulateTransitionEnd(transitionDuration)\n } else {\n transitionComplete()\n }\n }\n\n _enforceFocus() {\n $(document)\n .off(EVENT_FOCUSIN) // Guard against infinite focus loop\n .on(EVENT_FOCUSIN, event => {\n if (document !== event.target &&\n this._element !== event.target &&\n $(this._element).has(event.target).length === 0) {\n this._element.focus()\n }\n })\n }\n\n _setEscapeEvent() {\n if (this._isShown) {\n $(this._element).on(EVENT_KEYDOWN_DISMISS, event => {\n if (this._config.keyboard && event.which === ESCAPE_KEYCODE) {\n event.preventDefault()\n this.hide()\n } else if (!this._config.keyboard && event.which === ESCAPE_KEYCODE) {\n this._triggerBackdropTransition()\n }\n })\n } else if (!this._isShown) {\n $(this._element).off(EVENT_KEYDOWN_DISMISS)\n }\n }\n\n _setResizeEvent() {\n if (this._isShown) {\n $(window).on(EVENT_RESIZE, event => this.handleUpdate(event))\n } else {\n $(window).off(EVENT_RESIZE)\n }\n }\n\n _hideModal() {\n this._element.style.display = 'none'\n this._element.setAttribute('aria-hidden', true)\n this._element.removeAttribute('aria-modal')\n this._element.removeAttribute('role')\n this._isTransitioning = false\n this._showBackdrop(() => {\n $(document.body).removeClass(CLASS_NAME_OPEN)\n this._resetAdjustments()\n this._resetScrollbar()\n $(this._element).trigger(EVENT_HIDDEN)\n })\n }\n\n _removeBackdrop() {\n if (this._backdrop) {\n $(this._backdrop).remove()\n this._backdrop = null\n }\n }\n\n _showBackdrop(callback) {\n const animate = $(this._element).hasClass(CLASS_NAME_FADE) ?\n CLASS_NAME_FADE : ''\n\n if (this._isShown && this._config.backdrop) {\n this._backdrop = document.createElement('div')\n this._backdrop.className = CLASS_NAME_BACKDROP\n\n if (animate) {\n this._backdrop.classList.add(animate)\n }\n\n $(this._backdrop).appendTo(document.body)\n\n $(this._element).on(EVENT_CLICK_DISMISS, event => {\n if (this._ignoreBackdropClick) {\n this._ignoreBackdropClick = false\n return\n }\n\n if (event.target !== event.currentTarget) {\n return\n }\n\n if (this._config.backdrop === 'static') {\n this._triggerBackdropTransition()\n } else {\n this.hide()\n }\n })\n\n if (animate) {\n Util.reflow(this._backdrop)\n }\n\n $(this._backdrop).addClass(CLASS_NAME_SHOW)\n\n if (!callback) {\n return\n }\n\n if (!animate) {\n callback()\n return\n }\n\n const backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop)\n\n $(this._backdrop)\n .one(Util.TRANSITION_END, callback)\n .emulateTransitionEnd(backdropTransitionDuration)\n } else if (!this._isShown && this._backdrop) {\n $(this._backdrop).removeClass(CLASS_NAME_SHOW)\n\n const callbackRemove = () => {\n this._removeBackdrop()\n if (callback) {\n callback()\n }\n }\n\n if ($(this._element).hasClass(CLASS_NAME_FADE)) {\n const backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop)\n\n $(this._backdrop)\n .one(Util.TRANSITION_END, callbackRemove)\n .emulateTransitionEnd(backdropTransitionDuration)\n } else {\n callbackRemove()\n }\n } else if (callback) {\n callback()\n }\n }\n\n // ----------------------------------------------------------------------\n // the following methods are used to handle overflowing modals\n // todo (fat): these should probably be refactored out of modal.js\n // ----------------------------------------------------------------------\n\n _adjustDialog() {\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight\n\n if (!this._isBodyOverflowing && isModalOverflowing) {\n this._element.style.paddingLeft = `${this._scrollbarWidth}px`\n }\n\n if (this._isBodyOverflowing && !isModalOverflowing) {\n this._element.style.paddingRight = `${this._scrollbarWidth}px`\n }\n }\n\n _resetAdjustments() {\n this._element.style.paddingLeft = ''\n this._element.style.paddingRight = ''\n }\n\n _checkScrollbar() {\n const rect = document.body.getBoundingClientRect()\n this._isBodyOverflowing = Math.round(rect.left + rect.right) < window.innerWidth\n this._scrollbarWidth = this._getScrollbarWidth()\n }\n\n _setScrollbar() {\n if (this._isBodyOverflowing) {\n // Note: DOMNode.style.paddingRight returns the actual value or '' if not set\n // while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set\n const fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT))\n const stickyContent = [].slice.call(document.querySelectorAll(SELECTOR_STICKY_CONTENT))\n\n // Adjust fixed content padding\n $(fixedContent).each((index, element) => {\n const actualPadding = element.style.paddingRight\n const calculatedPadding = $(element).css('padding-right')\n $(element)\n .data('padding-right', actualPadding)\n .css('padding-right', `${parseFloat(calculatedPadding) + this._scrollbarWidth}px`)\n })\n\n // Adjust sticky content margin\n $(stickyContent).each((index, element) => {\n const actualMargin = element.style.marginRight\n const calculatedMargin = $(element).css('margin-right')\n $(element)\n .data('margin-right', actualMargin)\n .css('margin-right', `${parseFloat(calculatedMargin) - this._scrollbarWidth}px`)\n })\n\n // Adjust body padding\n const actualPadding = document.body.style.paddingRight\n const calculatedPadding = $(document.body).css('padding-right')\n $(document.body)\n .data('padding-right', actualPadding)\n .css('padding-right', `${parseFloat(calculatedPadding) + this._scrollbarWidth}px`)\n }\n\n $(document.body).addClass(CLASS_NAME_OPEN)\n }\n\n _resetScrollbar() {\n // Restore fixed content padding\n const fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT))\n $(fixedContent).each((index, element) => {\n const padding = $(element).data('padding-right')\n $(element).removeData('padding-right')\n element.style.paddingRight = padding ? padding : ''\n })\n\n // Restore sticky content\n const elements = [].slice.call(document.querySelectorAll(`${SELECTOR_STICKY_CONTENT}`))\n $(elements).each((index, element) => {\n const margin = $(element).data('margin-right')\n if (typeof margin !== 'undefined') {\n $(element).css('margin-right', margin).removeData('margin-right')\n }\n })\n\n // Restore body padding\n const padding = $(document.body).data('padding-right')\n $(document.body).removeData('padding-right')\n document.body.style.paddingRight = padding ? padding : ''\n }\n\n _getScrollbarWidth() { // thx d.walsh\n const scrollDiv = document.createElement('div')\n scrollDiv.className = CLASS_NAME_SCROLLBAR_MEASURER\n document.body.appendChild(scrollDiv)\n const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth\n document.body.removeChild(scrollDiv)\n return scrollbarWidth\n }\n\n // Static\n\n static _jQueryInterface(config, relatedTarget) {\n return this.each(function () {\n let data = $(this).data(DATA_KEY)\n const _config = {\n ...Default,\n ...$(this).data(),\n ...(typeof config === 'object' && config ? config : {})\n }\n\n if (!data) {\n data = new Modal(this, _config)\n $(this).data(DATA_KEY, data)\n }\n\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`)\n }\n\n data[config](relatedTarget)\n } else if (_config.show) {\n data.show(relatedTarget)\n }\n })\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * Data Api implementation\n * ------------------------------------------------------------------------\n */\n\n$(document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {\n let target\n const selector = Util.getSelectorFromElement(this)\n\n if (selector) {\n target = document.querySelector(selector)\n }\n\n const config = $(target).data(DATA_KEY) ?\n 'toggle' : {\n ...$(target).data(),\n ...$(this).data()\n }\n\n if (this.tagName === 'A' || this.tagName === 'AREA') {\n event.preventDefault()\n }\n\n const $target = $(target).one(EVENT_SHOW, showEvent => {\n if (showEvent.isDefaultPrevented()) {\n // Only register focus restorer if modal will actually get shown\n return\n }\n\n $target.one(EVENT_HIDDEN, () => {\n if ($(this).is(':visible')) {\n this.focus()\n }\n })\n })\n\n Modal._jQueryInterface.call($(target), config, this)\n})\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Modal._jQueryInterface\n$.fn[NAME].Constructor = Modal\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Modal._jQueryInterface\n}\n\nexport default Modal\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): tools/sanitizer.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst uriAttrs = [\n 'background',\n 'cite',\n 'href',\n 'itemtype',\n 'longdesc',\n 'poster',\n 'src',\n 'xlink:href'\n]\n\nconst ARIA_ATTRIBUTE_PATTERN = /^aria-[\\w-]*$/i\n\nexport const DefaultWhitelist = {\n // Global attributes allowed on any supplied element below.\n '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],\n a: ['target', 'href', 'title', 'rel'],\n area: [],\n b: [],\n br: [],\n col: [],\n code: [],\n div: [],\n em: [],\n hr: [],\n h1: [],\n h2: [],\n h3: [],\n h4: [],\n h5: [],\n h6: [],\n i: [],\n img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],\n li: [],\n ol: [],\n p: [],\n pre: [],\n s: [],\n small: [],\n span: [],\n sub: [],\n sup: [],\n strong: [],\n u: [],\n ul: []\n}\n\n/**\n * A pattern that recognizes a commonly useful subset of URLs that are safe.\n *\n * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts\n */\nconst SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^#&/:?]*(?:[#/?]|$))/gi\n\n/**\n * A pattern that matches safe data URLs. Only matches image, video and audio types.\n *\n * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts\n */\nconst DATA_URL_PATTERN = /^data:(?:image\\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\\/(?:mpeg|mp4|ogg|webm)|audio\\/(?:mp3|oga|ogg|opus));base64,[\\d+/a-z]+=*$/i\n\nfunction allowedAttribute(attr, allowedAttributeList) {\n const attrName = attr.nodeName.toLowerCase()\n\n if (allowedAttributeList.indexOf(attrName) !== -1) {\n if (uriAttrs.indexOf(attrName) !== -1) {\n return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))\n }\n\n return true\n }\n\n const regExp = allowedAttributeList.filter(attrRegex => attrRegex instanceof RegExp)\n\n // Check if a regular expression validates the attribute.\n for (let i = 0, len = regExp.length; i < len; i++) {\n if (attrName.match(regExp[i])) {\n return true\n }\n }\n\n return false\n}\n\nexport function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) {\n if (unsafeHtml.length === 0) {\n return unsafeHtml\n }\n\n if (sanitizeFn && typeof sanitizeFn === 'function') {\n return sanitizeFn(unsafeHtml)\n }\n\n const domParser = new window.DOMParser()\n const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html')\n const whitelistKeys = Object.keys(whiteList)\n const elements = [].slice.call(createdDocument.body.querySelectorAll('*'))\n\n for (let i = 0, len = elements.length; i < len; i++) {\n const el = elements[i]\n const elName = el.nodeName.toLowerCase()\n\n if (whitelistKeys.indexOf(el.nodeName.toLowerCase()) === -1) {\n el.parentNode.removeChild(el)\n\n continue\n }\n\n const attributeList = [].slice.call(el.attributes)\n const whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || [])\n\n attributeList.forEach(attr => {\n if (!allowedAttribute(attr, whitelistedAttributes)) {\n el.removeAttribute(attr.nodeName)\n }\n })\n }\n\n return createdDocument.body.innerHTML\n}\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): tooltip.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport {\n DefaultWhitelist,\n sanitizeHtml\n} from './tools/sanitizer'\nimport $ from 'jquery'\nimport Popper from 'popper.js'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'tooltip'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.tooltip'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\nconst CLASS_PREFIX = 'bs-tooltip'\nconst BSCLS_PREFIX_REGEX = new RegExp(`(^|\\\\s)${CLASS_PREFIX}\\\\S+`, 'g')\nconst DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn']\n\nconst DefaultType = {\n animation: 'boolean',\n template: 'string',\n title: '(string|element|function)',\n trigger: 'string',\n delay: '(number|object)',\n html: 'boolean',\n selector: '(string|boolean)',\n placement: '(string|function)',\n offset: '(number|string|function)',\n container: '(string|element|boolean)',\n fallbackPlacement: '(string|array)',\n boundary: '(string|element)',\n customClass: '(string|function)',\n sanitize: 'boolean',\n sanitizeFn: '(null|function)',\n whiteList: 'object',\n popperConfig: '(null|object)'\n}\n\nconst AttachmentMap = {\n AUTO: 'auto',\n TOP: 'top',\n RIGHT: 'right',\n BOTTOM: 'bottom',\n LEFT: 'left'\n}\n\nconst Default = {\n animation: true,\n template: '
' +\n '
' +\n '
',\n trigger: 'hover focus',\n title: '',\n delay: 0,\n html: false,\n selector: false,\n placement: 'top',\n offset: 0,\n container: false,\n fallbackPlacement: 'flip',\n boundary: 'scrollParent',\n customClass: '',\n sanitize: true,\n sanitizeFn: null,\n whiteList: DefaultWhitelist,\n popperConfig: null\n}\n\nconst HOVER_STATE_SHOW = 'show'\nconst HOVER_STATE_OUT = 'out'\n\nconst Event = {\n HIDE: `hide${EVENT_KEY}`,\n HIDDEN: `hidden${EVENT_KEY}`,\n SHOW: `show${EVENT_KEY}`,\n SHOWN: `shown${EVENT_KEY}`,\n INSERTED: `inserted${EVENT_KEY}`,\n CLICK: `click${EVENT_KEY}`,\n FOCUSIN: `focusin${EVENT_KEY}`,\n FOCUSOUT: `focusout${EVENT_KEY}`,\n MOUSEENTER: `mouseenter${EVENT_KEY}`,\n MOUSELEAVE: `mouseleave${EVENT_KEY}`\n}\n\nconst CLASS_NAME_FADE = 'fade'\nconst CLASS_NAME_SHOW = 'show'\n\nconst SELECTOR_TOOLTIP_INNER = '.tooltip-inner'\nconst SELECTOR_ARROW = '.arrow'\n\nconst TRIGGER_HOVER = 'hover'\nconst TRIGGER_FOCUS = 'focus'\nconst TRIGGER_CLICK = 'click'\nconst TRIGGER_MANUAL = 'manual'\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Tooltip {\n constructor(element, config) {\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s tooltips require Popper (https://popper.js.org)')\n }\n\n // private\n this._isEnabled = true\n this._timeout = 0\n this._hoverState = ''\n this._activeTrigger = {}\n this._popper = null\n\n // Protected\n this.element = element\n this.config = this._getConfig(config)\n this.tip = null\n\n this._setListeners()\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n static get NAME() {\n return NAME\n }\n\n static get DATA_KEY() {\n return DATA_KEY\n }\n\n static get Event() {\n return Event\n }\n\n static get EVENT_KEY() {\n return EVENT_KEY\n }\n\n static get DefaultType() {\n return DefaultType\n }\n\n // Public\n\n enable() {\n this._isEnabled = true\n }\n\n disable() {\n this._isEnabled = false\n }\n\n toggleEnabled() {\n this._isEnabled = !this._isEnabled\n }\n\n toggle(event) {\n if (!this._isEnabled) {\n return\n }\n\n if (event) {\n const dataKey = this.constructor.DATA_KEY\n let context = $(event.currentTarget).data(dataKey)\n\n if (!context) {\n context = new this.constructor(\n event.currentTarget,\n this._getDelegateConfig()\n )\n $(event.currentTarget).data(dataKey, context)\n }\n\n context._activeTrigger.click = !context._activeTrigger.click\n\n if (context._isWithActiveTrigger()) {\n context._enter(null, context)\n } else {\n context._leave(null, context)\n }\n } else {\n if ($(this.getTipElement()).hasClass(CLASS_NAME_SHOW)) {\n this._leave(null, this)\n return\n }\n\n this._enter(null, this)\n }\n }\n\n dispose() {\n clearTimeout(this._timeout)\n\n $.removeData(this.element, this.constructor.DATA_KEY)\n\n $(this.element).off(this.constructor.EVENT_KEY)\n $(this.element).closest('.modal').off('hide.bs.modal', this._hideModalHandler)\n\n if (this.tip) {\n $(this.tip).remove()\n }\n\n this._isEnabled = null\n this._timeout = null\n this._hoverState = null\n this._activeTrigger = null\n if (this._popper) {\n this._popper.destroy()\n }\n\n this._popper = null\n this.element = null\n this.config = null\n this.tip = null\n }\n\n show() {\n if ($(this.element).css('display') === 'none') {\n throw new Error('Please use show on visible elements')\n }\n\n const showEvent = $.Event(this.constructor.Event.SHOW)\n if (this.isWithContent() && this._isEnabled) {\n $(this.element).trigger(showEvent)\n\n const shadowRoot = Util.findShadowRoot(this.element)\n const isInTheDom = $.contains(\n shadowRoot !== null ? shadowRoot : this.element.ownerDocument.documentElement,\n this.element\n )\n\n if (showEvent.isDefaultPrevented() || !isInTheDom) {\n return\n }\n\n const tip = this.getTipElement()\n const tipId = Util.getUID(this.constructor.NAME)\n\n tip.setAttribute('id', tipId)\n this.element.setAttribute('aria-describedby', tipId)\n\n this.setContent()\n\n if (this.config.animation) {\n $(tip).addClass(CLASS_NAME_FADE)\n }\n\n const placement = typeof this.config.placement === 'function' ?\n this.config.placement.call(this, tip, this.element) :\n this.config.placement\n\n const attachment = this._getAttachment(placement)\n this.addAttachmentClass(attachment)\n\n const container = this._getContainer()\n $(tip).data(this.constructor.DATA_KEY, this)\n\n if (!$.contains(this.element.ownerDocument.documentElement, this.tip)) {\n $(tip).appendTo(container)\n }\n\n $(this.element).trigger(this.constructor.Event.INSERTED)\n\n this._popper = new Popper(this.element, tip, this._getPopperConfig(attachment))\n\n $(tip).addClass(CLASS_NAME_SHOW)\n $(tip).addClass(this.config.customClass)\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement) {\n $(document.body).children().on('mouseover', null, $.noop)\n }\n\n const complete = () => {\n if (this.config.animation) {\n this._fixTransition()\n }\n\n const prevHoverState = this._hoverState\n this._hoverState = null\n\n $(this.element).trigger(this.constructor.Event.SHOWN)\n\n if (prevHoverState === HOVER_STATE_OUT) {\n this._leave(null, this)\n }\n }\n\n if ($(this.tip).hasClass(CLASS_NAME_FADE)) {\n const transitionDuration = Util.getTransitionDurationFromElement(this.tip)\n\n $(this.tip)\n .one(Util.TRANSITION_END, complete)\n .emulateTransitionEnd(transitionDuration)\n } else {\n complete()\n }\n }\n }\n\n hide(callback) {\n const tip = this.getTipElement()\n const hideEvent = $.Event(this.constructor.Event.HIDE)\n const complete = () => {\n if (this._hoverState !== HOVER_STATE_SHOW && tip.parentNode) {\n tip.parentNode.removeChild(tip)\n }\n\n this._cleanTipClass()\n this.element.removeAttribute('aria-describedby')\n $(this.element).trigger(this.constructor.Event.HIDDEN)\n if (this._popper !== null) {\n this._popper.destroy()\n }\n\n if (callback) {\n callback()\n }\n }\n\n $(this.element).trigger(hideEvent)\n\n if (hideEvent.isDefaultPrevented()) {\n return\n }\n\n $(tip).removeClass(CLASS_NAME_SHOW)\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n $(document.body).children().off('mouseover', null, $.noop)\n }\n\n this._activeTrigger[TRIGGER_CLICK] = false\n this._activeTrigger[TRIGGER_FOCUS] = false\n this._activeTrigger[TRIGGER_HOVER] = false\n\n if ($(this.tip).hasClass(CLASS_NAME_FADE)) {\n const transitionDuration = Util.getTransitionDurationFromElement(tip)\n\n $(tip)\n .one(Util.TRANSITION_END, complete)\n .emulateTransitionEnd(transitionDuration)\n } else {\n complete()\n }\n\n this._hoverState = ''\n }\n\n update() {\n if (this._popper !== null) {\n this._popper.scheduleUpdate()\n }\n }\n\n // Protected\n\n isWithContent() {\n return Boolean(this.getTitle())\n }\n\n addAttachmentClass(attachment) {\n $(this.getTipElement()).addClass(`${CLASS_PREFIX}-${attachment}`)\n }\n\n getTipElement() {\n this.tip = this.tip || $(this.config.template)[0]\n return this.tip\n }\n\n setContent() {\n const tip = this.getTipElement()\n this.setElementContent($(tip.querySelectorAll(SELECTOR_TOOLTIP_INNER)), this.getTitle())\n $(tip).removeClass(`${CLASS_NAME_FADE} ${CLASS_NAME_SHOW}`)\n }\n\n setElementContent($element, content) {\n if (typeof content === 'object' && (content.nodeType || content.jquery)) {\n // Content is a DOM node or a jQuery\n if (this.config.html) {\n if (!$(content).parent().is($element)) {\n $element.empty().append(content)\n }\n } else {\n $element.text($(content).text())\n }\n\n return\n }\n\n if (this.config.html) {\n if (this.config.sanitize) {\n content = sanitizeHtml(content, this.config.whiteList, this.config.sanitizeFn)\n }\n\n $element.html(content)\n } else {\n $element.text(content)\n }\n }\n\n getTitle() {\n let title = this.element.getAttribute('data-original-title')\n\n if (!title) {\n title = typeof this.config.title === 'function' ?\n this.config.title.call(this.element) :\n this.config.title\n }\n\n return title\n }\n\n // Private\n\n _getPopperConfig(attachment) {\n const defaultBsConfig = {\n placement: attachment,\n modifiers: {\n offset: this._getOffset(),\n flip: {\n behavior: this.config.fallbackPlacement\n },\n arrow: {\n element: SELECTOR_ARROW\n },\n preventOverflow: {\n boundariesElement: this.config.boundary\n }\n },\n onCreate: data => {\n if (data.originalPlacement !== data.placement) {\n this._handlePopperPlacementChange(data)\n }\n },\n onUpdate: data => this._handlePopperPlacementChange(data)\n }\n\n return {\n ...defaultBsConfig,\n ...this.config.popperConfig\n }\n }\n\n _getOffset() {\n const offset = {}\n\n if (typeof this.config.offset === 'function') {\n offset.fn = data => {\n data.offsets = {\n ...data.offsets,\n ...(this.config.offset(data.offsets, this.element) || {})\n }\n\n return data\n }\n } else {\n offset.offset = this.config.offset\n }\n\n return offset\n }\n\n _getContainer() {\n if (this.config.container === false) {\n return document.body\n }\n\n if (Util.isElement(this.config.container)) {\n return $(this.config.container)\n }\n\n return $(document).find(this.config.container)\n }\n\n _getAttachment(placement) {\n return AttachmentMap[placement.toUpperCase()]\n }\n\n _setListeners() {\n const triggers = this.config.trigger.split(' ')\n\n triggers.forEach(trigger => {\n if (trigger === 'click') {\n $(this.element).on(\n this.constructor.Event.CLICK,\n this.config.selector,\n event => this.toggle(event)\n )\n } else if (trigger !== TRIGGER_MANUAL) {\n const eventIn = trigger === TRIGGER_HOVER ?\n this.constructor.Event.MOUSEENTER :\n this.constructor.Event.FOCUSIN\n const eventOut = trigger === TRIGGER_HOVER ?\n this.constructor.Event.MOUSELEAVE :\n this.constructor.Event.FOCUSOUT\n\n $(this.element)\n .on(eventIn, this.config.selector, event => this._enter(event))\n .on(eventOut, this.config.selector, event => this._leave(event))\n }\n })\n\n this._hideModalHandler = () => {\n if (this.element) {\n this.hide()\n }\n }\n\n $(this.element).closest('.modal').on('hide.bs.modal', this._hideModalHandler)\n\n if (this.config.selector) {\n this.config = {\n ...this.config,\n trigger: 'manual',\n selector: ''\n }\n } else {\n this._fixTitle()\n }\n }\n\n _fixTitle() {\n const titleType = typeof this.element.getAttribute('data-original-title')\n\n if (this.element.getAttribute('title') || titleType !== 'string') {\n this.element.setAttribute(\n 'data-original-title',\n this.element.getAttribute('title') || ''\n )\n\n this.element.setAttribute('title', '')\n }\n }\n\n _enter(event, context) {\n const dataKey = this.constructor.DATA_KEY\n context = context || $(event.currentTarget).data(dataKey)\n\n if (!context) {\n context = new this.constructor(\n event.currentTarget,\n this._getDelegateConfig()\n )\n $(event.currentTarget).data(dataKey, context)\n }\n\n if (event) {\n context._activeTrigger[\n event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER\n ] = true\n }\n\n if ($(context.getTipElement()).hasClass(CLASS_NAME_SHOW) || context._hoverState === HOVER_STATE_SHOW) {\n context._hoverState = HOVER_STATE_SHOW\n return\n }\n\n clearTimeout(context._timeout)\n\n context._hoverState = HOVER_STATE_SHOW\n\n if (!context.config.delay || !context.config.delay.show) {\n context.show()\n return\n }\n\n context._timeout = setTimeout(() => {\n if (context._hoverState === HOVER_STATE_SHOW) {\n context.show()\n }\n }, context.config.delay.show)\n }\n\n _leave(event, context) {\n const dataKey = this.constructor.DATA_KEY\n context = context || $(event.currentTarget).data(dataKey)\n\n if (!context) {\n context = new this.constructor(\n event.currentTarget,\n this._getDelegateConfig()\n )\n $(event.currentTarget).data(dataKey, context)\n }\n\n if (event) {\n context._activeTrigger[\n event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER\n ] = false\n }\n\n if (context._isWithActiveTrigger()) {\n return\n }\n\n clearTimeout(context._timeout)\n\n context._hoverState = HOVER_STATE_OUT\n\n if (!context.config.delay || !context.config.delay.hide) {\n context.hide()\n return\n }\n\n context._timeout = setTimeout(() => {\n if (context._hoverState === HOVER_STATE_OUT) {\n context.hide()\n }\n }, context.config.delay.hide)\n }\n\n _isWithActiveTrigger() {\n for (const trigger in this._activeTrigger) {\n if (this._activeTrigger[trigger]) {\n return true\n }\n }\n\n return false\n }\n\n _getConfig(config) {\n const dataAttributes = $(this.element).data()\n\n Object.keys(dataAttributes)\n .forEach(dataAttr => {\n if (DISALLOWED_ATTRIBUTES.indexOf(dataAttr) !== -1) {\n delete dataAttributes[dataAttr]\n }\n })\n\n config = {\n ...this.constructor.Default,\n ...dataAttributes,\n ...(typeof config === 'object' && config ? config : {})\n }\n\n if (typeof config.delay === 'number') {\n config.delay = {\n show: config.delay,\n hide: config.delay\n }\n }\n\n if (typeof config.title === 'number') {\n config.title = config.title.toString()\n }\n\n if (typeof config.content === 'number') {\n config.content = config.content.toString()\n }\n\n Util.typeCheckConfig(\n NAME,\n config,\n this.constructor.DefaultType\n )\n\n if (config.sanitize) {\n config.template = sanitizeHtml(config.template, config.whiteList, config.sanitizeFn)\n }\n\n return config\n }\n\n _getDelegateConfig() {\n const config = {}\n\n if (this.config) {\n for (const key in this.config) {\n if (this.constructor.Default[key] !== this.config[key]) {\n config[key] = this.config[key]\n }\n }\n }\n\n return config\n }\n\n _cleanTipClass() {\n const $tip = $(this.getTipElement())\n const tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX)\n if (tabClass !== null && tabClass.length) {\n $tip.removeClass(tabClass.join(''))\n }\n }\n\n _handlePopperPlacementChange(popperData) {\n this.tip = popperData.instance.popper\n this._cleanTipClass()\n this.addAttachmentClass(this._getAttachment(popperData.placement))\n }\n\n _fixTransition() {\n const tip = this.getTipElement()\n const initConfigAnimation = this.config.animation\n\n if (tip.getAttribute('x-placement') !== null) {\n return\n }\n\n $(tip).removeClass(CLASS_NAME_FADE)\n this.config.animation = false\n this.hide()\n this.show()\n this.config.animation = initConfigAnimation\n }\n\n // Static\n\n static _jQueryInterface(config) {\n return this.each(function () {\n const $element = $(this)\n let data = $element.data(DATA_KEY)\n const _config = typeof config === 'object' && config\n\n if (!data && /dispose|hide/.test(config)) {\n return\n }\n\n if (!data) {\n data = new Tooltip(this, _config)\n $element.data(DATA_KEY, data)\n }\n\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`)\n }\n\n data[config]()\n }\n })\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Tooltip._jQueryInterface\n$.fn[NAME].Constructor = Tooltip\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Tooltip._jQueryInterface\n}\n\nexport default Tooltip\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): popover.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Tooltip from './tooltip'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'popover'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.popover'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\nconst CLASS_PREFIX = 'bs-popover'\nconst BSCLS_PREFIX_REGEX = new RegExp(`(^|\\\\s)${CLASS_PREFIX}\\\\S+`, 'g')\n\nconst Default = {\n ...Tooltip.Default,\n placement: 'right',\n trigger: 'click',\n content: '',\n template: '
' +\n '
' +\n '

' +\n '
'\n}\n\nconst DefaultType = {\n ...Tooltip.DefaultType,\n content: '(string|element|function)'\n}\n\nconst CLASS_NAME_FADE = 'fade'\nconst CLASS_NAME_SHOW = 'show'\n\nconst SELECTOR_TITLE = '.popover-header'\nconst SELECTOR_CONTENT = '.popover-body'\n\nconst Event = {\n HIDE: `hide${EVENT_KEY}`,\n HIDDEN: `hidden${EVENT_KEY}`,\n SHOW: `show${EVENT_KEY}`,\n SHOWN: `shown${EVENT_KEY}`,\n INSERTED: `inserted${EVENT_KEY}`,\n CLICK: `click${EVENT_KEY}`,\n FOCUSIN: `focusin${EVENT_KEY}`,\n FOCUSOUT: `focusout${EVENT_KEY}`,\n MOUSEENTER: `mouseenter${EVENT_KEY}`,\n MOUSELEAVE: `mouseleave${EVENT_KEY}`\n}\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass Popover extends Tooltip {\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n static get NAME() {\n return NAME\n }\n\n static get DATA_KEY() {\n return DATA_KEY\n }\n\n static get Event() {\n return Event\n }\n\n static get EVENT_KEY() {\n return EVENT_KEY\n }\n\n static get DefaultType() {\n return DefaultType\n }\n\n // Overrides\n\n isWithContent() {\n return this.getTitle() || this._getContent()\n }\n\n addAttachmentClass(attachment) {\n $(this.getTipElement()).addClass(`${CLASS_PREFIX}-${attachment}`)\n }\n\n getTipElement() {\n this.tip = this.tip || $(this.config.template)[0]\n return this.tip\n }\n\n setContent() {\n const $tip = $(this.getTipElement())\n\n // We use append for html objects to maintain js events\n this.setElementContent($tip.find(SELECTOR_TITLE), this.getTitle())\n let content = this._getContent()\n if (typeof content === 'function') {\n content = content.call(this.element)\n }\n\n this.setElementContent($tip.find(SELECTOR_CONTENT), content)\n\n $tip.removeClass(`${CLASS_NAME_FADE} ${CLASS_NAME_SHOW}`)\n }\n\n // Private\n\n _getContent() {\n return this.element.getAttribute('data-content') ||\n this.config.content\n }\n\n _cleanTipClass() {\n const $tip = $(this.getTipElement())\n const tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX)\n if (tabClass !== null && tabClass.length > 0) {\n $tip.removeClass(tabClass.join(''))\n }\n }\n\n // Static\n\n static _jQueryInterface(config) {\n return this.each(function () {\n let data = $(this).data(DATA_KEY)\n const _config = typeof config === 'object' ? config : null\n\n if (!data && /dispose|hide/.test(config)) {\n return\n }\n\n if (!data) {\n data = new Popover(this, _config)\n $(this).data(DATA_KEY, data)\n }\n\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`)\n }\n\n data[config]()\n }\n })\n }\n}\n\n/**\n * ------------------------------------------------------------------------\n * jQuery\n * ------------------------------------------------------------------------\n */\n\n$.fn[NAME] = Popover._jQueryInterface\n$.fn[NAME].Constructor = Popover\n$.fn[NAME].noConflict = () => {\n $.fn[NAME] = JQUERY_NO_CONFLICT\n return Popover._jQueryInterface\n}\n\nexport default Popover\n","/**\n * --------------------------------------------------------------------------\n * Bootstrap (v4.6.0): scrollspy.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nimport $ from 'jquery'\nimport Util from './util'\n\n/**\n * ------------------------------------------------------------------------\n * Constants\n * ------------------------------------------------------------------------\n */\n\nconst NAME = 'scrollspy'\nconst VERSION = '4.6.0'\nconst DATA_KEY = 'bs.scrollspy'\nconst EVENT_KEY = `.${DATA_KEY}`\nconst DATA_API_KEY = '.data-api'\nconst JQUERY_NO_CONFLICT = $.fn[NAME]\n\nconst Default = {\n offset: 10,\n method: 'auto',\n target: ''\n}\n\nconst DefaultType = {\n offset: 'number',\n method: 'string',\n target: '(string|element)'\n}\n\nconst EVENT_ACTIVATE = `activate${EVENT_KEY}`\nconst EVENT_SCROLL = `scroll${EVENT_KEY}`\nconst EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`\n\nconst CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'\nconst CLASS_NAME_ACTIVE = 'active'\n\nconst SELECTOR_DATA_SPY = '[data-spy=\"scroll\"]'\nconst SELECTOR_NAV_LIST_GROUP = '.nav, .list-group'\nconst SELECTOR_NAV_LINKS = '.nav-link'\nconst SELECTOR_NAV_ITEMS = '.nav-item'\nconst SELECTOR_LIST_ITEMS = '.list-group-item'\nconst SELECTOR_DROPDOWN = '.dropdown'\nconst SELECTOR_DROPDOWN_ITEMS = '.dropdown-item'\nconst SELECTOR_DROPDOWN_TOGGLE = '.dropdown-toggle'\n\nconst METHOD_OFFSET = 'offset'\nconst METHOD_POSITION = 'position'\n\n/**\n * ------------------------------------------------------------------------\n * Class Definition\n * ------------------------------------------------------------------------\n */\n\nclass ScrollSpy {\n constructor(element, config) {\n this._element = element\n this._scrollElement = element.tagName === 'BODY' ? window : element\n this._config = this._getConfig(config)\n this._selector = `${this._config.target} ${SELECTOR_NAV_LINKS},` +\n `${this._config.target} ${SELECTOR_LIST_ITEMS},` +\n `${this._config.target} ${SELECTOR_DROPDOWN_ITEMS}`\n this._offsets = []\n this._targets = []\n this._activeTarget = null\n this._scrollHeight = 0\n\n $(this._scrollElement).on(EVENT_SCROLL, event => this._process(event))\n\n this.refresh()\n this._process()\n }\n\n // Getters\n\n static get VERSION() {\n return VERSION\n }\n\n static get Default() {\n return Default\n }\n\n // Public\n\n refresh() {\n const autoMethod = this._scrollElement === this._scrollElement.window ?\n METHOD_OFFSET : METHOD_POSITION\n\n const offsetMethod = this._config.method === 'auto' ?\n autoMethod : this._config.method\n\n const offsetBase = offsetMethod === METHOD_POSITION ?\n this._getScrollTop() : 0\n\n this._offsets = []\n this._targets = []\n\n this._scrollHeight = this._getScrollHeight()\n\n const targets = [].slice.call(document.querySelectorAll(this._selector))\n\n targets\n .map(element => {\n let target\n const targetSelector = Util.getSelectorFromElement(element)\n\n if (targetSelector) {\n target = document.querySelector(targetSelector)\n }\n\n if (target) {\n const targetBCR = target.getBoundingClientRect()\n if (targetBCR.width || targetBCR.height) {\n // TODO (fat): remove sketch reliance on jQuery position/offset\n return [\n $(target)[offsetMethod]().top + offsetBase,\n targetSelector\n ]\n }\n }\n\n return null\n })\n .filter(item => item)\n .sort((a, b) => a[0] - b[0])\n .forEach(item => {\n this._offsets.push(item[0])\n this._targets.push(item[1])\n })\n }\n\n dispose() {\n $.removeData(this._element, DATA_KEY)\n $(this._scrollElement).off(EVENT_KEY)\n\n this._element = null\n this._scrollElement = null\n this._config = null\n this._selector = null\n this._offsets = null\n this._targets = null\n this._activeTarget = null\n this._scrollHeight = null\n }\n\n // Private\n\n _getConfig(config) {\n config = {\n ...Default,\n ...(typeof config === 'object' && config ? config : {})\n }\n\n if (typeof config.target !== 'string' && Util.isElement(config.target)) {\n let id = $(config.target).attr('id')\n if (!id) {\n id = Util.getUID(NAME)\n $(config.target).attr('id', id)\n }\n\n config.target = `#${id}`\n }\n\n Util.typeCheckConfig(NAME, config, DefaultType)\n\n return config\n }\n\n _getScrollTop() {\n return this._scrollElement === window ?\n this._scrollElement.pageYOffset : this._scrollElement.scrollTop\n }\n\n _getScrollHeight() {\n return this._scrollElement.scrollHeight || Math.max(\n document.body.scrollHeight,\n document.documentElement.scrollHeight\n )\n }\n\n _getOffsetHeight() {\n return this._scrollElement === window ?\n window.innerHeight : this._scrollElement.getBoundingClientRect().height\n }\n\n _process() {\n const scrollTop = this._getScrollTop() + this._config.offset\n const scrollHeight = this._getScrollHeight()\n const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight()\n\n if (this._scrollHeight !== scrollHeight) {\n this.refresh()\n }\n\n if (scrollTop >= maxScroll) {\n const target = this._targets[this._targets.length - 1]\n\n if (this._activeTarget !== target) {\n this._activate(target)\n }\n\n return\n }\n\n if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {\n this._activeTarget = null\n this._clear()\n return\n }\n\n for (let i = this._offsets.length; i--;) {\n const isActiveTarget = this._activeTarget !== this._targets[i] &&\n scrollTop >= this._offsets[i] &&\n (typeof this._offsets[i + 1] === 'undefined' ||\n scrollTop < this._offsets[i + 1])\n\n if (isActiveTarget) {\n this._activate(this._targets[i])\n }\n }\n }\n\n _activate(target) {\n this._activeTarget = target\n\n this._clear()\n\n const queries = this._selector\n .split(',')\n .map(selector => `${selector}[data-target=\"${target}\"],${selector}[href=\"${target}\"]`)\n\n const $link = $([].slice.call(document.querySelectorAll(queries.join(','))))\n\n if ($link.hasClass(CLASS_NAME_DROPDOWN_ITEM)) {\n $link.closest(SELECTOR_DROPDOWN)\n .find(SELECTOR_DROPDOWN_TOGGLE)\n .addClass(CLASS_NAME_ACTIVE)\n $link.addClass(CLASS_NAME_ACTIVE)\n } else {\n // Set triggered link as active\n $link.addClass(CLASS_NAME_ACTIVE)\n // Set triggered links parents as active\n // With both
    and
`}else{let mode=display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
-
${peer.name===""?"Untitled":peer.name}
-
-
`;let peer_transfer=`
-

- ${roundN(peer.total_receive+total_r,4)} GB -

-

- ${roundN(peer.total_sent+total_s,4)} GB -

-
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` -
-
-
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});response.lock_access_peers.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name=`
-
${peer.name===""?"Untitled":peer.name}
-
-
`;let peer_transfer=`
-

- ${roundN(peer.total_receive+total_r,4)} GB -

-

- ${roundN(peer.total_sent+total_s,4)} GB -

-
`;let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control=` -
-
-
- - Peer Disabled -
`;let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(configuration_interval===undefined){setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=configuration_name;let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({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"),keys:keys,amount:$new_add_amount.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.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"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());window.configurations.showToast(`Deleted ${peer_ids.length} peers`);$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding");document.querySelector(".no-response .container h4").innerHTML=message},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let time=0;let count=0;let d1=new Date;function loadPeers(searchString){d1=new Date;let good=true;$.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){console.log(response);parsePeers(response)}).fail(function(){noResponding();good=false});return good}function parsePeers(response){if(response.status){removeAllTooltips();let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;window.console.log(`Average time: ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);removeNoResponding();peers=response.data.peer_data;configurationAlert(response.data);configurationHeader(response.data);configurationPeers(response.data);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();$("#configuration_name").text(configuration_name);if(firstLoading){firstLoading=false;$("#config_body").removeClass("firstLoading")}}else{noResponding(response.message);removeConfigurationInterval()}}function removeAllTooltips(){$(".tooltip").remove()}function toggleAccess(peerID){$.ajax({url:"/api/togglePeerAccess",method:"POST",headers:{"Content-Type":"application/json"},data:JSON.stringify({peerID:peerID,config:configuration_name})}).done(function(res){if(res.status){loadPeers($("#search_peer_textbox").val())}else{showToast(res.reason)}})}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}let numberToast=0;function showToast(msg){$(".toastContainer").append(``);$(`#${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");numberToast++}function updateRefreshInterval(interval){configuration_timeout=interval;window.localStorage.setItem("configurationTimeout",configuration_timeout.toString());removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done(function(res){if(res.status===true){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else{document.querySelector("#allowed_ips").value=res.message;document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}})}function deleteConfiguration(){}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},configurationDeleteModal:()=>{return configurationDeleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},configurationTimeout:()=>{return configuration_timeout},updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},removeConfigurationInterval:()=>{removeConfigurationInterval()},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},deleteConfiguration:()=>{deleteConfiguration()},parsePeers:response=>{parsePeers(response)},toggleAccess:peerID=>{toggleAccess(peerID)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>{return configuration_name},setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");$("#configuration_delete").on("click",function(){window.configurations.configurationDeleteModal().toggle()});$("#sure_delete_configuration").on("click",function(){window.configurations.removeConfigurationInterval();$(this).attr("disabled","disabled");function done(res){if(res.status){window.configurations.configurationDeleteModal().toggle()}}ajaxPostJSON("/api/deleteConfiguration",{name:configuration_name},done)});document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});$(".toggle--switch").on("click",function(){$(this).addClass("waiting").attr("disabled","disabled");let id=window.configurations.getConfigurationName();let status=$(this).prop("checked");let ele=$(this);$.ajax({url:`/switch/${id}`}).done(function(res){console.log();if(res){if(status){window.configurations.showToast(`${id} is running.`)}else{window.configurations.showToast(`${id} is stopped.`)}ele.removeClass("waiting");ele.removeAttr("disabled")}else{if(status){$(this).prop("checked",false)}else{$(this).prop("checked",true)}}window.configurations.loadPeers($("#search_peer_textbox").val())})});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=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.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=window.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{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.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{window.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=>window.configurations.triggerIp(ele))});$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);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).data("peer-id");$("#delete_peer").data("peer-id",peer_id);window.configurations.deleteModal().toggle()});$body.on("click",".btn-lock-peer",function(){window.configurations.toggleAccess($(this).data("peer-id"),window.configurations.getConfigurationName());if($(this).hasClass("lock")){console.log($(this).data("peer-name"));window.configurations.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{window.configurations.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")}});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let config=window.configurations.getConfigurationName();let peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){let peer_id=$(this).data("peer-id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+window.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);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+window.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")}})}});$("#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{window.configurations.settingModal().toggle();window.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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$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];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$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([5e3,1e4,3e4,6e4].includes(interval)){window.configurations.updateRefreshInterval(interval)}});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");window.localStorage.setItem("displayMode",$(this).data("display-mode"));window.configurations.updateDisplayMode();if($(this).data("display-mode")==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");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;$("#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));window.configurations.deletePeers(window.configurations.getConfigurationName(),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file diff --git a/src/static/js/configurationTool.js b/src/static/js/configurationTool.js index 4eb59e9d..22a26dbb 100644 --- a/src/static/js/configurationTool.js +++ b/src/static/js/configurationTool.js @@ -122,6 +122,35 @@ $editConfiguration.on("click", function(){ 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); +}) /** * ========== @@ -150,9 +179,9 @@ $(".toggle--switch").on("change", function(){ }).done(function(res){ if (res.status){ if (status){ - configurations.showToast(`${id} is running.`) + showToast(`${id} is running.`) }else{ - configurations.showToast(`${id} is stopped.`) + showToast(`${id} is stopped.`) } }else{ if (status){ @@ -160,7 +189,7 @@ $(".toggle--switch").on("change", function(){ }else{ ele.prop("checked", true) } - configurations.showToast(res.reason); + 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"); @@ -283,7 +312,7 @@ $add_peer.addEventListener("click", function() { $("#add_peer_form").trigger("reset"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; - configurations.showToast("Add peer successful!"); + showToast("Add peer successful!"); configurations.addModal().toggle(); } } @@ -447,12 +476,12 @@ $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")) - configurations.showToast(`Enabled ${$(this).children().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 - configurations.showToast(`Disabled ${$(this).children().data("peer-name")}`) + 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'); } @@ -706,12 +735,12 @@ $body.on("click", ".display_mode", function() { Array($(".peer_list").children()).forEach(function(child) { $(child).removeClass().addClass("col-12"); }); - configurations.showToast("Displaying as List"); + showToast("Displaying as List"); } else { Array($(".peer_list").children()).forEach(function(child) { $(child).removeClass().addClass("col-sm-6 col-lg-4"); }); - configurations.showToast("Displaying as Grids"); + showToast("Displaying as Grids"); } }); @@ -891,9 +920,9 @@ $("#download_all_peers").on("click", function() { success: function(res) { if (res.peers.length > 0) { window.wireguard.generateZipFiles(res); - configurations.showToast("Peers' zip file download successful!"); + showToast("Peers' zip file download successful!"); } else { - configurations.showToast("Oops! There are no peer can be download."); + showToast("Oops! There are no peer can be download."); } } }); diff --git a/src/static/js/configurationTool.min.js b/src/static/js/configurationTool.min.js new file mode 100644 index 00000000..0fc5ea32 --- /dev/null +++ b/src/static/js/configurationTool.min.js @@ -0,0 +1 @@ +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("/")},5e3)}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)},3e4);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")}});$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)});document.querySelector(".add_btn").addEventListener("click",()=>{configurations.addModal().toggle()});$(".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())})});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=""}});$("#add_modal").on("show.bs.modal",function(){configurations.generateKeyPair();configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");configurations.generateKeyPair()});$("#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('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$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"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");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")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{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))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){configurations.triggerIp($(this).data("ip"))});$("#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{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))});$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()})});$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{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")}});$("#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)});$body.on("click",".btn-setting-peer",function(){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()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#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")}})}});$("#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")}});$(".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)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$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())}})});$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!"});$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([5e3,1e4,3e4,6e4].includes(interval)){configurations.updateRefreshInterval(interval)}});$body.on("click",".refresh",function(){configurations.loadPeers($("#search_peer_textbox").val())});$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")}});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$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)}});$("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_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(''+name+"
"+peer.id+"
")});configurations.deleteBulkModal().toggle()});$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");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;$("#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}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){configurations.toggleDeleteByBulkIP($(this))}})});$(configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){configurations.toggleDeleteByBulkIP($(this))}})});$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)}})});$("#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.")}}})}); \ No newline at end of file diff --git a/src/static/js/index.js b/src/static/js/index.js index 84ac7f11..acc244a5 100644 --- a/src/static/js/index.js +++ b/src/static/js/index.js @@ -1,4 +1,3 @@ -let numberToast = 0; let emptyInputFeedback = "Can't leave empty"; $('[data-toggle="tooltip"]').tooltip() let $add_configuration = $("#add_configuration"); @@ -19,25 +18,6 @@ addConfigurationModal.on("hidden.bs.modal", function(){ $(".addConfigurationAvailableIPs").text("N/A"); }); -function showToast(msg){ - $(".toastContainer").append( - `` ); - $(`#${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"); - numberToast++; -} - $(".toggle--switch").on("change", function(){ $(this).addClass("waiting").attr("disabled", "disabled"); let id = $(this).data("conf-id"); @@ -59,6 +39,7 @@ $(".toggle--switch").on("change", function(){ } }else{ ele.parents().children(".card-message").html(`
Configuration toggle failed. Please check the following error message:
${res.message}
`) + showToast(`${id} toggled failed.`, true); if (status){ ele.prop("checked", false) }else{ @@ -70,8 +51,18 @@ $(".toggle--switch").on("change", function(){ }); $(".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"); } }); diff --git a/src/static/js/index.min.js b/src/static/js/index.min.js index 46f95d92..2fe17031 100644 --- a/src/static/js/index.min.js +++ b/src/static/js/index.min.js @@ -1,10 +1 @@ -let numberToast=0;let emptyInputFeedback="Can't leave empty";$('[data-toggle="tooltip"]').tooltip();let $add_configuration=$("#add_configuration");let addConfigurationModal=$("#addConfigurationModal");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")});function showToast(msg){$(".toastContainer").append(``);$(`#${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");numberToast++}$(".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(`
Configuration toggle failed. Please check the following error message:
${res.message}
`);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"){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)})}export{ajaxPostJSON};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(`${res.data}`);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{let name=res.data;$(".addConfigurationAddStatus").removeClass("text-primary").addClass("text-success").html(` ${name} added successfully.`);if(res.status){setTimeout(()=>{$(".addConfigurationToggleStatus").removeClass("waiting").html(`
Toggle Configuration`);$.ajax({url:`/switch/${name}`}).done(function(res){if(res.status){$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-success").html(` Toggle Successfully. Refresh in 5 seconds.`);setTimeout(()=>{$(".addConfigurationToggleStatus").text("Refeshing...");location.reload()},5e3)}else{$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} toggle failed.`);$("#addCconfigurationAlertMessage").removeClass("d-none").html(`${name} toggle failed. Please check the following error message:
${res.message}`)}})},500)}else{$(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} adding failed.`);$("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason)}};ajaxPostJSON("/api/addConfiguration",data,done)}}); \ No newline at end of file +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(`
Configuration toggle failed. Please check the following error message:
${res.message}
`);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(`${res.data}`);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{let name=res.data;$(".addConfigurationAddStatus").removeClass("text-primary").addClass("text-success").html(` ${name} added successfully.`);if(res.status){setTimeout(()=>{$(".addConfigurationToggleStatus").removeClass("waiting").html(`
Toggle Configuration`);$.ajax({url:`/switch/${name}`}).done(function(res){if(res.status){$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-success").html(` Toggle Successfully. Refresh in 5 seconds.`);setTimeout(()=>{$(".addConfigurationToggleStatus").text("Refeshing...");location.reload()},5e3)}else{$(".addConfigurationToggleStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} toggle failed.`);$("#addCconfigurationAlertMessage").removeClass("d-none").html(`${name} toggle failed. Please check the following error message:
${res.message}`)}})},500)}else{$(".addConfigurationStatus").removeClass("text-primary").addClass("text-danger").html(` ${name} adding failed.`);$("#addCconfigurationAlert").removeClass("d-none").children(".alert-body").text(res.reason)}};ajaxPostJSON("/api/addConfiguration",data,done)}}); \ No newline at end of file diff --git a/src/static/js/jquery.min.js b/src/static/js/jquery.min.js deleted file mode 100644 index 200b54e4..00000000 --- a/src/static/js/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0'); + showToast("Switched to dark theme"); + } + } + }); + } +}); \ No newline at end of file diff --git a/src/static/js/settings.min.js b/src/static/js/settings.min.js new file mode 100644 index 00000000..45629bbd --- /dev/null +++ b/src/static/js/settings.min.js @@ -0,0 +1 @@ +$(".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('');showToast("Switched to dark theme")}}})}}); \ No newline at end of file diff --git a/src/static/js/tools.js b/src/static/js/tools.js index 8623eb32..46ab0f31 100644 --- a/src/static/js/tools.js +++ b/src/static/js/tools.js @@ -64,4 +64,27 @@ $(".send_traceroute").on("click", function (){ $("#traceroute_modal .form-control").removeAttr("disabled"); } }); -}); \ No newline at end of file +}); +let numberToast = 0; +function showToast(msg, isDanger = false) { + $(".toastContainer").append( + `` ) + $(`#${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++; +} \ No newline at end of file diff --git a/src/static/js/tools.min.js b/src/static/js/tools.min.js index d18ce0b3..167c7864 100644 --- a/src/static/js/tools.min.js +++ b/src/static/js/tools.min.js @@ -1 +1,10 @@ -$(".ip_dropdown").on("change",function(){$(".modal.show .btn").removeAttr("disabled")});$(".conf_dropdown").on("change",function(){$(".modal.show .ip_dropdown").html('
- {% include "modal.html" %}
{% include "tools.html" %} @@ -192,7 +191,7 @@ {% include "footer.html" %} - + - + \ No newline at end of file diff --git a/src/templates/index.html b/src/templates/index.html index 16c7e46c..67cc443b 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -156,10 +156,9 @@
-{% include "tools.html" %} + {% include "tools.html" %} {% include "footer.html" %} - + - \ No newline at end of file diff --git a/src/templates/modal.html b/src/templates/modal.html index c60caefb..2343fb90 100644 --- a/src/templates/modal.html +++ b/src/templates/modal.html @@ -371,58 +371,32 @@

                 
+
+
+
+ +

+
+
+
+
+ +

+
+
+
-
- -
-
- -
- -
-
-
-
-
-
-
- - -
-
-
-
-
- - -
-
-
-
-
-
-
- - -
-
-
-
-
- -

N/A

-
-
+ +


+
+ + +
+
+
diff --git a/src/templates/settings.html b/src/templates/settings.html index 881401a3..47f34c1f 100644 --- a/src/templates/settings.html +++ b/src/templates/settings.html @@ -181,69 +181,9 @@ {% include "tools.html" %} +
- {% include "footer.html" %} - - $(".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(); - }else{ - $("head").append(''); - } - } - }); - } - }); - - - \ No newline at end of file From 0c0bce975570f2b9b63ab40928c3e8b8bf1d373d Mon Sep 17 00:00:00 2001 From: Donald Zou Date: Thu, 30 Nov 2023 09:42:02 -0500 Subject: [PATCH 029/214] Combining Vue.js!!! How exciting! Adding Vue.js to handle frontend changes, leaving the server only need to response json data. Ditching flask template and hope it can reduce the memory and cpu usage :) --- .gitignore | 3 +- package-lock.json | 248 ++++++++++++++++++++++++++++++++ package.json | 6 + src/dashboard.py | 15 +- src/static/app/app.js | 51 +++++++ src/static/app/cookie.js | 9 ++ src/static/app/index.js | 5 + src/static/app/signin/fetch.js | 28 ++++ src/static/app/signin/signin.js | 52 +++++++ src/static/app/store.js | 5 + src/static/css/dashboard.css | 6 +- src/templates/footer.html | 3 +- src/templates/header.html | 11 +- src/templates/index_new.html | 37 +++++ src/templates/signin.html | 24 +--- 15 files changed, 462 insertions(+), 41 deletions(-) create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/static/app/app.js create mode 100644 src/static/app/cookie.js create mode 100644 src/static/app/index.js create mode 100644 src/static/app/signin/fetch.js create mode 100644 src/static/app/signin/signin.js create mode 100644 src/static/app/store.js create mode 100644 src/templates/index_new.html diff --git a/.gitignore b/.gitignore index 8f1b4940..ad995bc4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,5 @@ venv/** log/** release/* src/db/wgdashboard.db -.jshintrc \ No newline at end of file +.jshintrc +node_modules/** \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..248b0255 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,248 @@ +{ + "name": "Wireguard-Dashboard", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "vue": "^3.3.9", + "vue-router": "^4.2.5" + } + }, + "node_modules/@babel/parser": { + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.5.tgz", + "integrity": "sha512-hOOqoiNXrmGdFbhgCzu6GiURxUgM27Xwd/aPuu8RfHEZPBzL1Z54okAHAQjXfcQNwvrlkAmAp4SlRTZ45vlthQ==", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@vue/compiler-core": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.3.9.tgz", + "integrity": "sha512-+/Lf68Vr/nFBA6ol4xOtJrW+BQWv3QWKfRwGSm70jtXwfhZNF4R/eRgyVJYoxFRhdCTk/F6g99BP0ffPgZihfQ==", + "dependencies": { + "@babel/parser": "^7.23.3", + "@vue/shared": "3.3.9", + "estree-walker": "^2.0.2", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.3.9.tgz", + "integrity": "sha512-nfWubTtLXuT4iBeDSZ5J3m218MjOy42Vp2pmKVuBKo2/BLcrFUX8nCSr/bKRFiJ32R8qbdnnnBgRn9AdU5v0Sg==", + "dependencies": { + "@vue/compiler-core": "3.3.9", + "@vue/shared": "3.3.9" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.3.9.tgz", + "integrity": "sha512-wy0CNc8z4ihoDzjASCOCsQuzW0A/HP27+0MDSSICMjVIFzk/rFViezkR3dzH+miS2NDEz8ywMdbjO5ylhOLI2A==", + "dependencies": { + "@babel/parser": "^7.23.3", + "@vue/compiler-core": "3.3.9", + "@vue/compiler-dom": "3.3.9", + "@vue/compiler-ssr": "3.3.9", + "@vue/reactivity-transform": "3.3.9", + "@vue/shared": "3.3.9", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.5", + "postcss": "^8.4.31", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.3.9.tgz", + "integrity": "sha512-NO5oobAw78R0G4SODY5A502MGnDNiDjf6qvhn7zD7TJGc8XDeIEw4fg6JU705jZ/YhuokBKz0A5a/FL/XZU73g==", + "dependencies": { + "@vue/compiler-dom": "3.3.9", + "@vue/shared": "3.3.9" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.5.1.tgz", + "integrity": "sha512-+KpckaAQyfbvshdDW5xQylLni1asvNSGme1JFs8I1+/H5pHEhqUKMEQD/qn3Nx5+/nycBq11qAEi8lk+LXI2dA==" + }, + "node_modules/@vue/reactivity": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.3.9.tgz", + "integrity": "sha512-VmpIqlNp+aYDg2X0xQhJqHx9YguOmz2UxuUJDckBdQCNkipJvfk9yA75woLWElCa0Jtyec3lAAt49GO0izsphw==", + "dependencies": { + "@vue/shared": "3.3.9" + } + }, + "node_modules/@vue/reactivity-transform": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.3.9.tgz", + "integrity": "sha512-HnUFm7Ry6dFa4Lp63DAxTixUp8opMtQr6RxQCpDI1vlh12rkGIeYqMvJtK+IKyEfEOa2I9oCkD1mmsPdaGpdVg==", + "dependencies": { + "@babel/parser": "^7.23.3", + "@vue/compiler-core": "3.3.9", + "@vue/shared": "3.3.9", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.5" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.3.9.tgz", + "integrity": "sha512-xxaG9KvPm3GTRuM4ZyU8Tc+pMVzcu6eeoSRQJ9IE7NmCcClW6z4B3Ij6L4EDl80sxe/arTtQ6YmgiO4UZqRc+w==", + "dependencies": { + "@vue/reactivity": "3.3.9", + "@vue/shared": "3.3.9" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.3.9.tgz", + "integrity": "sha512-e7LIfcxYSWbV6BK1wQv9qJyxprC75EvSqF/kQKe6bdZEDNValzeRXEVgiX7AHI6hZ59HA4h7WT5CGvm69vzJTQ==", + "dependencies": { + "@vue/runtime-core": "3.3.9", + "@vue/shared": "3.3.9", + "csstype": "^3.1.2" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.3.9.tgz", + "integrity": "sha512-w0zT/s5l3Oa3ZjtLW88eO4uV6AQFqU8X5GOgzq7SkQQu6vVr+8tfm+OI2kDBplS/W/XgCBuFXiPw6T5EdwXP0A==", + "dependencies": { + "@vue/compiler-ssr": "3.3.9", + "@vue/shared": "3.3.9" + }, + "peerDependencies": { + "vue": "3.3.9" + } + }, + "node_modules/@vue/shared": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.3.9.tgz", + "integrity": "sha512-ZE0VTIR0LmYgeyhurPTpy4KzKsuDyQbMSdM49eKkMnT5X4VfFBLysMzjIZhLEFQYjjOVVfbvUDHckwjDFiO2eA==" + }, + "node_modules/csstype": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.2.tgz", + "integrity": "sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==" + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + }, + "node_modules/magic-string": { + "version": "0.30.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", + "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" + }, + "node_modules/postcss": { + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/vue": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.3.9.tgz", + "integrity": "sha512-sy5sLCTR8m6tvUk1/ijri3Yqzgpdsmxgj6n6yl7GXXCXqVbmW2RCXe9atE4cEI6Iv7L89v5f35fZRRr5dChP9w==", + "dependencies": { + "@vue/compiler-dom": "3.3.9", + "@vue/compiler-sfc": "3.3.9", + "@vue/runtime-dom": "3.3.9", + "@vue/server-renderer": "3.3.9", + "@vue/shared": "3.3.9" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.2.5.tgz", + "integrity": "sha512-DIUpKcyg4+PTQKfFPX88UWhlagBEBEfJ5A8XDXRJLUnZOvcpMF8o/dnL90vpVkGaPbjvXazV/rC1qBKrZlFugw==", + "dependencies": { + "@vue/devtools-api": "^6.5.0" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.2.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..cd954bb0 --- /dev/null +++ b/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "vue": "^3.3.9", + "vue-router": "^4.2.5" + } +} diff --git a/src/dashboard.py b/src/dashboard.py index e5aeaeac..931780e5 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -689,6 +689,9 @@ def auth_req(): Action before every request @return: Redirect """ + return None + + if getattr(g, 'db', None) is None: g.db = connect_db() g.cur = g.db.cursor() @@ -767,9 +770,13 @@ def auth(): if password.hexdigest() == config["Account"]["password"] \ and data['username'] == config["Account"]["username"]: session['username'] = data['username'] + resp = Flask.make_response(jsonify({"status": True, "msg": ""})) + + + resp.set_cookie("auth", hashlib.sha256(f"{data['username']}{datetime.now()}".encode()).hexdigest()) session.permanent = True - config.clear() - return jsonify({"status": True, "msg": ""}) + config.clear(resp) + return config.clear() return jsonify({"status": False, "msg": "Username or Password is incorrect."}) @@ -789,8 +796,8 @@ def index(): if "switch_msg" in session: msg = session["switch_msg"] session.pop("switch_msg") - - return render_template('index.html', conf=get_conf_list(), msg=msg) + return render_template('index_new.html') + # return render_template('index.html', conf=get_conf_list(), msg=msg) # Setting Page diff --git a/src/static/app/app.js b/src/static/app/app.js new file mode 100644 index 00000000..75eda86e --- /dev/null +++ b/src/static/app/app.js @@ -0,0 +1,51 @@ +const { createApp, ref } = Vue; +import Index from './index.js' +import Signin from './signin/signin.js' +const {createPinia} = Pinia +import {cookie} from "./cookie.js"; + +const app = createApp({ + template: ` + + + ` +}); +const pinia = createPinia() +const routes = [ + { + path: '/', + component: Index, + meta: { + requiresAuth: true + } + }, + { + path: '/signin', component: Signin + } +] + +const router = VueRouter.createRouter({ + // 4. Provide the history implementation to use. We are using the hash history for simplicity here. + history: VueRouter.createWebHashHistory(), + routes, // short for `routes: routes` +}); + +router.beforeEach((to, from, next) => { + if (to.meta.requiresAuth){ + if (cookie.getCookie("auth")){ + next() + }else{ + next("/signin") + } + }else { + next(); + } +}); + +app.use(router); +app.use(pinia) +app.mount('#app'); \ No newline at end of file diff --git a/src/static/app/cookie.js b/src/static/app/cookie.js new file mode 100644 index 00000000..964df541 --- /dev/null +++ b/src/static/app/cookie.js @@ -0,0 +1,9 @@ +export const cookie = { + + //https://stackoverflow.com/a/15724300 + getCookie(name) { + const value = `; ${document.cookie}`; + const parts = value.split(`; ${name}=`); + if (parts.length === 2) return parts.pop().split(';').shift(); + } +} \ No newline at end of file diff --git a/src/static/app/index.js b/src/static/app/index.js new file mode 100644 index 00000000..98402f0c --- /dev/null +++ b/src/static/app/index.js @@ -0,0 +1,5 @@ +export default { + template: ` + this is idex + ` +} \ No newline at end of file diff --git a/src/static/app/signin/fetch.js b/src/static/app/signin/fetch.js new file mode 100644 index 00000000..08367216 --- /dev/null +++ b/src/static/app/signin/fetch.js @@ -0,0 +1,28 @@ +export const fetchGet = async (url, params=undefined, callback=undefined) => { + const urlSearchParams = new URLSearchParams(params); + await fetch(`${url}?${urlSearchParams.toString()}}`, { + headers: { + "content-type": "application/json" + } + }) + .then(x => x.json()) + .then(x => callback ? callback(x) : undefined) + .catch(() => { + alert("Error occurred! Check console") + }); +} + +export const fetchPost = async (url, body, callback) => { + await fetch(`${url}`, { + headers: { + "content-type": "application/json" + }, + method: "POST", + body: JSON.stringify(body) + }) + .then(x => x.json()) + .then(x => callback ? callback(x) : undefined) + // .catch(() => { + // alert("Error occurred! Check console") + // }); +} \ No newline at end of file diff --git a/src/static/app/signin/signin.js b/src/static/app/signin/signin.js new file mode 100644 index 00000000..0a2ae77d --- /dev/null +++ b/src/static/app/signin/signin.js @@ -0,0 +1,52 @@ +import {fetchPost} from "./fetch.js"; + +export default { + data(){ + return { + username: "", + password: "" + } + }, + template: ` + + `, + methods: { + async auth(){ + if (this.username && this.password){ + await fetchPost("/auth", { + username: this.username, + password: this.password + }, (response) => { + console.log(response) + }) + }else{ + document.querySelectorAll("input[required]").forEach(x => { + if (x.value.length === 0){ + x.classList.remove("is-valid") + x.classList.add("is-invalid") + }else{ + x.classList.remove("is-invalid") + x.classList.add("is-valid") + } + }) + } + } + } +} \ No newline at end of file diff --git a/src/static/app/store.js b/src/static/app/store.js new file mode 100644 index 00000000..1e10f01b --- /dev/null +++ b/src/static/app/store.js @@ -0,0 +1,5 @@ +import { defineStore } from 'pinia' + +export const wgdStore = defineStore('WGDashboardStore', { + +}) \ No newline at end of file diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 2cb4fcd9..ae852e98 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -89,8 +89,8 @@ body { padding-top: .75rem; padding-bottom: .75rem; font-size: 1rem; - background-color: rgba(0, 0, 0, .25); - box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25); + /*background-color: rgba(0, 0, 0, .25);*/ + /*box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);*/ } .navbar .navbar-toggler { @@ -468,7 +468,7 @@ main { .login-box label[for="password"] { font-size: 1rem; margin: 0 !important; - transform: translateY(30px) translateX(16px); + transform: translateY(2.1rem) translateX(1rem); padding: 0; } diff --git a/src/templates/footer.html b/src/templates/footer.html index d79b1f15..7dfb9bd9 100644 --- a/src/templates/footer.html +++ b/src/templates/footer.html @@ -1,4 +1,3 @@ - - + \ No newline at end of file diff --git a/src/templates/header.html b/src/templates/header.html index 3834eb88..14dfd1bd 100644 --- a/src/templates/header.html +++ b/src/templates/header.html @@ -11,14 +11,9 @@ - + - - {% if session["theme"] == "dark" %} - - {% endif %} - - - + + diff --git a/src/templates/index_new.html b/src/templates/index_new.html new file mode 100644 index 00000000..0a90dc67 --- /dev/null +++ b/src/templates/index_new.html @@ -0,0 +1,37 @@ + + + + + + WGDashboard + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + \ No newline at end of file diff --git a/src/templates/signin.html b/src/templates/signin.html index 0a492858..1a0bfc7a 100644 --- a/src/templates/signin.html +++ b/src/templates/signin.html @@ -11,29 +11,7 @@ {% include "navbar.html" %} - +
Version: {{ version }} {% include "footer.html" %} From f671c992e1e52d96d244820778ac149502626963 Mon Sep 17 00:00:00 2001 From: Donald Zou Date: Mon, 8 Jan 2024 12:23:57 -0500 Subject: [PATCH 030/214] testing something... --- README.md | 2 +- package-lock.json | 248 ---- package.json | 6 - src/WGDashboard_donald.zou.egg-info/PKG-INFO | 557 --------- .../SOURCES.txt | 8 - .../dependency_links.txt | 1 - .../top_level.txt | 1 - src/dashboard.py | 2 +- src/static/app/.gitignore | 30 + src/static/app/index.html | 13 + src/static/app/jsconfig.json | 8 + src/static/app/package-lock.json | 1036 +++++++++++++++++ src/static/app/package.json | 22 + src/static/app/public/favicon.ico | Bin 0 -> 4286 bytes src/static/app/src/App.vue | 12 + src/static/app/src/main.js | 17 + src/static/app/src/router/index.js | 34 + src/static/app/src/stores/counter.js | 12 + src/static/app/src/utilities/cookie.js | 9 + src/static/app/src/utilities/fetch.js | 28 + src/static/app/src/views/index.vue | 13 + src/static/app/src/views/signin.vue | 60 + src/static/app/vite.config.js | 21 + src/static/{app => app2}/app.js | 2 +- src/static/{app => app2}/cookie.js | 0 src/static/{app => app2}/index.js | 0 src/static/{app => app2}/signin/fetch.js | 0 src/static/{app => app2}/signin/signin.js | 0 src/static/{app => app2}/store.js | 0 src/templates/index_new.html | 3 +- 30 files changed, 1319 insertions(+), 826 deletions(-) delete mode 100644 package-lock.json delete mode 100644 package.json delete mode 100644 src/WGDashboard_donald.zou.egg-info/PKG-INFO delete mode 100644 src/WGDashboard_donald.zou.egg-info/SOURCES.txt delete mode 100644 src/WGDashboard_donald.zou.egg-info/dependency_links.txt delete mode 100644 src/WGDashboard_donald.zou.egg-info/top_level.txt create mode 100644 src/static/app/.gitignore create mode 100644 src/static/app/index.html create mode 100644 src/static/app/jsconfig.json create mode 100644 src/static/app/package-lock.json create mode 100644 src/static/app/package.json create mode 100644 src/static/app/public/favicon.ico create mode 100644 src/static/app/src/App.vue create mode 100644 src/static/app/src/main.js create mode 100644 src/static/app/src/router/index.js create mode 100644 src/static/app/src/stores/counter.js create mode 100644 src/static/app/src/utilities/cookie.js create mode 100644 src/static/app/src/utilities/fetch.js create mode 100644 src/static/app/src/views/index.vue create mode 100644 src/static/app/src/views/signin.vue create mode 100644 src/static/app/vite.config.js rename src/static/{app => app2}/app.js (98%) rename src/static/{app => app2}/cookie.js (100%) rename src/static/{app => app2}/index.js (100%) rename src/static/{app => app2}/signin/fetch.js (100%) rename src/static/{app => app2}/signin/signin.js (100%) rename src/static/{app => app2}/store.js (100%) diff --git a/README.md b/README.md index 44ca4dd1..93de1560 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ In the `src` folder, it contained a file called `wg-dashboard.service`, we can u └─6602 /usr/bin/python3 /root/wgdashboard/src/dashboard.py Aug 03 22:31:26 ubuntu-wg systemd[1]: Started wg-dashboard.service. - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Serving Flask app "WGDashboard" (lazy loading) + Aug 03 22:31:27 ubuntu-wg python3[6602]: * Serving Flask app1 "WGDashboard" (lazy loading) Aug 03 22:31:27 ubuntu-wg python3[6602]: * Environment: production Aug 03 22:31:27 ubuntu-wg python3[6602]: WARNING: This is a development server. Do not use it in a production deployment. Aug 03 22:31:27 ubuntu-wg python3[6602]: Use a production WSGI server instead. diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 248b0255..00000000 --- a/package-lock.json +++ /dev/null @@ -1,248 +0,0 @@ -{ - "name": "Wireguard-Dashboard", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "dependencies": { - "vue": "^3.3.9", - "vue-router": "^4.2.5" - } - }, - "node_modules/@babel/parser": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.5.tgz", - "integrity": "sha512-hOOqoiNXrmGdFbhgCzu6GiURxUgM27Xwd/aPuu8RfHEZPBzL1Z54okAHAQjXfcQNwvrlkAmAp4SlRTZ45vlthQ==", - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" - }, - "node_modules/@vue/compiler-core": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.3.9.tgz", - "integrity": "sha512-+/Lf68Vr/nFBA6ol4xOtJrW+BQWv3QWKfRwGSm70jtXwfhZNF4R/eRgyVJYoxFRhdCTk/F6g99BP0ffPgZihfQ==", - "dependencies": { - "@babel/parser": "^7.23.3", - "@vue/shared": "3.3.9", - "estree-walker": "^2.0.2", - "source-map-js": "^1.0.2" - } - }, - "node_modules/@vue/compiler-dom": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.3.9.tgz", - "integrity": "sha512-nfWubTtLXuT4iBeDSZ5J3m218MjOy42Vp2pmKVuBKo2/BLcrFUX8nCSr/bKRFiJ32R8qbdnnnBgRn9AdU5v0Sg==", - "dependencies": { - "@vue/compiler-core": "3.3.9", - "@vue/shared": "3.3.9" - } - }, - "node_modules/@vue/compiler-sfc": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.3.9.tgz", - "integrity": "sha512-wy0CNc8z4ihoDzjASCOCsQuzW0A/HP27+0MDSSICMjVIFzk/rFViezkR3dzH+miS2NDEz8ywMdbjO5ylhOLI2A==", - "dependencies": { - "@babel/parser": "^7.23.3", - "@vue/compiler-core": "3.3.9", - "@vue/compiler-dom": "3.3.9", - "@vue/compiler-ssr": "3.3.9", - "@vue/reactivity-transform": "3.3.9", - "@vue/shared": "3.3.9", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.5", - "postcss": "^8.4.31", - "source-map-js": "^1.0.2" - } - }, - "node_modules/@vue/compiler-ssr": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.3.9.tgz", - "integrity": "sha512-NO5oobAw78R0G4SODY5A502MGnDNiDjf6qvhn7zD7TJGc8XDeIEw4fg6JU705jZ/YhuokBKz0A5a/FL/XZU73g==", - "dependencies": { - "@vue/compiler-dom": "3.3.9", - "@vue/shared": "3.3.9" - } - }, - "node_modules/@vue/devtools-api": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.5.1.tgz", - "integrity": "sha512-+KpckaAQyfbvshdDW5xQylLni1asvNSGme1JFs8I1+/H5pHEhqUKMEQD/qn3Nx5+/nycBq11qAEi8lk+LXI2dA==" - }, - "node_modules/@vue/reactivity": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.3.9.tgz", - "integrity": "sha512-VmpIqlNp+aYDg2X0xQhJqHx9YguOmz2UxuUJDckBdQCNkipJvfk9yA75woLWElCa0Jtyec3lAAt49GO0izsphw==", - "dependencies": { - "@vue/shared": "3.3.9" - } - }, - "node_modules/@vue/reactivity-transform": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.3.9.tgz", - "integrity": "sha512-HnUFm7Ry6dFa4Lp63DAxTixUp8opMtQr6RxQCpDI1vlh12rkGIeYqMvJtK+IKyEfEOa2I9oCkD1mmsPdaGpdVg==", - "dependencies": { - "@babel/parser": "^7.23.3", - "@vue/compiler-core": "3.3.9", - "@vue/shared": "3.3.9", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.5" - } - }, - "node_modules/@vue/runtime-core": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.3.9.tgz", - "integrity": "sha512-xxaG9KvPm3GTRuM4ZyU8Tc+pMVzcu6eeoSRQJ9IE7NmCcClW6z4B3Ij6L4EDl80sxe/arTtQ6YmgiO4UZqRc+w==", - "dependencies": { - "@vue/reactivity": "3.3.9", - "@vue/shared": "3.3.9" - } - }, - "node_modules/@vue/runtime-dom": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.3.9.tgz", - "integrity": "sha512-e7LIfcxYSWbV6BK1wQv9qJyxprC75EvSqF/kQKe6bdZEDNValzeRXEVgiX7AHI6hZ59HA4h7WT5CGvm69vzJTQ==", - "dependencies": { - "@vue/runtime-core": "3.3.9", - "@vue/shared": "3.3.9", - "csstype": "^3.1.2" - } - }, - "node_modules/@vue/server-renderer": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.3.9.tgz", - "integrity": "sha512-w0zT/s5l3Oa3ZjtLW88eO4uV6AQFqU8X5GOgzq7SkQQu6vVr+8tfm+OI2kDBplS/W/XgCBuFXiPw6T5EdwXP0A==", - "dependencies": { - "@vue/compiler-ssr": "3.3.9", - "@vue/shared": "3.3.9" - }, - "peerDependencies": { - "vue": "3.3.9" - } - }, - "node_modules/@vue/shared": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.3.9.tgz", - "integrity": "sha512-ZE0VTIR0LmYgeyhurPTpy4KzKsuDyQbMSdM49eKkMnT5X4VfFBLysMzjIZhLEFQYjjOVVfbvUDHckwjDFiO2eA==" - }, - "node_modules/csstype": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.2.tgz", - "integrity": "sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==" - }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" - }, - "node_modules/magic-string": { - "version": "0.30.5", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", - "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.4.15" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/nanoid": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", - "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" - }, - "node_modules/postcss": { - "version": "8.4.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", - "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { - "nanoid": "^3.3.6", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/source-map-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", - "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/vue": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.3.9.tgz", - "integrity": "sha512-sy5sLCTR8m6tvUk1/ijri3Yqzgpdsmxgj6n6yl7GXXCXqVbmW2RCXe9atE4cEI6Iv7L89v5f35fZRRr5dChP9w==", - "dependencies": { - "@vue/compiler-dom": "3.3.9", - "@vue/compiler-sfc": "3.3.9", - "@vue/runtime-dom": "3.3.9", - "@vue/server-renderer": "3.3.9", - "@vue/shared": "3.3.9" - }, - "peerDependencies": { - "typescript": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/vue-router": { - "version": "4.2.5", - "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.2.5.tgz", - "integrity": "sha512-DIUpKcyg4+PTQKfFPX88UWhlagBEBEfJ5A8XDXRJLUnZOvcpMF8o/dnL90vpVkGaPbjvXazV/rC1qBKrZlFugw==", - "dependencies": { - "@vue/devtools-api": "^6.5.0" - }, - "funding": { - "url": "https://github.com/sponsors/posva" - }, - "peerDependencies": { - "vue": "^3.2.0" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index cd954bb0..00000000 --- a/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "dependencies": { - "vue": "^3.3.9", - "vue-router": "^4.2.5" - } -} diff --git a/src/WGDashboard_donald.zou.egg-info/PKG-INFO b/src/WGDashboard_donald.zou.egg-info/PKG-INFO deleted file mode 100644 index 7a99e8af..00000000 --- a/src/WGDashboard_donald.zou.egg-info/PKG-INFO +++ /dev/null @@ -1,557 +0,0 @@ -Metadata-Version: 2.1 -Name: WGDashboard-donald.zou -Version: 3.1 -Summary: Simplest dashboard for WireGuard VPN written in Python w/ Flask -Home-page: https://github.com/donaldzou/WGDashboard -Author: Donald Cheng Hong Zou -Author-email: donaldzou@live.hk -License: UNKNOWN -Project-URL: Bug Tracker, https://github.com/donaldzou/WGDashboard/issues -Platform: UNKNOWN -Classifier: Programming Language :: Python :: 3 -Classifier: License :: OSI Approved :: Apache License -Classifier: Operating System :: OS Independent -Requires-Python: >=3.7 -Description-Content-Type: text/markdown -License-File: LICENSE - -

- WGDashboard -

-

WGDashboard

- - -

- -

-

- - wakatime - -

-

Monitoring WireGuard is not convinient, need to login into server and type wg show. That's why this platform is being created, to view all configurations and manage them in a easier way.

-

Note: This project is not affiliate to the official WireGuard Project ;)

- -## 📣 What's New: v3.0 - -- 🎉 **New Features** - - **Moved from TinyDB to SQLite**: SQLite provide a better performance and loading speed when getting peers! Also avoided crashing the database due to **race condition**. - - **Added Gunicorn WSGI Server**: This could provide more stable on handling HTTP request, and more flexibility in the future (such as HTTPS support). **BIG THANKS to @pgalonza :heart:** - - **Add Peers by Bulk:** User can add peers by bulk, just simply set the amount and click add. - - **Delete Peers by Bulk**: User can delete peers by bulk, without deleting peers one by one. - - **Download Peers in Zip**: User can download all *downloadable* peers in a zip. - - **Added Pre-shared Key to peers:** Now each peer can add with a pre-shared key to enhance security. Previously added peers can add the pre-shared key through the peer setting button. - - **Redirect Back to Previous Page:** The dashboard will now redirect you back to your previous page if the current session got timed out and you need to sign in again. - - **Added Some [🥘 Experimental Functions](#-experimental-functions)** - -- 🪚 **Bug Fixed** - - [IP Sorting range issues #99](https://github.com/donaldzou/WGDashboard/issues/99) [❤️ @barryboom] - - [INvalid character written to tunnel json file #108](https://github.com/donaldzou/WGDashboard/issues/108) [❤️ @ikidd] - - [Add IPv6 #91](https://github.com/donaldzou/WGDashboard/pull/91) [❤️ @pgalonza] - - [Added MTU and PersistentKeepalive to QR code and download files #112](https://github.com/donaldzou/WGDashboard/pull/112) [:heart: @reafian] - - **And many other bugs provided by our beloved users** :heart: -- **🧐 Other Changes** - - **Key generating moved to front-end**: No longer need to use the server's WireGuard to generate keys, thanks to the `wireguard.js` from the [official repository](https://git.zx2c4.com/wireguard-tools/tree/contrib/keygen-html/wireguard.js)! - - **Peer transfer calculation**: each peer will now show all transfer amount (previously was only showing transfer amount from the last configuration start-up). - - **UI adjustment on running peers**: peers will have a new style indicating that it is running. - - **`wgd.sh` finally can update itself**: So now user could update the whole dashboard from `wgd.sh`, with the `update` command. - - **Minified JS and CSS files**: Although only a small changes on the file size, but I think is still a good practice to save a bit of bandwidth ;) - -*And many other small changes for performance and bug fixes! :laughing:* - -> If you have any other brilliant ideas for this project, please shout it in here [#129](https://github.com/donaldzou/WGDashboard/issues/129) :heart: - -**For users who is using `v2.x.x` please be sure to read [this](#please-note-for-user-who-is-using-v231-or-below) before updating WGDashboard ;)** - -
- -## Table of Content - - -- [💡 Features](#-features) -- [📝 Requirement](#-requirement) -- [🛠 Install](#-install) -- [🪜 Usage](#-usage) - - [Start/Stop/Restart WGDashboard](#startstoprestart-wgdashboard) - - [Autostart WGDashboard on boot](#autostart-wgdashboard-on-boot--v22) -- [✂️ Dashboard Configuration](#%EF%B8%8F-dashboard-configuration) - - [Dashboard Configuration file](#dashboard-configuration-file) - - [Generating QR code and peer configuration file (.conf)](#generating-qr-code-and-peer-configuration-file-conf) -- [❓ How to update the dashboard?](#-how-to-update-the-dashboard) -- [🥘 Experimental Functions](#-experimental-functions) -- [🔍 Screenshot](#-screenshot) -- [⏰ Changelog](#--changelog) -- [🛒 Dependencies](#-dependencies) -- [✨ Contributors](#-contributors) - -## 💡 Features - -- **No need to re-configure existing WireGuard configuration! It can search for existed configuration files.** -- Easy to use interface, provided username and password protection to the dashboard -- Add peers and edit (Allowed IPs, DNS, Private Key...) -- View peers and configuration real time details (Data Usage, Latest Handshakes...) -- Share your peer configuration with QR code or file download -- Testing tool: Ping and Traceroute to your peer's ip -- **And more functions are coming up!** - - -## 📝 Requirement - -- Recommend the following OS, tested by our beloved users: - - [x] Ubuntu 18.04.1 LTS - 20.04.1 LTS [@Me] - - [x] Debian GNU/Linux 10 (buster) [❤️ @[robchez](https://github.com/robchez)] - - [x] AlmaLinux 8.4 (Electric Cheetah) [❤️ @[barry-smithjr](https://github.com/)] - - [x] CentOS 7 [❤️ @[PrzemekSkw](https://github.com/PrzemekSkw)] - - > **If you have tested on other OS and it works perfectly please provide it to me in [#31](https://github.com/donaldzou/wireguard-dashboard/issues/31). Thank you!** - -- **WireGuard** and **WireGuard-Tools (`wg-quick`)** are installed. - - > Don't know how? Check this official documentation - -- Configuration files under **`/etc/wireguard`**, but please note the following sample - - ```ini - [Interface] - ... - SaveConfig = true - # Need to include this line to allow WireGuard Tool to save your configuration, - # or if you just want it to monitor your WireGuard Interface and don't need to - # make any changes with the dashboard, you can set it to false. - - [Peer] - PublicKey = abcd1234 - AllowedIPs = 1.2.3.4/32 - # Must have for each peer - ``` - -- Python 3.7+ & Pip3 - -- Browser support CSS3 and ES6 - -## 🛠 Install -1. Download WGDashboard - - ```shell - git clone -b v3.0.5 https://github.com/donaldzou/WGDashboard.git wgdashboard - -2. Open the WGDashboard folder - - ```shell - cd wgdashboard/src - ``` - -3. Install WGDashboard - - ```shell - sudo chmod u+x wgd.sh - sudo ./wgd.sh install - ``` - -4. Give read and execute permission to root of the WireGuard configuration folder, you can change the path if your configuration files are not stored in `/etc/wireguard` - - ```shell - sudo chmod -R 755 /etc/wireguard - ``` - -5. Run WGDashboard - - ```shell - ./wgd.sh start - ``` - - **Note**: - - > For [`pivpn`](https://github.com/pivpn/pivpn) user, please use `sudo ./wgd.sh start` to run if your current account does not have the permission to run `wg show` and `wg-quick`. - -6. Access dashboard - - Access your server with port `10086` (e.g. http://your_server_ip:10086), using username `admin` and password `admin`. See below how to change port and ip that the dashboard is running with. - -## 🪜 Usage - -#### Start/Stop/Restart WGDashboard - - -```shell -cd wgdashboard/src ------------------------------ -./wgd.sh start # Start the dashboard in background ------------------------------ -./wgd.sh debug # Start the dashboard in foreground (debug mode) ------------------------------ -./wgd.sh stop # Stop the dashboard ------------------------------ -./wgd.sh restart # Restart the dasboard -``` - -#### Autostart WGDashboard on boot (>= v2.2) - -In the `src` folder, it contained a file called `wg-dashboard.service`, we can use this file to let our system to autostart the dashboard after reboot. The following guide has tested on **Ubuntu**, most **Debian** based OS might be the same, but some might not. Please don't hesitate to provide your system if you have tested the autostart on another system. - -1. Changing the directory to the dashboard's directory - - ```shell - cd wgdashboard/src - ``` - -2. Get the full path of the dashboard's directory - - ```shell - pwd - #Output: /root/wgdashboard/src - ``` - - For this example, the output is `/root/wireguard-dashboard/src`, your path might be different since it depends on where you downloaded the dashboard in the first place. **Copy the the output to somewhere, we will need this in the next step.** - -3. Edit the service file, the service file is located in `wireguard-dashboard/src`, you can use other editor you like, here will be using `nano` - - ```shell - nano wg-dashboard.service - ``` - - You will see something like this: - - ```ini - [Unit] - After=network.service - - [Service] - WorkingDirectory= - ExecStart=/usr/bin/python3 /dashboard.py - Restart=always - - - [Install] - WantedBy=default.target - ``` - - Now, we need to replace both `` to the one you just copied from step 2. After doing this, the file will become something like this, your file might be different: - - ```ini - [Unit] - After=netword.service - - [Service] - WorkingDirectory=/root/wgdashboard/src - ExecStart=/usr/bin/python3 /root/wgdashboard/src/dashboard.py - Restart=always - - - [Install] - WantedBy=default.target - ``` - - **Be aware that after the value of `WorkingDirectory`, it does not have a `/` (slash).** And then save the file after you edited it - -4. Copy the service file to systemd folder - - ```bash - $ cp wg-dashboard.service /etc/systemd/system/wg-dashboard.service - ``` - - To make sure you copy the file successfully, you can use this command `cat /etc/systemd/system/wg-dashboard.service` to see if it will output the file you just edited. - -5. Enable the service - - ```bash - $ sudo chmod 664 /etc/systemd/system/wg-dashboard.service - $ sudo systemctl daemon-reload - $ sudo systemctl enable wg-dashboard.service - $ sudo systemctl start wg-dashboard.service # <-- To start the service - ``` - -6. Check if the service run correctly - - ```bash - $ sudo systemctl status wg-dashboard.service - ``` - - And you should see something like this - - ```shell - ● wg-dashboard.service - Loaded: loaded (/etc/systemd/system/wg-dashboard.service; enabled; vendor preset: enabled) - Active: active (running) since Tue 2021-08-03 22:31:26 UTC; 4s ago - Main PID: 6602 (python3) - Tasks: 1 (limit: 453) - Memory: 26.1M - CGroup: /system.slice/wg-dashboard.service - └─6602 /usr/bin/python3 /root/wgdashboard/src/dashboard.py - - Aug 03 22:31:26 ubuntu-wg systemd[1]: Started wg-dashboard.service. - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Serving Flask app "WGDashboard" (lazy loading) - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Environment: production - Aug 03 22:31:27 ubuntu-wg python3[6602]: WARNING: This is a development server. Do not use it in a production deployment. - Aug 03 22:31:27 ubuntu-wg python3[6602]: Use a production WSGI server instead. - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Debug mode: off - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Running on all addresses. - Aug 03 22:31:27 ubuntu-wg python3[6602]: WARNING: This is a development server. Do not use it in a production deployment. - Aug 03 22:31:27 ubuntu-wg python3[6602]: * Running on http://0.0.0.0:10086/ (Press CTRL+C to quit) - ``` - - If you see `Active:` followed by `active (running) since...` then it means it run correctly. - -7. Stop/Start/Restart the service - - ```bash - sudo systemctl stop wg-dashboard.service # <-- To stop the service - sudo systemctl start wg-dashboard.service # <-- To start the service - sudo systemctl restart wg-dashboard.service # <-- To restart the service - ``` - -8. **And now you can reboot your system, and use the command at step 6 to see if it will auto start after the reboot, or just simply access the dashboard through your browser. If you have any questions or problem, please report it in the issue page.** - -## ✂️ Dashboard Configuration - -#### Dashboard Configuration file - -Since version 2.0, WGDashboard will be using a configuration file called `wg-dashboard.ini`, (It will generate automatically after first time running the dashboard). More options will include in future versions, and for now it included the following configurations: - -| | Description | Default | Edit Available | -| ---------------------------- | ------------------------------------------------------------ | ---------------------------------------------------- | -------------- | -| **`[Account]`** | *Configuration on account* | | | -| `username` | Dashboard login username | `admin` | Yes | -| `password` | Password, will be hash with SHA256 | `admin` hashed in SHA256 | Yes | -| | | | | -| **`[Server]`** | *Configuration on dashboard* | | | -| `wg_conf_path` | The path of all the Wireguard configurations | `/etc/wireguard` | Yes | -| `app_ip` | IP address the dashboard will run with | `0.0.0.0` | Yes | -| `app_port` | Port the the dashboard will run with | `10086` | Yes | -| `auth_req` | Does the dashboard need authentication to access, if `auth_req = false` , user will not be access the **Setting** tab due to security consideration. **User can only edit the file directly in system**. | `true` | **No** | -| `version` | Dashboard Version | `v3.0.5` | **No** | -| `dashboard_refresh_interval` | How frequent the dashboard will refresh on the configuration page | `60000ms` | Yes | -| `dashboard_sort` | How configuration is sorting | `status` | Yes | -| | | | | -| **`[Peers]`** | *Default Settings on a new peer* | | | -| `peer_global_dns` | DNS Server | `1.1.1.1` | Yes | -| `peer_endpoint_allowed_ip` | Endpoint Allowed IP | `0.0.0.0/0` | Yes | -| `peer_display_mode` | How peer will display | `grid` | Yes | -| `remote_endpoint` | Remote Endpoint (i.e where your peers will connect to) | *depends on your server's default network interface* | Yes | -| `peer_mtu` | Maximum Transmit Unit | `1420` | | -| `peer_keep_alive` | Keep Alive | `21` | Yes | - -#### Generating QR code and peer configuration file (.conf) - -Starting version 2.2, dashboard can now generate QR code and configuration file for each peer. Here is a template of what each QR code encoded with and the same content will be inside the file: - -```ini -[Interface] -PrivateKey = QWERTYUIOPO234567890YUSDAKFH10E1B12JE129U21= -Address = 0.0.0.0/32 -DNS = 1.1.1.1 - -[Peer] -PublicKey = QWERTYUIOPO234567890YUSDAKFH10E1B12JE129U21= -AllowedIPs = 0.0.0.0/0 -Endpoint = 0.0.0.0:51820 -``` - -| | Description | Default Value | Available in Peer setting | -| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------- | -| **`[Interface]`** | | | | -| `PrivateKey` | The private key of this peer | Private key generated by WireGuard (`wg genkey`) or provided by user | Yes | -| `Address` | The `allowed_ips` of your peer | N/A | Yes | -| `DNS` | The DNS server your peer will use | `1.1.1.1` - Cloud flare DNS, you can change it when you adding the peer or in the peer setting. | Yes | -| **`[Peer]`** | | | | -| `PublicKey` | The public key of your server | N/A | No | -| `AllowedIPs` | IP ranges for which a peer will route traffic | `0.0.0.0/0` - Indicated a default route to send all internet and VPN traffic through that peer. | Yes | -| `Endpoint` | Your wireguard server ip and port, the dashboard will search for your server's default interface's ip. | `:` | Yes | - -## ❓ How to update the dashboard? - -#### **Please note for user who is using `v2.3.1` or below** - -- For user who is using `v2.3.1` or below, please notice that all data that stored in the current database will **not** transfer to the new database. This is hard decision to move from TinyDB to SQLite. But SQLite does provide a thread-safe access and TinyDB doesn't. I couldn't find a safe way to transfer the data, so you need to do them manually... Sorry about that :pensive: . But I guess this would be a great start for future development :sunglasses:. - -
- -#### Update Method 1 (For `v3.0` or above) - -1. Change your directory to `wgdashboard/src` - - ```bash - cd wgdashboard/src - ``` - -2. Update the dashboard with the following - - ```bash - ./wgd.sh update - ``` - - > If this doesn't work, please use the method below. Sorry about that :( - -#### Update Method 2 - - -1. Change your directory to `wgdashboard` - - ```shell - cd wgdashboard/src - ``` - -2. Update the dashboard - ```shell - git pull https://github.com/donaldzou/WGDashboard.git v3.0.5 --force - ``` - -3. Install - - ```shell - ./wgd.sh install - ``` - - - -Starting with `v3.0`, you can simply do `./wgd.sh update` !! (I hope, lol) - -## 🥘 Experimental Functions - -#### Progressive Web App (PWA) for WGDashboard - -- With `v3.0`, I've added a `manifest.json` into the dashboard, so user could add their dashboard as a PWA to their browser or mobile device. - - - - - -## 🔍 Screenshot - -![Sign In Page](img/SignIn.png) - -![Index Image](img/HomePage.png) - -![Configuration](img/Configuration.png) - -![Add Peer](img/AddPeer.png) - -![Edit Peer](img/EditPeer.png) - -![Delete Peer](img/DeleteBulk.png) - -![Dashboard Setting](img/DashboardSetting.png) - -![Ping](img/Ping.png) - -![Traceroute](img/Traceroute.png) - -## ⏰ Changelog - -#### v2.3.1 - Sep 8, 2021 - -- Updated dashboard's name to **WGDashboard**!! - -#### v2.3 - Sep 8, 2021 - -- 🎉 **New Features** - - **Update directly from `wgd.sh`:** Now you can update WGDashboard directly from the bash script. - - **Displaying Peers:** You can switch the display mode between list and table in the configuration page. -- 🪚 **Bug Fixed** - - [Peer DNS Validation Fails #67](issues/67): Added DNS format check. [❤️ @realfian] - - [configparser.NoSectionError: No section: 'Interface' #66](issues/66): Changed permission requirement for `etc/wireguard` from `744` to `755`. [❤️ @ramalmaty] - - [Feature request: Interface not loading when information missing #73](issues/73): Fixed when Configuration Address and Listen Port is missing will crash the dashboard. [❤️ @js32] - - [Remote Peer, MTU and PersistentKeepalives added #70](pull/70): Added MTU, remote peer and Persistent Keepalive. [❤️ @realfian] - - [Fixes DNS check to support search domain #65](pull/65): Added allow input domain into DNS. [❤️@davejlong] -- **🧐 Other Changes** - - Moved Add Peer Button into the right bottom corner. - -#### v2.2.1 - Aug 16, 2021 - -Bug Fixed: -- Added support for full subnet on Allowed IP -- Peer setting Save button - -#### v2.2 - Aug 14, 2021 - -- 🎉 **New Features** - - **Add new peers**: Now you can add peers directly on dashboard, it will generate a pair of private key and public key. You can also set its DNS, endpoint allowed IPs. Both can set a default value in the setting page. [❤️ in [#44](https://github.com/donaldzou/wireguard-dashboard/issues/44)] - - **QR Code:** You can add the private key in peer setting of your existed peer to create a QR code. Or just create a new one, dashboard will now be able to auto generate a private key and public key ;) Don't worry, all keys will be generated on your machine, and **will delete all key files after they got generated**. [❤️ in [#29](https://github.com/donaldzou/wireguard-dashboard/issues/29)] - - **Peer configuration file download:** Same as QR code, you now can download the peer configuration file, so you don't need to manually input all the details on the peer machine! [❤️ in [#40](https://github.com/donaldzou/wireguard-dashboard/issues/40)] - - **Search peers**: You can now search peers by their name. - - **Autostart on boot:** Added a tutorial on how to start the dashboard to on boot! Please read the [tutorial below](#autostart-wireguard-dashboard-on-boot). [❤️ in [#29](https://github.com/donaldzou/wireguard-dashboard/issues/29)] - - **Click to copy**: You can now click and copy all peer's public key and configuration's public key. - - .... -- 🪚 **Bug Fixed** - - When there are comments in the wireguard config file, will cause the dashboard to crash. - - Used regex to search for config files. -- **🧐 Other Changes** - - Moved all external CSS and JavaScript file to local hosting (Except Bootstrap Icon, due to large amount of SVG files). - - Updated Python dependencies - - Flask: `v1.1.2 => v2.0.1` - - Jinja: `v2.10.1 => v3.0.1` - - icmplib: `v2.1.1 => v3.0.1` - - Updated CSS/JS dependencies - - Bootstrap: `v4.5.3 => v4.6.0` - - UI adjustment - - Adjusted how peers will display in larger screens, used to be 1 row per peer, now is 3 peers in 1 row. - -#### v2.1 - Jul 2, 2021 - -- Added **Ping** and **Traceroute** tools! -- Adjusted the calculation of data usage on each peers -- Added refresh interval of the dashboard -- Bug fixed when no configuration on fresh install ([#23](https://github.com/donaldzou/wireguard-dashboard/issues/23)) -- Fixed crash when too many peers ([#22](https://github.com/donaldzou/wireguard-dashboard/issues/22)) - -#### v2.0 - May 5, 2021 - -- Added login function to dashboard - - ***I'm not using the most ideal way to store the username and password, feel free to provide a better way to do this if you any good idea!*** -- Added a config file to the dashboard -- Dashboard config can be change within the **Setting** tab on the side bar -- Adjusted UI -- And much more! - -#### v1.1.2 - Apr 3, 2021 - -- Resolved issue [#3](https://github.com/donaldzou/wireguard-dashboard/issues/3). - -#### v1.1.1 - Apr 2, 2021 - -- Able to add a friendly name to each peer. Thanks [#2](https://github.com/donaldzou/wireguard-dashboard/issues/2) ! - -#### v1.0 - Dec 27, 2020 - -- Added the function to remove peers - -## 🛒 Dependencies - -- CSS/JS - - [Bootstrap](https://getbootstrap.com/docs/4.6/getting-started/introduction/) `v4.6.0` - - [Bootstrap Icon](https://icons.getbootstrap.com) `v1.4.0` - - [jQuery](https://jquery.com) `v3.5.1` -- Python - - [Flask](https://pypi.org/project/Flask/) `v2.0.1` - - [ifcfg](https://pypi.org/project/ifcfg/) `v0.21` - - [icmplib](https://pypi.org/project/icmplib/) `v2.1.1` - - [flask-qrcode](https://pypi.org/project/Flask-QRcode/) `v3.0.0` - -## ✨ Contributors - - -[![All Contributors](https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square)](#contributors-) - - -Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): - - - - - - - - - - - - -

antonioag95

⚠️ 💻

tonjo

💻

Richard Newton

💻

David Long

💻

Markus Neubauer

💻
- - - - - - -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! - diff --git a/src/WGDashboard_donald.zou.egg-info/SOURCES.txt b/src/WGDashboard_donald.zou.egg-info/SOURCES.txt deleted file mode 100644 index ad2c179b..00000000 --- a/src/WGDashboard_donald.zou.egg-info/SOURCES.txt +++ /dev/null @@ -1,8 +0,0 @@ -LICENSE -README.md -pyproject.toml -setup.cfg -src/WGDashboard_donald.zou.egg-info/PKG-INFO -src/WGDashboard_donald.zou.egg-info/SOURCES.txt -src/WGDashboard_donald.zou.egg-info/dependency_links.txt -src/WGDashboard_donald.zou.egg-info/top_level.txt \ No newline at end of file diff --git a/src/WGDashboard_donald.zou.egg-info/dependency_links.txt b/src/WGDashboard_donald.zou.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891..00000000 --- a/src/WGDashboard_donald.zou.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/WGDashboard_donald.zou.egg-info/top_level.txt b/src/WGDashboard_donald.zou.egg-info/top_level.txt deleted file mode 100644 index 8b137891..00000000 --- a/src/WGDashboard_donald.zou.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/dashboard.py b/src/dashboard.py index 931780e5..e0036d61 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -1802,7 +1802,7 @@ def get_all_transfer_thread(): print("waiting 15 sec ") time.sleep(7) global stop_thread - # with app.app_context(): + # with app1.app_context(): try: db = connect_db() cur = db.cursor() diff --git a/src/static/app/.gitignore b/src/static/app/.gitignore new file mode 100644 index 00000000..8ee54e8d --- /dev/null +++ b/src/static/app/.gitignore @@ -0,0 +1,30 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +.DS_Store +dist +dist-ssr +coverage +*.local + +/cypress/videos/ +/cypress/screenshots/ + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +*.tsbuildinfo diff --git a/src/static/app/index.html b/src/static/app/index.html new file mode 100644 index 00000000..456879ab --- /dev/null +++ b/src/static/app/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite App + + +
+ + + diff --git a/src/static/app/jsconfig.json b/src/static/app/jsconfig.json new file mode 100644 index 00000000..5a1f2d22 --- /dev/null +++ b/src/static/app/jsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "paths": { + "@/*": ["./src/*"] + } + }, + "exclude": ["node_modules", "dist"] +} diff --git a/src/static/app/package-lock.json b/src/static/app/package-lock.json new file mode 100644 index 00000000..0aeda042 --- /dev/null +++ b/src/static/app/package-lock.json @@ -0,0 +1,1036 @@ +{ + "name": "app", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "app", + "version": "0.0.0", + "dependencies": { + "bootstrap": "^5.3.2", + "bootstrap-icons": "^1.11.2", + "pinia": "^2.1.7", + "vue": "^3.3.11", + "vue-router": "^4.2.5" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^4.5.2", + "vite": "^5.0.10" + } + }, + "node_modules/@babel/parser": { + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", + "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz", + "integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz", + "integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz", + "integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz", + "integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz", + "integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz", + "integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz", + "integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz", + "integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz", + "integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz", + "integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz", + "integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz", + "integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz", + "integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz", + "integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz", + "integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz", + "integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz", + "integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz", + "integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz", + "integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz", + "integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz", + "integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz", + "integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz", + "integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", + "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.9.2.tgz", + "integrity": "sha512-RKzxFxBHq9ysZ83fn8Iduv3A283K7zPPYuhL/z9CQuyFrjwpErJx0h4aeb/bnJ+q29GRLgJpY66ceQ/Wcsn3wA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.9.2.tgz", + "integrity": "sha512-yZ+MUbnwf3SHNWQKJyWh88ii2HbuHCFQnAYTeeO1Nb8SyEiWASEi5dQUygt3ClHWtA9My9RQAYkjvrsZ0WK8Xg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.9.2.tgz", + "integrity": "sha512-vqJ/pAUh95FLc/G/3+xPqlSBgilPnauVf2EXOQCZzhZJCXDXt/5A8mH/OzU6iWhb3CNk5hPJrh8pqJUPldN5zw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.9.2.tgz", + "integrity": "sha512-otPHsN5LlvedOprd3SdfrRNhOahhVBwJpepVKUN58L0RnC29vOAej1vMEaVU6DadnpjivVsNTM5eNt0CcwTahw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.9.2.tgz", + "integrity": "sha512-ewG5yJSp+zYKBYQLbd1CUA7b1lSfIdo9zJShNTyc2ZP1rcPrqyZcNlsHgs7v1zhgfdS+kW0p5frc0aVqhZCiYQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.9.2.tgz", + "integrity": "sha512-pL6QtV26W52aCWTG1IuFV3FMPL1m4wbsRG+qijIvgFO/VBsiXJjDPE/uiMdHBAO6YcpV4KvpKtd0v3WFbaxBtg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.9.2.tgz", + "integrity": "sha512-On+cc5EpOaTwPSNetHXBuqylDW+765G/oqB9xGmWU3npEhCh8xu0xqHGUA+4xwZLqBbIZNcBlKSIYfkBm6ko7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.9.2.tgz", + "integrity": "sha512-Wnx/IVMSZ31D/cO9HSsU46FjrPWHqtdF8+0eyZ1zIB5a6hXaZXghUKpRrC4D5DcRTZOjml2oBhXoqfGYyXKipw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.9.2.tgz", + "integrity": "sha512-ym5x1cj4mUAMBummxxRkI4pG5Vht1QMsJexwGP8547TZ0sox9fCLDHw9KCH9c1FO5d9GopvkaJsBIOkTKxksdw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.9.2.tgz", + "integrity": "sha512-m0hYELHGXdYx64D6IDDg/1vOJEaiV8f1G/iO+tejvRCJNSwK4jJ15e38JQy5Q6dGkn1M/9KcyEOwqmlZ2kqaZg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.9.2.tgz", + "integrity": "sha512-x1CWburlbN5JjG+juenuNa4KdedBdXLjZMp56nHFSHTOsb/MI2DYiGzLtRGHNMyydPGffGId+VgjOMrcltOksA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.9.2.tgz", + "integrity": "sha512-VVzCB5yXR1QlfsH1Xw1zdzQ4Pxuzv+CPr5qpElpKhVxlxD3CRdfubAG9mJROl6/dmj5gVYDDWk8sC+j9BI9/kQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.9.2.tgz", + "integrity": "sha512-SYRedJi+mweatroB+6TTnJYLts0L0bosg531xnQWtklOI6dezEagx4Q0qDyvRdK+qgdA3YZpjjGuPFtxBmddBA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vitejs/plugin-vue": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-4.6.2.tgz", + "integrity": "sha512-kqf7SGFoG+80aZG6Pf+gsZIVvGSCKE98JbiWqcCV9cThtg91Jav0yvYFC9Zb+jKetNGF6ZKeoaxgZfND21fWKw==", + "dev": true, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.0.0 || ^5.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.3.tgz", + "integrity": "sha512-u8jzgFg0EDtSrb/hG53Wwh1bAOQFtc1ZCegBpA/glyvTlgHl+tq13o1zvRfLbegYUw/E4mSTGOiCnAJ9SJ+lsg==", + "dependencies": { + "@babel/parser": "^7.23.6", + "@vue/shared": "3.4.3", + "entities": "^4.5.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.3.tgz", + "integrity": "sha512-oGF1E9/htI6JWj/lTJgr6UgxNCtNHbM6xKVreBWeZL9QhRGABRVoWGAzxmtBfSOd+w0Zi5BY0Es/tlJrN6WgEg==", + "dependencies": { + "@vue/compiler-core": "3.4.3", + "@vue/shared": "3.4.3" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.3.tgz", + "integrity": "sha512-NuJqb5is9I4uzv316VRUDYgIlPZCG8D+ARt5P4t5UDShIHKL25J3TGZAUryY/Aiy0DsY7srJnZL5ryB6DD63Zw==", + "dependencies": { + "@babel/parser": "^7.23.6", + "@vue/compiler-core": "3.4.3", + "@vue/compiler-dom": "3.4.3", + "@vue/compiler-ssr": "3.4.3", + "@vue/shared": "3.4.3", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.5", + "postcss": "^8.4.32", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.3.tgz", + "integrity": "sha512-wnYQtMBkeFSxgSSQbYGQeXPhQacQiog2c6AlvMldQH6DB+gSXK/0F6DVXAJfEiuBSgBhUc8dwrrG5JQcqwalsA==", + "dependencies": { + "@vue/compiler-dom": "3.4.3", + "@vue/shared": "3.4.3" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.5.1.tgz", + "integrity": "sha512-+KpckaAQyfbvshdDW5xQylLni1asvNSGme1JFs8I1+/H5pHEhqUKMEQD/qn3Nx5+/nycBq11qAEi8lk+LXI2dA==" + }, + "node_modules/@vue/reactivity": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.4.3.tgz", + "integrity": "sha512-q5f9HLDU+5aBKizXHAx0w4whkIANs1Muiq9R5YXm0HtorSlflqv9u/ohaMxuuhHWCji4xqpQ1eL04WvmAmGnFg==", + "dependencies": { + "@vue/shared": "3.4.3" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.4.3.tgz", + "integrity": "sha512-C1r6QhB1qY7D591RCSFhMULyzL9CuyrGc+3PpB0h7dU4Qqw6GNyo4BNFjHZVvsWncrUlKX3DIKg0Y7rNNr06NQ==", + "dependencies": { + "@vue/reactivity": "3.4.3", + "@vue/shared": "3.4.3" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.4.3.tgz", + "integrity": "sha512-wrsprg7An5Ec+EhPngWdPuzkp0BEUxAKaQtN9dPU/iZctPyD9aaXmVtehPJerdQxQale6gEnhpnfywNw3zOv2A==", + "dependencies": { + "@vue/runtime-core": "3.4.3", + "@vue/shared": "3.4.3", + "csstype": "^3.1.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.4.3.tgz", + "integrity": "sha512-BUxt8oVGMKKsqSkM1uU3d3Houyfy4WAc2SpSQRebNd+XJGATVkW/rO129jkyL+kpB/2VRKzE63zwf5RtJ3XuZw==", + "dependencies": { + "@vue/compiler-ssr": "3.4.3", + "@vue/shared": "3.4.3" + }, + "peerDependencies": { + "vue": "3.4.3" + } + }, + "node_modules/@vue/shared": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.3.tgz", + "integrity": "sha512-rIwlkkP1n4uKrRzivAKPZIEkHiuwY5mmhMJ2nZKCBLz8lTUlE73rQh4n1OnnMurXt1vcUNyH4ZPfdh8QweTjpQ==" + }, + "node_modules/bootstrap": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.3.2.tgz", + "integrity": "sha512-D32nmNWiQHo94BKHLmOrdjlL05q1c8oxbtBphQFb9Z5to6eGRDCm0QgeaZ4zFBHzfg2++rqa2JkqCcxDy0sH0g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/twbs" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/bootstrap" + } + ], + "peerDependencies": { + "@popperjs/core": "^2.11.8" + } + }, + "node_modules/bootstrap-icons": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/bootstrap-icons/-/bootstrap-icons-1.11.2.tgz", + "integrity": "sha512-TgdiPv+IM9tgDb+dsxrnGIyocsk85d2M7T0qIgkvPedZeoZfyeG/j+yiAE4uHCEayKef2RP05ahQ0/e9Sv75Wg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/twbs" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/bootstrap" + } + ] + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz", + "integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.11", + "@esbuild/android-arm": "0.19.11", + "@esbuild/android-arm64": "0.19.11", + "@esbuild/android-x64": "0.19.11", + "@esbuild/darwin-arm64": "0.19.11", + "@esbuild/darwin-x64": "0.19.11", + "@esbuild/freebsd-arm64": "0.19.11", + "@esbuild/freebsd-x64": "0.19.11", + "@esbuild/linux-arm": "0.19.11", + "@esbuild/linux-arm64": "0.19.11", + "@esbuild/linux-ia32": "0.19.11", + "@esbuild/linux-loong64": "0.19.11", + "@esbuild/linux-mips64el": "0.19.11", + "@esbuild/linux-ppc64": "0.19.11", + "@esbuild/linux-riscv64": "0.19.11", + "@esbuild/linux-s390x": "0.19.11", + "@esbuild/linux-x64": "0.19.11", + "@esbuild/netbsd-x64": "0.19.11", + "@esbuild/openbsd-x64": "0.19.11", + "@esbuild/sunos-x64": "0.19.11", + "@esbuild/win32-arm64": "0.19.11", + "@esbuild/win32-ia32": "0.19.11", + "@esbuild/win32-x64": "0.19.11" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", + "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" + }, + "node_modules/pinia": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-2.1.7.tgz", + "integrity": "sha512-+C2AHFtcFqjPih0zpYuvof37SFxMQ7OEG2zV9jRI12i9BOy3YQVAHwdKtyyc8pDcDyIc33WCIsZaCFWU7WWxGQ==", + "dependencies": { + "@vue/devtools-api": "^6.5.0", + "vue-demi": ">=0.14.5" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "@vue/composition-api": "^1.4.0", + "typescript": ">=4.4.4", + "vue": "^2.6.14 || ^3.3.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/pinia/node_modules/vue-demi": { + "version": "0.14.6", + "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.6.tgz", + "integrity": "sha512-8QA7wrYSHKaYgUxDA5ZC24w+eHm3sYCbp0EzcDwKqN3p6HqtTCGR/GVsPyZW92unff4UlcSh++lmqDWN3ZIq4w==", + "hasInstallScript": true, + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/postcss": { + "version": "8.4.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.32.tgz", + "integrity": "sha512-D/kj5JNu6oo2EIy+XL/26JEDTlIbB8hw85G8StOE6L74RQAVVP5rej6wxCNqyMbR4RkPfqvezVbPw81Ngd6Kcw==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.9.2.tgz", + "integrity": "sha512-66RB8OtFKUTozmVEh3qyNfH+b+z2RXBVloqO2KCC/pjFaGaHtxP9fVfOQKPSGXg2mElmjmxjW/fZ7iKrEpMH5Q==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.9.2", + "@rollup/rollup-android-arm64": "4.9.2", + "@rollup/rollup-darwin-arm64": "4.9.2", + "@rollup/rollup-darwin-x64": "4.9.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.9.2", + "@rollup/rollup-linux-arm64-gnu": "4.9.2", + "@rollup/rollup-linux-arm64-musl": "4.9.2", + "@rollup/rollup-linux-riscv64-gnu": "4.9.2", + "@rollup/rollup-linux-x64-gnu": "4.9.2", + "@rollup/rollup-linux-x64-musl": "4.9.2", + "@rollup/rollup-win32-arm64-msvc": "4.9.2", + "@rollup/rollup-win32-ia32-msvc": "4.9.2", + "@rollup/rollup-win32-x64-msvc": "4.9.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/vite": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.0.10.tgz", + "integrity": "sha512-2P8J7WWgmc355HUMlFrwofacvr98DAjoE52BfdbwQtyLH06XKwaL/FMnmKM2crF0iX4MpmMKoDlNCB1ok7zHCw==", + "dev": true, + "dependencies": { + "esbuild": "^0.19.3", + "postcss": "^8.4.32", + "rollup": "^4.2.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vue": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.4.3.tgz", + "integrity": "sha512-GjN+culMAGv/mUbkIv8zMKItno8npcj5gWlXkSxf1SPTQf8eJ4A+YfHIvQFyL1IfuJcMl3soA7SmN1fRxbf/wA==", + "dependencies": { + "@vue/compiler-dom": "3.4.3", + "@vue/compiler-sfc": "3.4.3", + "@vue/runtime-dom": "3.4.3", + "@vue/server-renderer": "3.4.3", + "@vue/shared": "3.4.3" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.2.5.tgz", + "integrity": "sha512-DIUpKcyg4+PTQKfFPX88UWhlagBEBEfJ5A8XDXRJLUnZOvcpMF8o/dnL90vpVkGaPbjvXazV/rC1qBKrZlFugw==", + "dependencies": { + "@vue/devtools-api": "^6.5.0" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.2.0" + } + } + } +} diff --git a/src/static/app/package.json b/src/static/app/package.json new file mode 100644 index 00000000..ca65f0c7 --- /dev/null +++ b/src/static/app/package.json @@ -0,0 +1,22 @@ +{ + "name": "app", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "bootstrap": "^5.3.2", + "bootstrap-icons": "^1.11.2", + "pinia": "^2.1.7", + "vue": "^3.3.11", + "vue-router": "^4.2.5" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^4.5.2", + "vite": "^5.0.10" + } +} diff --git a/src/static/app/public/favicon.ico b/src/static/app/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..df36fcfb72584e00488330b560ebcf34a41c64c2 GIT binary patch literal 4286 zcmds*O-Phc6o&64GDVCEQHxsW(p4>LW*W<827=Unuo8sGpRux(DN@jWP-e29Wl%wj zY84_aq9}^Am9-cWTD5GGEo#+5Fi2wX_P*bo+xO!)p*7B;iKlbFd(U~_d(U?#hLj56 zPhFkj-|A6~Qk#@g^#D^U0XT1cu=c-vu1+SElX9NR;kzAUV(q0|dl0|%h|dI$%VICy zJnu2^L*Te9JrJMGh%-P79CL0}dq92RGU6gI{v2~|)p}sG5x0U*z<8U;Ij*hB9z?ei z@g6Xq-pDoPl=MANPiR7%172VA%r)kevtV-_5H*QJKFmd;8yA$98zCxBZYXTNZ#QFk2(TX0;Y2dt&WitL#$96|gJY=3xX zpCoi|YNzgO3R`f@IiEeSmKrPSf#h#Qd<$%Ej^RIeeYfsxhPMOG`S`Pz8q``=511zm zAm)MX5AV^5xIWPyEu7u>qYs?pn$I4nL9J!=K=SGlKLXpE<5x+2cDTXq?brj?n6sp= zphe9;_JHf40^9~}9i08r{XM$7HB!`{Ys~TK0kx<}ZQng`UPvH*11|q7&l9?@FQz;8 zx!=3<4seY*%=OlbCbcae?5^V_}*K>Uo6ZWV8mTyE^B=DKy7-sdLYkR5Z?paTgK-zyIkKjIcpyO z{+uIt&YSa_$QnN_@t~L014dyK(fOOo+W*MIxbA6Ndgr=Y!f#Tokqv}n<7-9qfHkc3 z=>a|HWqcX8fzQCT=dqVbogRq!-S>H%yA{1w#2Pn;=e>JiEj7Hl;zdt-2f+j2%DeVD zsW0Ab)ZK@0cIW%W7z}H{&~yGhn~D;aiP4=;m-HCo`BEI+Kd6 z={Xwx{TKxD#iCLfl2vQGDitKtN>z|-AdCN|$jTFDg0m3O`WLD4_s#$S literal 0 HcmV?d00001 diff --git a/src/static/app/src/App.vue b/src/static/app/src/App.vue new file mode 100644 index 00000000..c0c4ebec --- /dev/null +++ b/src/static/app/src/App.vue @@ -0,0 +1,12 @@ + + + \ No newline at end of file diff --git a/src/static/app/src/main.js b/src/static/app/src/main.js new file mode 100644 index 00000000..07024e56 --- /dev/null +++ b/src/static/app/src/main.js @@ -0,0 +1,17 @@ +import '../../css/dashboard.css' +import 'bootstrap/dist/css/bootstrap.css' +import 'bootstrap/dist/js/bootstrap.js' +import 'bootstrap-icons/font/bootstrap-icons.css' + +import { createApp } from 'vue' +import { createPinia } from 'pinia' + +import App from './App.vue' +import router from './router' + +const app = createApp(App) + +app.use(createPinia()) +app.use(router) + +app.mount('#app') diff --git a/src/static/app/src/router/index.js b/src/static/app/src/router/index.js new file mode 100644 index 00000000..8c424bff --- /dev/null +++ b/src/static/app/src/router/index.js @@ -0,0 +1,34 @@ +import { createRouter, createWebHashHistory } from 'vue-router' +import {cookie} from "../utilities/cookie.js"; +import Index from "@/views/index.vue" +import Signin from "@/views/signin.vue"; + +const router = createRouter({ + history: createWebHashHistory(), + routes: [ + { + path: '/', + component: Index, + meta: { + requiresAuth: true + } + }, + { + path: '/signin', component: Signin + } + ] +}); + +router.beforeEach((to, from, next) => { + if (to.meta.requiresAuth){ + if (cookie.getCookie("auth")){ + next() + }else{ + next("/signin") + } + }else { + next(); + } +}); + +export default router diff --git a/src/static/app/src/stores/counter.js b/src/static/app/src/stores/counter.js new file mode 100644 index 00000000..b6757ba5 --- /dev/null +++ b/src/static/app/src/stores/counter.js @@ -0,0 +1,12 @@ +import { ref, computed } from 'vue' +import { defineStore } from 'pinia' + +export const useCounterStore = defineStore('counter', () => { + const count = ref(0) + const doubleCount = computed(() => count.value * 2) + function increment() { + count.value++ + } + + return { count, doubleCount, increment } +}) diff --git a/src/static/app/src/utilities/cookie.js b/src/static/app/src/utilities/cookie.js new file mode 100644 index 00000000..03657e5a --- /dev/null +++ b/src/static/app/src/utilities/cookie.js @@ -0,0 +1,9 @@ +export const cookie = { + + //https://stackoverflow.com/a/15724300 + getCookie(name) { + const value = `; ${document.cookie}`; + const parts = value.split(`; ${name}=`); + if (parts.length === 2) return parts.pop().split(';').shift(); + } +} \ No newline at end of file diff --git a/src/static/app/src/utilities/fetch.js b/src/static/app/src/utilities/fetch.js new file mode 100644 index 00000000..1b546936 --- /dev/null +++ b/src/static/app/src/utilities/fetch.js @@ -0,0 +1,28 @@ +export const fetchGet = async (url, params=undefined, callback=undefined) => { + const urlSearchParams = new URLSearchParams(params); + await fetch(`${url}?${urlSearchParams.toString()}}`, { + headers: { + "content-type": "application/json" + } + }) + .then(x => x.json()) + .then(x => callback ? callback(x) : undefined) + .catch(() => { + alert("Error occurred! Check console") + }); +} + +export const fetchPost = async (url, body, callback) => { + await fetch(`${url}`, { + headers: { + "content-type": "application/json" + }, + method: "POST", + body: JSON.stringify(body) + }) + .then(x => x.json()) + .then(x => callback ? callback(x) : undefined) + // .catch(() => { + // alert("Error occurred! Check console") + // }); +} \ No newline at end of file diff --git a/src/static/app/src/views/index.vue b/src/static/app/src/views/index.vue new file mode 100644 index 00000000..fa83de88 --- /dev/null +++ b/src/static/app/src/views/index.vue @@ -0,0 +1,13 @@ + + + + + \ No newline at end of file diff --git a/src/static/app/src/views/signin.vue b/src/static/app/src/views/signin.vue new file mode 100644 index 00000000..c9621e58 --- /dev/null +++ b/src/static/app/src/views/signin.vue @@ -0,0 +1,60 @@ + + + + + \ No newline at end of file diff --git a/src/static/app/vite.config.js b/src/static/app/vite.config.js new file mode 100644 index 00000000..c4f155c3 --- /dev/null +++ b/src/static/app/vite.config.js @@ -0,0 +1,21 @@ +import { fileURLToPath, URL } from 'node:url' + +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vue(), + ], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)) + } + }, + server:{ + proxy: { + '/': 'http://178.128.231.4:10086/' + } + } +}) diff --git a/src/static/app/app.js b/src/static/app2/app.js similarity index 98% rename from src/static/app/app.js rename to src/static/app2/app.js index 75eda86e..48bb6ad9 100644 --- a/src/static/app/app.js +++ b/src/static/app2/app.js @@ -48,4 +48,4 @@ router.beforeEach((to, from, next) => { app.use(router); app.use(pinia) -app.mount('#app'); \ No newline at end of file +app.mount('#app1'); \ No newline at end of file diff --git a/src/static/app/cookie.js b/src/static/app2/cookie.js similarity index 100% rename from src/static/app/cookie.js rename to src/static/app2/cookie.js diff --git a/src/static/app/index.js b/src/static/app2/index.js similarity index 100% rename from src/static/app/index.js rename to src/static/app2/index.js diff --git a/src/static/app/signin/fetch.js b/src/static/app2/signin/fetch.js similarity index 100% rename from src/static/app/signin/fetch.js rename to src/static/app2/signin/fetch.js diff --git a/src/static/app/signin/signin.js b/src/static/app2/signin/signin.js similarity index 100% rename from src/static/app/signin/signin.js rename to src/static/app2/signin/signin.js diff --git a/src/static/app/store.js b/src/static/app2/store.js similarity index 100% rename from src/static/app/store.js rename to src/static/app2/store.js diff --git a/src/templates/index_new.html b/src/templates/index_new.html index 0a90dc67..30782886 100644 --- a/src/templates/index_new.html +++ b/src/templates/index_new.html @@ -32,6 +32,5 @@ - - + \ No newline at end of file From 864f82ba11395abb43e8086e1248ef850e29924c Mon Sep 17 00:00:00 2001 From: Donald Zou Date: Tue, 9 Jan 2024 00:25:47 -0500 Subject: [PATCH 031/214] Started to refactor dashboard.py with dashboard_new.py and trying really hard to figure out sqlalchemy lol --- src/dashboard.py | 49 +- src/dashboard_new.py | 197 ++++ src/static/app/index.html | 2 +- src/static/app/public/dashboard.css | 934 ++++++++++++++++++ src/static/app/src/App.vue | 3 +- src/static/app/src/components/navbar.vue | 43 + src/static/app/src/router/index.js | 12 +- .../app/src/views/configurationList.vue | 13 + src/static/app/src/views/index.vue | 14 +- src/static/app/src/views/signin.vue | 47 +- src/static/app/vite.config.js | 2 +- src/static/css/dashboard.css | 60 +- 12 files changed, 1310 insertions(+), 66 deletions(-) create mode 100644 src/dashboard_new.py create mode 100644 src/static/app/public/dashboard.css create mode 100644 src/static/app/src/components/navbar.vue create mode 100644 src/static/app/src/views/configurationList.vue diff --git a/src/dashboard.py b/src/dashboard.py index e0036d61..72a47a04 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -288,9 +288,6 @@ def get_transfer(config_name): # {round(cumulative_sent + cumulative_receive, 4)}, '{now_string}') # ''') - - - def get_endpoint(config_name): """ Get endpoint from all peers of a configuration @@ -310,8 +307,6 @@ def get_endpoint(config_name): % (data_usage[count + 1], data_usage[count])) count += 2 - - def get_allowed_ip(conf_peer_data, config_name): """ Get allowed ips from all peers of a configuration @@ -324,8 +319,6 @@ def get_allowed_ip(conf_peer_data, config_name): g.cur.execute("UPDATE " + config_name + " SET allowed_ip = '%s' WHERE id = '%s'" % (i.get('AllowedIPs', '(None)'), i["PublicKey"])) - - def get_all_peers_data(config_name): """ Look for new peers from WireGuard @@ -488,7 +481,6 @@ def get_conf_total_data(config_name): download_total = round(download_total, 4) return [total, upload_total, download_total] - def get_conf_status(config_name): """ Check if the configuration is running or not @@ -690,9 +682,8 @@ def auth_req(): @return: Redirect """ return None - - if getattr(g, 'db', None) is None: + print('hi') g.db = connect_db() g.cur = g.db.cursor() conf = get_dashboard_conf() @@ -781,6 +772,7 @@ def auth(): return jsonify({"status": False, "msg": "Username or Password is incorrect."}) + """ Index Page """ @@ -796,8 +788,8 @@ def index(): if "switch_msg" in session: msg = session["switch_msg"] session.pop("switch_msg") - return render_template('index_new.html') - # return render_template('index.html', conf=get_conf_list(), msg=msg) + # return render_template('index_new.html') + return render_template('index.html', conf=get_conf_list(), msg=msg) # Setting Page @@ -1787,6 +1779,37 @@ def traceroute_ip(): return jsonify(returnjson) except Exception: return "Error" + +### NEW API ROUTES + +@app.route('/api/authenticate', methods=['POST']) +def api_auth(): + """ + Authentication request + @return: json object indicating verifying + """ + data = request.get_json() + config = get_dashboard_conf() + password = hashlib.sha256(data['password'].encode()) + if password.hexdigest() == config["Account"]["password"] \ + and data['username'] == config["Account"]["username"]: + session['username'] = data['username'] + resp = jsonify(ResponseObject(True)) + resp.set_cookie("authToken", hashlib.sha256(f"{data['username']}{datetime.now()}".encode()).hexdigest()) + session.permanent = True + config.clear() + return resp + + config.clear() + return jsonify(ResponseObject(False, "Username or password in incorrect.")) + + +def ResponseObject(status = True, message = None, data = None) -> dict: + return { + "status": status, + "message": message, + "data": data + } import atexit @@ -1911,8 +1934,6 @@ def init_dashboard(): """ Create dashboard default configuration. """ - - # Set Default INI File if not os.path.isfile(DASHBOARD_CONF): open(DASHBOARD_CONF, "w+").close() diff --git a/src/dashboard_new.py b/src/dashboard_new.py new file mode 100644 index 00000000..7a893752 --- /dev/null +++ b/src/dashboard_new.py @@ -0,0 +1,197 @@ +from crypt import methods +import sqlite3 +import configparser +import hashlib +import ipaddress +import json +# Python Built-in Library +import os +import secrets +import subprocess +import time +import re +import urllib.parse +import urllib.request +import urllib.error +from datetime import datetime, timedelta +from operator import itemgetter +# PIP installed library +import ifcfg +from flask import Flask, request, render_template, redirect, url_for, session, jsonify, g +from flask_qrcode import QRcode +from icmplib import ping, traceroute + +# Import other python files +import threading + +from sqlalchemy.orm import mapped_column, declarative_base, Session +from sqlalchemy import FLOAT, INT, VARCHAR, select, MetaData +from sqlalchemy import create_engine + +DASHBOARD_VERSION = 'v3.1' +CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.') +DB_PATH = os.path.join(CONFIGURATION_PATH, 'db') +if not os.path.isdir(DB_PATH): + os.mkdir(DB_PATH) +DASHBOARD_CONF = os.path.join(CONFIGURATION_PATH, 'wg-dashboard.ini') + +# WireGuard's configuration path +WG_CONF_PATH = None +# Dashboard Config Name +# Upgrade Required +UPDATE = None +# Flask App Configuration +app = Flask("WGDashboard") +app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 5206928 +app.secret_key = secrets.token_urlsafe(32) +# Enable QR Code Generator +QRcode(app) + +''' +Classes +''' +Base = declarative_base() + + +class DashboardConfig: + + def __init__(self): + self.__config = configparser.ConfigParser(strict=False) + self.__config.read(DASHBOARD_CONF) + self.__default = { + "Account": { + "username": "admin", + "password": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" + }, + "Server": { + "wg_conf_path": "/etc/wireguard", + "app_ip": "0.0.0.0", + "app_port": "10086", + "auth_req": "true", + "version": DASHBOARD_VERSION, + "dashboard_refresh_interval": "60000", + "dashboard_sort": "status", + "dashboard_theme": "light" + }, + "Peers": { + "peer_global_DNS": "1.1.1.1", + "peer_endpoint_allowed_ip": "0.0.0.0/0", + "peer_display_mode": "grid", + "remote_endpoint": ifcfg.default_interface()['inet'], + "peer_MTU": "1420", + "peer_keep_alive": "21" + } + } + + for section, keys in self.__default.items(): + for key, value in keys.items(): + exist, currentData = self.GetConfig(section, key) + if not exist: + self.SetConfig(section, key, value) + + def SetConfig(self, section: str, key: str, value: any) -> bool: + if section not in self.__config: + self.__config[section] = {} + self.__config[section][key] = value + return self.SaveConfig() + + def SaveConfig(self) -> bool: + try: + with open(DASHBOARD_CONF, "w+", encoding='utf-8') as configFile: + self.__config.write(configFile) + return True + except Exception as e: + return False + + def GetConfig(self, section, key) -> [any, bool]: + if section not in self.__config: + return False, None + + if key not in self.__config[section]: + return False, None + + return True, self.__config[section][key] + + +def ResponseObject(status=True, message=None, data=None) -> dict: + return { + "status": status, + "message": message, + "data": data + } + + +DashboardConfig = DashboardConfig() + +''' +Private Functions +''' + + +def _createPeerModel(wgConfigName): + class Peer(Base): + __tablename__ = wgConfigName + id = mapped_column(VARCHAR, primary_key=True) + private_key = mapped_column(VARCHAR) + DNS = mapped_column(VARCHAR) + endpoint_allowed_ip = mapped_column(VARCHAR) + name = mapped_column(VARCHAR) + total_receive = mapped_column(FLOAT) + total_sent = mapped_column(FLOAT) + total_data = mapped_column(FLOAT) + endpoint = mapped_column(VARCHAR) + status = mapped_column(VARCHAR) + latest_handshake = mapped_column(VARCHAR) + allowed_ip = mapped_column(VARCHAR) + cumu_receive = mapped_column(FLOAT) + cumu_sent = mapped_column(FLOAT) + cumu_data = mapped_column(FLOAT) + mtu = mapped_column(INT) + keepalive = mapped_column(INT) + remote_endpoint = mapped_column(VARCHAR) + preshared_key = mapped_column(VARCHAR) + + return Peer + + +def _regexMatch(regex, text): + pattern = re.compile(regex) + return pattern.search(text) is not None + + +def _getConfigurationList(): + conf = [] + for i in os.listdir(WG_CONF_PATH): + if _regexMatch("^(.{1,}).(conf)$", i): + i = i.replace('.conf', '') + _createPeerModel(i).__table__.create(engine) + _createPeerModel(i + "_restrict_access").__table__.create(engine) + + +''' +API Routes +''' + + +@app.route('/api/authenticate', methods=['POST']) +def API_AuthenticateLogin(): + data = request.get_json() + password = hashlib.sha256(data['password'].encode()) + print() + if password.hexdigest() == DashboardConfig.GetConfig("Account", "password")[1] \ + and data['username'] == DashboardConfig.GetConfig("Account", "username")[1]: + session['username'] = data['username'] + resp = jsonify(ResponseObject(True)) + resp.set_cookie("authToken", + hashlib.sha256(f"{data['username']}{datetime.now()}".encode()).hexdigest()) + session.permanent = True + return resp + return jsonify(ResponseObject(False, "Username or password is incorrect.")) + + +if __name__ == "__main__": + engine = create_engine("sqlite:///" + os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db')) + _, app_ip = DashboardConfig.GetConfig("Server", "app_ip") + _, app_port = DashboardConfig.GetConfig("Server", "app_port") + _getConfigurationList() + app.run(host=app_ip, debug=False, port=app_port) diff --git a/src/static/app/index.html b/src/static/app/index.html index 456879ab..8e026c5e 100644 --- a/src/static/app/index.html +++ b/src/static/app/index.html @@ -8,6 +8,6 @@
- + diff --git a/src/static/app/public/dashboard.css b/src/static/app/public/dashboard.css new file mode 100644 index 00000000..40ff23df --- /dev/null +++ b/src/static/app/public/dashboard.css @@ -0,0 +1,934 @@ +body { + font-size: .875rem; + /*font-family: 'Poppins', sans-serif;*/ +} + +.codeFont{ + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; +} + +.feather { + width: 16px; + height: 16px; + vertical-align: text-bottom; +} + +.btn-primary { + font-weight: bold; +} + +/* + * Sidebar + */ + +/*.sidebar {*/ +/* position: fixed;*/ +/* top: 0;*/ +/* bottom: 0;*/ +/* left: 0;*/ +/* z-index: 100;*/ +/* !* Behind the navbar *!*/ +/* padding: 48px 0 0;*/ +/* !* Height of navbar *!*/ +/* box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);*/ +/*}*/ + +/*.sidebar-sticky {*/ +/* position: relative;*/ +/* top: 0;*/ +/* height: calc(100vh - 48px);*/ +/* padding-top: .5rem;*/ +/* overflow-x: hidden;*/ +/* overflow-y: auto;*/ +/* !* Scrollable contents if viewport is shorter than content. *!*/ +/*}*/ + +/*@supports ((position: -webkit-sticky) or (position: sticky)) {*/ +/* .sidebar-sticky {*/ +/* position: -webkit-sticky;*/ +/* position: sticky;*/ +/* }*/ +/*}*/ + +.sidebar .nav-link, .bottomNavContainer .nav-link{ + font-weight: 500; + color: #333; + transition: 0.2s cubic-bezier(0.82, -0.07, 0, 1.01); +} + +.nav-link:hover { + padding-left: 30px; + background-color: #dfdfdf; +} + +.sidebar .nav-link .feather { + margin-right: 4px; + color: #999; +} + +.sidebar .nav-link.active, .bottomNavContainer .nav-link.active { + color: #007bff; +} + +.sidebar .nav-link:hover .feather, +.sidebar .nav-link.active .feather { + color: inherit; +} + +.sidebar-heading { + font-size: .75rem; + text-transform: uppercase; +} + + +/* + * Navbar + */ + +.navbar-brand { + padding-top: .75rem; + padding-bottom: .75rem; + font-size: 1rem; + /*background-color: rgba(0, 0, 0, .25);*/ + /*box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);*/ +} + +.navbar .navbar-toggler { + top: .25rem; + right: 1rem; +} + +.form-control { + transition: all 0.2s ease-in-out; +} + +.form-control:disabled { + cursor: not-allowed; +} + +.navbar .form-control { + padding: .75rem 1rem; + border-width: 0; + border-radius: 0; +} + +.form-control-dark { + color: #fff; + background-color: rgba(255, 255, 255, .1); + border-color: rgba(255, 255, 255, .1); +} + +.form-control-dark:focus { + border-color: transparent; + box-shadow: 0 0 0 3px rgba(255, 255, 255, .25); +} + +.dot { + width: 10px; + height: 10px; + border-radius: 50px; + display: inline-block; + margin-left: auto !important; +} + +.dot-running { + background-color: #28a745!important; + box-shadow: 0 0 0 0.2rem #28a74545; +} + +.h6-dot-running { + margin-left: 0.3rem; +} + +.dot-stopped { + background-color: #6c757d!important; +} + +.card-running { + border-color: #28a745; +} + +.info h6 { + line-break: anywhere; + transition: all 0.4s cubic-bezier(0.96, -0.07, 0.34, 1.01); + opacity: 1; +} + +.info .row .col-sm { + display: flex; + flex-direction: column; +} + +.info .row .col-sm small { + display: flex; +} + +.info .row .col-sm small strong:last-child(1) { + margin-left: auto !important; +} + +.btn-control { + border: none !important; + padding: 0; + margin: 0 1rem 0 0; +} + +.btn-control:hover{ + background-color: transparent !important; +} + +.btn-control:active, +.btn-control:focus { + background-color: transparent !important; + border: none !important; + box-shadow: none; +} + +.btn-qrcode-peer { + padding: 0 !important; +} + +.btn-qrcode-peer:active, +.btn-qrcode-peer:hover { + transform: scale(0.9) rotate(180deg); + border: 0 !important; +} + +.btn-download-peer:active, +.btn-download-peer:hover { + color: #17a2b8 !important; + transform: translateY(5px); +} + +.share_peer_btn_group .btn-control { + margin: 0 0 0 1rem; + padding: 0 !important; + transition: all 0.4s cubic-bezier(1, -0.43, 0, 1.37); +} + +.btn-control:hover { + background: white; +} + +.btn-delete-peer:hover { + color: #dc3545; +} + +.btn-lock-peer:hover { + color: #28a745; +} + +.btn-lock-peer.lock{ + color: #6c757d +} + +.btn-lock-peer.lock:hover{ + color: #6c757d +} + +.btn-control.btn-outline-primary:hover{ + color: #007bff +} + +/* .btn-setting-peer:hover { + color: #007bff +} */ + +.btn-download-peer:hover { + color: #17a2b8; +} + +.login-container { + padding: 2rem; +} + +@media (max-width: 992px) { + .card-col { + margin-bottom: 1rem; + } +} + +.switch { + font-size: 2rem; +} + +.switch:hover { + text-decoration: none +} + +.btn-group-label:hover { + color: #007bff; + border-color: #007bff; + background: white; +} + +.peer_data_group { + text-align: right; + display: flex; + margin-bottom: 0.5rem +} + +.peer_data_group p { + text-transform: uppercase; + margin-bottom: 0; + margin-right: 1rem +} + +@media (max-width: 768px) { + .peer_data_group { + text-align: left; + } +} + +.index-switch { + display: flex; + align-items: center; + justify-content: flex-end; +} + +main { + margin-bottom: 3rem; +} + +.peer_list { + margin-bottom: 7rem +} + +@media (max-width: 768px) { + .add_btn { + bottom: 1.5rem !important; + } + .peer_list { + margin-bottom: 7rem !important; + } +} + +.btn-manage-group { + z-index: 99; + position: fixed; + bottom: 3rem; + right: 2rem; + display: flex; +} + +.btn-manage-group .setting_btn_menu { + position: absolute; + top: -124px; + background-color: white; + padding: 1rem 0; + right: 0; + box-shadow: 0 10px 20px rgb(0 0 0 / 19%), 0 6px 6px rgb(0 0 0 / 23%); + border-radius: 10px; + min-width: 250px; + display: none; + transform: translateY(-30px); + opacity: 0; + transition: all 0.3s cubic-bezier(0.58, 0.03, 0.05, 1.28); +} + +.btn-manage-group .setting_btn_menu.show { + display: block; +} + +.setting_btn_menu.showing { + transform: translateY(0px); + opacity: 1; +} + +.setting_btn_menu a { + display: flex; + padding: 0.5rem 1rem; + transition: all 0.1s ease-in-out; + font-size: 1rem; + align-items: center; + cursor: pointer; +} + +.setting_btn_menu a:hover { + background-color: #efefef; + text-decoration: none; +} + +.setting_btn_menu a i { + margin-right: auto !important; +} + +.add_btn { + height: 54px; + z-index: 99; + border-radius: 100px !important; + padding: 0 14px; + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); + margin-right: 1rem; + font-size: 1.5rem; +} + +.setting_btn { + height: 54px; + z-index: 99; + border-radius: 100px !important; + padding: 0 14px; + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); + font-size: 1.5rem; +} + +@-webkit-keyframes rotating +/* Safari and Chrome */ + +{ + from { + -webkit-transform: rotate(0deg); + -o-transform: rotate(0deg); + transform: rotate(0deg); + } + to { + -webkit-transform: rotate(360deg); + -o-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotating { + from { + -ms-transform: rotate(0deg); + -moz-transform: rotate(0deg); + -webkit-transform: rotate(0deg); + -o-transform: rotate(0deg); + transform: rotate(0deg); + } + to { + -ms-transform: rotate(360deg); + -moz-transform: rotate(360deg); + -webkit-transform: rotate(360deg); + -o-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +.rotating::before { + -webkit-animation: rotating 0.75s linear infinite; + -moz-animation: rotating 0.75s linear infinite; + -ms-animation: rotating 0.75s linear infinite; + -o-animation: rotating 0.75s linear infinite; + animation: rotating 0.75s linear infinite; +} + +.peer_private_key_textbox_switch { + position: absolute; + right: 2rem; + transform: translateY(-28px); + font-size: 1.2rem; + cursor: pointer; +} + +#peer_private_key_textbox, +#private_key, +#public_key, +#peer_preshared_key_textbox { + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; +} + +.progress-bar { + transition: 0.3s ease-in-out; +} + +.key { + transition: 0.2s ease-in-out; + cursor: pointer; +} + +.key:hover { + color: #007bff; +} + +.card { + border-radius: 10px; +} + +.peer_list .card .button-group { + height: 22px; +} + +.form-control { + border-radius: 10px; +} + +.btn { + border-radius: 8px; + /*padding: 0.6rem 0.9em;*/ +} + +.login-box #username, +.login-box #password { + padding: 0.6rem calc( 0.9rem + 32px); + height: inherit; +} + +.login-box label[for="username"], +.login-box label[for="password"] { + font-size: 1rem; + margin: 0 !important; + transform: translateY(2.1rem) translateX(1rem); + padding: 0; +} + + +/*label[for="password"]{*/ + + +/* transform: translateY(32px) translateX(16px);*/ + + +/*}*/ + +.modal-content { + border-radius: 10px; +} + +.tooltip-inner { + font-size: 0.8rem; +} + +@-webkit-keyframes loading { + 0% { + background-color: #dfdfdf; + } + 50% { + background-color: #adadad; + } + 100% { + background-color: #dfdfdf; + } +} + +@-moz-keyframes loading { + 0% { + background-color: #dfdfdf; + } + 50% { + background-color: #adadad; + } + 100% { + background-color: #dfdfdf; + } +} + +.conf_card { + transition: 0.2s ease-in-out; +} + +.conf_card:hover { + border-color: #007bff; + cursor: pointer; +} + +.info_loading { + /* animation: loading 2s infinite ease-in-out; + /* border-radius: 5px; */ + height: 19.19px; + /* transition: 0.3s ease-in-out; */ + + /* transform: translateX(40px); */ + opacity: 0 !important; +} + +#conf_status_btn { + transition: 0.2s ease-in-out; +} + +#conf_status_btn.info_loading { + height: 38px; + border-radius: 5px; + animation: loading 3s infinite ease-in-out; +} + +#qrcode_img img { + width: 100%; +} + +#selected_ip_list .badge, +#selected_peer_list .badge { + margin: 0.1rem +} + +#add_modal.ip_modal_open { + transition: filter 0.2s ease-in-out; + filter: brightness(0.5); +} + +#delete_bulk_modal .list-group a.active { + background-color: #dc3545; + border-color: #dc3545; +} + +#selected_peer_list { + max-height: 80px; + overflow-y: scroll; + overflow-x: hidden; +} + +.no-response { + width: 100%; + height: 100%; + position: fixed; + background: #000000ba; + z-index: 10000; + display: none; + flex-direction: column; + align-items: center; + justify-content: center; + opacity: 0; + transition: all 1s ease-in-out; +} + +.no-response.active { + display: flex; +} + +.no-response.active.show { + opacity: 100; +} + +.no-response .container>* { + text-align: center; +} + +.no-responding { + transition: all 1s ease-in-out; + filter: blur(10px); +} + +pre.index-alert { + margin-bottom: 0; + padding: 1rem; + background-color: #343a40; + border: 1px solid rgba(0, 0, 0, .125); + border-radius: .25rem; + margin-top: 1rem; + color: white; +} + +.peerNameCol { + display: flex; + align-items: center; + margin-bottom: 0.2rem +} + +.peerName { + margin: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.peerLightContainer { + text-transform: uppercase; + margin: 0; + margin-left: auto !important; +} + +.conf_card .dot, +.info .dot { + transform: translateX(10px); +} + +#config_body { + transition: 0.3s ease-in-out; +} + + +#config_body.firstLoading { + opacity: 0.2; +} + +.chartTitle { + display: flex; +} + +.chartControl { + margin-bottom: 1rem; + display: flex; + align-items: center; +} + +.chartTitle h6 { + margin-bottom: 0; + line-height: 1; + margin-right: 0.5rem; +} + +.chartContainer.fullScreen { + position: fixed; + z-index: 9999; + background-color: white; + top: 0; + left: 0; + width: calc( 100% + 15px); + height: 100%; + padding: 32px; +} + +.chartContainer.fullScreen .col-sm { + padding-right: 0; + height: 100%; +} + +.chartContainer.fullScreen .chartCanvasContainer { + width: 100%; + height: calc( 100% - 47px) !important; + max-height: calc( 100% - 47px) !important; +} + +#switch{ + transition: all 200ms ease-in; +} + +.toggle--switch{ + display: none; +} + +.toggleLabel{ + width: 64px; + height: 32px; + background-color: #6c757d17; + display: flex; + position: relative; + border: 2px solid #6c757d8c; + border-radius: 100px; + transition: all 200ms ease-in; + cursor: pointer; + margin: 0; +} + +.toggle--switch.waiting + .toggleLabel{ + opacity: 0.5; +} + +.toggleLabel::before{ + background-color: #6c757d; + height: 26px; + width: 26px; + content: ""; + border-radius: 100px; + margin: 1px; + position: absolute; + animation-name: off; + animation-duration: 350ms; + animation-fill-mode: forwards; + transition: all 200ms ease-in; + cursor: pointer; +} + +.toggleLabel:hover::before{ + filter: brightness(1.2); +} + + +.toggle--switch:checked + .toggleLabel{ + background-color: #007bff17 !important; + border: 2px solid #007bff8c; +} + +.toggle--switch:checked + .toggleLabel::before{ + background-color: #007bff; + animation-name: on; + animation-duration: 350ms; + animation-fill-mode: forwards; +} + +@keyframes on { + 0%{ + left: 0px; + } + 60%{ + left: 0px; + width: 40px; + } + 100%{ + left: 32px; + width: 26px; + } +} + +@keyframes off { + 0%{ + left: 32px; + } + 60%{ + left: 18px; + width: 40px; + } + 100%{ + left: 0px; + width: 26px; + } +} + +.toastContainer{ + z-index: 99999 !important; +} + +.toast{ + min-width: 300px; + background-color: rgba(255,255,255,1); + z-index: 99999; +} + +.toast-header{ + background-color: rgba(255,255,255); +} + +.toast-progressbar{ + width: 100%; + height: 4px; + background-color: #007bff; + border-bottom-left-radius: .25rem; +} + +.addConfigurationAvailableIPs{ + margin-bottom: 0; +} + +.input-feedback{ + display: none; +} + +#addConfigurationModal label{ + display: flex; + width: 100%; + align-items: center; +} + +#addConfigurationModal label a{ + margin-left: auto !important; +} + +#reGeneratePrivateKey{ + border-top-right-radius: 10px; + border-bottom-right-radius: 10px; +} + +.addConfigurationToggleStatus.waiting{ + opacity: 0.5; +} + +/*.conf_card .card-body .row .card-col{*/ +/* margin-bottom: 0.5rem;*/ +/*}*/ + +.peerDataUsageChartContainer{ + min-height: 50vh; + width: 100%; +} + +.peerDataUsageChartControl{ + display: block !important; + margin: 0; +} + +.peerDataUsageChartControl .switchUnit{ + width: 33.3%; +} + +.peerDataUsageChartControl .switchTimePeriod{ + width: 25%; +} + +@media (min-width: 1200px){ + #peerDataUsage .modal-xl { + max-width: 95vw; + } +} + +.bottom{ + display: none; +} + + +@media (max-width: 768px){ + .bottom{ + display: block; + } + + .btn-manage-group{ + bottom: calc( 3rem + 40px + env(safe-area-inset-bottom, 5px)); + } + + main{ + padding-bottom: calc( 3rem + 40px + env(safe-area-inset-bottom, 5px)); + } +} + + +.bottomNavContainer{ + display: flex; + color: #333; + padding-bottom: env(safe-area-inset-bottom, 5px); + box-shadow: inset 0 1px 0 rgb(0 0 0 / 10%); +} + +.bottomNavButton{ + width: 25vw; + display: flex; + flex-direction: column; + align-items: center; + margin: 0.7rem 0; + color: rgba(51, 51, 51, 0.5); + cursor: pointer; + transition: all ease-in 0.2s; +} + +.bottomNavButton.active{ + color: #333; +} + +.bottomNavButton i{ + font-size: 1.2rem; +} + +.bottomNavButton .subNav{ + width: 100vw; + position: absolute; + z-index: 10000; + bottom: 0; + left: 0; + background-color: #272b30; + display: none; + animation-duration: 400ms; + padding-bottom: env(safe-area-inset-bottom, 5px); +} + +.bottomNavButton .subNav.active{ + display: block; +} + + +.bottomNavButton .subNav .nav .nav-item .nav-link{ + padding: 0.7rem 1rem; +} + +.bottomNavWrapper{ + height: 100%; + width: 100%; + background-color: #000000a1; + position: fixed; + z-index: 1030; + display: none; + left: 0; +} + +.bottomNavWrapper.active{ + display: block; +} + +.sb-update-url .dot-running{ + transform: translateX(10px); +} + +.list-group-item{ + transition: all 0.1s ease-in; +} + +.theme-switch-btn{ + width: 100%; +} \ No newline at end of file diff --git a/src/static/app/src/App.vue b/src/static/app/src/App.vue index c0c4ebec..10bc14ea 100644 --- a/src/static/app/src/App.vue +++ b/src/static/app/src/App.vue @@ -1,9 +1,10 @@