diff --git a/.gitignore b/.gitignore
index b762303..db9e370 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,4 @@ log/**
release/*
*.db
src/db/wgdashboard.db
+.jshintrc
diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 0000000..0201c21
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,6 @@
+{
+ "globals": {
+ "peers": true
+ },
+ "esversion": 7
+}
\ No newline at end of file
diff --git a/README.md b/README.md
index bc7a572..0d07ab4 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,7 @@
- **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:*
diff --git a/src/dashboard.py b/src/dashboard.py
index 2cc8844..bea2fe4 100644
--- a/src/dashboard.py
+++ b/src/dashboard.py
@@ -1062,7 +1062,7 @@ def switch(config_name):
if status == "running":
try:
check = subprocess.check_output("wg-quick down " + config_name,
- shell=True, stderr=subprocess.STDOUT)
+ shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as exc:
session["switch_msg"] = exc.output.strip().decode("utf-8")
return redirect('/')
@@ -1670,28 +1670,33 @@ def check_update():
return result
+
"""
Configure DashBoard before start web-server
"""
+
+
def run_dashboard():
init_dashboard()
- global update
- update = check_update()
- global config
+ global UPDATE
+ UPDATE = check_update()
config = configparser.ConfigParser(strict=False)
config.read('wg-dashboard.ini')
- global app_ip
+ # global app_ip
app_ip = config.get("Server", "app_ip")
- global app_port
+ # global app_port
app_port = config.get("Server", "app_port")
- global wg_conf_path
- wg_conf_path = config.get("Server", "wg_conf_path")
+ global WG_CONF_PATH
+ WG_CONF_PATH = config.get("Server", "wg_conf_path")
config.clear()
return app
+
"""
Get host and port for web-server
"""
+
+
def get_host_bind():
init_dashboard()
config = configparser.ConfigParser(strict=False)
@@ -1701,6 +1706,15 @@ def get_host_bind():
return app_ip, app_port
+
if __name__ == "__main__":
- run_dashboard()
+ UPDATE = check_update()
+ config = configparser.ConfigParser(strict=False)
+ config.read('wg-dashboard.ini')
+ # global app_ip
+ app_ip = config.get("Server", "app_ip")
+ # global app_port
+ 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)
diff --git a/src/static/.DS_Store b/src/static/.DS_Store
index d127be4..cf820c4 100644
Binary files a/src/static/.DS_Store and b/src/static/.DS_Store differ
diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css
index 1c33bc5..cc7da53 100644
--- a/src/static/css/dashboard.css
+++ b/src/static/css/dashboard.css
@@ -52,6 +52,7 @@ body {
.nav-link:hover {
padding-left: 30px;
+ background-color: #dfdfdf;
}
.sidebar .nav-link .feather {
@@ -170,8 +171,24 @@ body {
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{
- padding: 0 0 0 1rem;
+ margin: 0 0 0 1rem;
+ padding: 0 !important;
+ transition: all 0.4s cubic-bezier(1, -0.43, 0, 1.37);
}
.btn-control:hover{
diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css
index 5f39e1a..f82f199 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}.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}.share_peer_btn_group .btn-control{padding:0 0 0 1rem}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.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:#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}.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: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}.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
diff --git a/src/static/img/192x192ios.png b/src/static/img/192x192ios.png
new file mode 100644
index 0000000..0bfe520
Binary files /dev/null and b/src/static/img/192x192ios.png differ
diff --git a/src/static/img/icon-192x192.png b/src/static/img/icon-192x192.png
new file mode 100644
index 0000000..5e950a2
Binary files /dev/null and b/src/static/img/icon-192x192.png differ
diff --git a/src/static/img/icon-256x256.png b/src/static/img/icon-256x256.png
new file mode 100644
index 0000000..f801831
Binary files /dev/null and b/src/static/img/icon-256x256.png differ
diff --git a/src/static/img/icon-384x384.png b/src/static/img/icon-384x384.png
new file mode 100644
index 0000000..4b34f5c
Binary files /dev/null and b/src/static/img/icon-384x384.png differ
diff --git a/src/static/img/icon-512x512.png b/src/static/img/icon-512x512.png
new file mode 100644
index 0000000..69b6883
Binary files /dev/null and b/src/static/img/icon-512x512.png differ
diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js
index 1ef56f1..389f844 100644
--- a/src/static/js/configuration.js
+++ b/src/static/js/configuration.js
@@ -3,326 +3,585 @@
* Under Apache-2.0 License
*/
-/**
- * This will load peers data from server
- * @param search
- */
-function load_data(search){
- startProgressBar();
- let result = '';
- $.ajax({
- method: "GET",
- url: "/get_config/"+conf_name+"?search="+encodeURIComponent(search),
- headers:{
- "Content-Type": "application/json"
- },
- success: function (response){
- removeNoResponding();
- peers = response.peer_data;
- if (response.listen_port === "" && response.status === "stopped"){
- $("config_info_alert").append('
Peer QR Code and configuration file download required a specified Listen Port.
');
+(function(){
+ /* global peers */
+ /* global conf_name */
+
+ /**
+ * Definitions
+ */
+ 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();
+
+
+ /**
+ * To show alert on the configuration page
+ * @param response
+ */
+ 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);
+ }
+ }
+
+ /**
+ * Parse all responded information onto the configuration header
+ * @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`;
+ }
+ $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"));
+ }
+
+ /**
+ * Parse all responded information onto the peers list
+ * @param response
+ */
+ 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 = '
';
+ 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();
}
- if (response.conf_address === "N/A"){
- $("config_info_alert").append('Configuration Address need to be specified to have peers connect to it.
');
- }
- let $conf_status_btn = $("#conf_status_btn");
- if (response.checked === "checked"){
- $conf_status_btn.html(' ON');
- }else{
- $conf_status_btn.html(' OFF');
- }
- $("#sort_by_dropdown option").removeAttr("selected");
- $("#sort_by_dropdown option[value="+response.sort_tag+"]").attr("selected", "selected");
- $(".interval-btn-group button").removeClass("active");
- $("button[data-refresh-interval="+response.dashboard_refresh_interval+"]").addClass("active");
- $(".display-btn-group button").removeClass("active");
- $("button[data-display-mode="+response.peer_display_mode+"]").addClass("active");
+ }
+ }
-
-
- $("#conf_status").html(response.status+'');
- $("#conf_connected_peers").html(response.running_peer);
- $("#conf_total_data_usage").html(response.total_data_usage[0] +" GB");
- $("#conf_total_data_received").html(response.total_data_usage[2] +" GB");
- $("#conf_total_data_sent").html(response.total_data_usage[1]+" GB");
- $("#conf_public_key").html(response.public_key);
- $("#conf_listen_port").html(response.listen_port === "" ? "N/A":response.listen_port);
- $("#conf_address").html(response.conf_address);
- $(".info h6").removeClass("info_loading");
- $conf_status_btn.removeClass("info_loading");
-
-
-
- if (response.peer_data.length === 0){
- $(".peer_list").html('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 = '
';
- let html = '
' +
- '
' +
- '
' +
- '
' +
- peer_name +
- spliter +
- peer_transfer +
- peer_key +
- peer_allowed_ip +
- peer_latest_handshake +
- spliter +
- peer_endpoint +
- spliter +
- peer_control +
- '
' +
- '
' +
- '
' +
- '
';
- result += html;
});
- $(".peer_list").html(result);
- if (response.dashboard_refresh_interval !== load_interval){
- load_interval = response.dashboard_refresh_interval;
- clearInterval(load_timeout);
- load_timeout = setInterval(function (){
- load_data($('#search_peer_textbox').val());
- }, response.dashboard_refresh_interval);
+ }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";
+ }
+ }
+
+ /**
+ * Delete one peer or by bulk
+ * @param config
+ * @param peer_ids
+ */
+ 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");
}
}
+ });
+ }
+
+ /**
+ * Handle when the server is not responding
+ */
+ 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);
+ }
+
+ /**
+ * Remove no responding
+ */
+ 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);
+ }
+
+ /**
+ * Set configuration refresh Interval
+ */
+ function setConfigurationInterval(){
+ configuration_interval = setInterval(function (){
+ loadPeers($('#search_peer_textbox').val());
+ }, configuration_timeout);
+ }
+
+ /**
+ * Remove configuration refresh interval
+ */
+ function removeConfigurationInterval(){
+ clearInterval(configuration_interval);
+ }
+
+ /**
+ * Start Progress Bar
+ */
+ 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);
+ }
+
+ /**
+ * Still Loading Progress Bar
+ */
+ 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(){
+ $progress_bar.css("opacity", "0");
+ },250);
+ }
+
+ /**
+ * Round Transfer number into 4 digits
+ * @param value
+ * @param digits
+ * @returns {number}
+ */
+ function roundN(value, digits) {
+ let tenToN = 10 ** digits;
+ return (Math.round(value * tenToN)) / tenToN;
+ }
+
+ /**
+ * Load Peers from server to configuration page
+ * @param searchString
+ */
+ function loadPeers(searchString){
+ startProgressBar();
+ $.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();
+ }).fail(function(){
+ noResponding();
+ });
+ }
+
+ /**
+ * Generate Private and Public key for a new peer
+ */
+ 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;
+ }
+
+ /**
+ * Show toast
+ * @param msg
+ */
+ function showToast(msg) {
+ $('#alertToast').toast('show');
+ $('#alertToast .toast-body').html(msg);
+ }
+
+ /**
+ * Update peer's refresh interval
+ * @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");
}
- }).fail(function(){
- noResponding();
- });
-}
+ }
-function noResponding(){
- $(".no-response").addClass("active");
- setTimeout(function (){
- $(".no-response").addClass("show");
- $("#right_body").addClass("no-responding");
- $(".navbar").addClass("no-responding");
- },10);
-}
+ /**
+ * Clean IP
+ * @param val
+ * @returns {string}
+ */
+ function cleanIp(val){
+ let clean_ip = val.split(',');
+ for (let i = 0; i < clean_ip.length; i++) {
+ clean_ip[i] = clean_ip[i].trim(' ');
+ }
+ return clean_ip.filter(Boolean).join(",");
+ }
-function removeNoResponding(){
- $(".no-response").removeClass("show");
- $("#right_body").removeClass("no-responding");
- $(".navbar").removeClass("no-responding");
- setTimeout(function (){
- $(".no-response").removeClass("active");
- },1010);
-}
+ /**
+ * Trigger IP badge and item
+ * @param 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")){
+ $ip_ele.classList.remove("active");
+ document.querySelector(`#selected_ip_list .badge[data-ip='${ip}']`).remove();
+ }else{
+ $ip_ele.classList.add("active");
+ document.querySelector("#selected_ip_list").innerHTML += `${ip}`;
+ }
+ }
+ }
+
+ /**
+ * Download single configuration file
+ * @param conf
+ */
+ 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();
+ }
+
+ /**
+ * Toggle delete by bulk IP
+ * @param 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")){
+ element.removeClass("active");
+ $("#selected_peer_list .badge[data-id='"+id+"']").remove();
+ }else{
+ element.addClass("active");
+ $selected_peer_list.append(''+name+' - '+id+'');
+ }
+ }
+
+ /**
+ * Copy public keys to clipboard
+ * @param element
+ */
+ function copyToClipboard(element) {
+ let $temp = $("");
+ $body.append($temp);
+ $temp.val($(element).text()).trigger( "select" );
+ document.execCommand("copy");
+ $temp.remove();
+ }
+
+ /**
+ * Get all available IP for this configuration
+ */
+ 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(); }
+ };
+})();
-$("[data-toggle='tooltip']").tooltip();
-$("[data-toggle='popover']").popover();
let $body = $("body");
-let $progress_bar = $(".progress-bar");
let available_ips = [];
-let $save_peer = $("#save_peer");
+let $add_peer = document.getElementById("save_peer");
-$(".add_btn").on("click", function(){
- $addModal.toggle();
+/**
+ * ==========
+ * Add peers
+ * ==========
+ */
+
+/**
+ * Toggle add peers modal when add button clicked
+ */
+document.querySelector(".add_btn").addEventListener("click", () => {
+ window.configurations.addModal().toggle();
});
-/**
- * Round Transfer number into 4 digits
- * @param value
- * @param digits
- * @returns {number}
- */
-function roundN(value, digits) {
- let tenToN = 10 ** digits;
- return (Math.round(value * tenToN)) / tenToN;
-}
-
-/**
- * Start Progress Bar
- */
-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);
-}
-
-/**
- * Still Loading Progress Bar
- */
-function stillLoadingProgressBar(){
- $progress_bar.css("transition", "3s ease-in-out").css("width", "75%");
-}
-
-/**
- * End Progress Bae
- */
-function endProgressBar(){
- $progress_bar.css("transition", "0.3s ease-in-out").css("width","100%");
- setTimeout(function(){
- $progress_bar.css("opacity", "0");
- },250);
-
-}
-
-/**
- * Show toast
- * @param msg
- */
-function showToast(msg) {
- $('#alertToast').toast('show');
- $('#alertToast .toast-body').html(msg);
-}
-
/**
* When configuration switch got click
*/
-$body.on("click", ".switch", function (){
- $(this).siblings($(".spinner-border")).css("display", "inline-block");
- $(this).remove();
- location.replace("/switch/"+$(this).attr('id'));
+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")}`);
+ }
});
-/**
- * Generate Private and Public key for a new peer
- */
-function generate_key(){
- let keys = wireguard.generateKeypair();
- $("#private_key").val(keys.privateKey);
- $("#public_key").val(keys.publicKey);
- $("#add_peer_alert").addClass("d-none");
- $("#re_generate_key i").removeClass("rotating");
- $("#enable_preshare_key").val(keys.presharedKey);
-}
-
/**
* Generate Public key when private got change
*/
-$("#private_key").on("change",function(){
- if ($(this).val().length === 44){
- $("#re_generate_key i").addClass("rotating");
- $("#public_key").val(wireguard.generatePublicKey($("#private_key").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{
- $("#public_key").removeAttr("disabled").val("");
+ publicKey.attributes.removeNamedItem("disabled");
+ publicKey.value = "";
}
});
/**
- * Trigger IP badge and item
- * @param ip
+ * Handle when add modal is show and hide
*/
-function trigger_ip(ip){
- let $ip_ele = $(".available-ip-item[data-ip='"+ip+"']");
- if ($ip_ele.html()){
- if ($ip_ele.hasClass("active")){
- $ip_ele.removeClass("active");
- $("#selected_ip_list .badge[data-ip='"+ip+"']").remove();
- }else{
- $ip_ele.addClass("active");
- $("#selected_ip_list").append(''+ip+'')
- }
- }
-}
-
-/**
- * Get all available IP for this configuration
- */
-function get_available_ip(){
- $.ajax({
- "url": "/available_ips/"+$save_peer.attr("conf_id"),
- "method": "GET",
- }).done(function (res) {
- available_ips = res;
- let $list_group = $("#available_ip_modal .modal-body .list-group");
- $list_group.html("");
- $("#allowed_ips").val(available_ips[0]);
- available_ips.forEach((ip) =>
- $list_group.append(''+ip+''));
- });
-}
-
-$("#available_ip_modal").on("show.bs.modal", () => {
- $('#add_modal').addClass("ip_modal_open");
-}).on("hidden.bs.modal", function () {
- $('#add_modal').removeClass("ip_modal_open");
- let ips = [];
- let $selected_ip_list = $("#selected_ip_list");
- $selected_ip_list.children().each(function(){
- ips.push($(this).data("ip"));
- });
- ips.forEach((ele) => trigger_ip(ele));
-})
-
-/**
- * When IP Badge got click
- */
-$body.on("click", ".available-ip-badge", function(){
- $(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");
- $(this).remove();
-})
-
-/**
- * When available ip item got click
- */
-$body.on("click", ".available-ip-item", function () {
- trigger_ip($(this).data("ip"));
+$('#add_modal').on('show.bs.modal', function () {
+ window.configurations.generateKeyPair();
+ window.configurations.getAvailableIps();
+}).on('hide.bs.modal', function(){
+ $("#allowed_ips_indicator").html('');
});
-let $ipModal = new bootstrap.Modal(document.getElementById('available_ip_modal'), {
- keyboard: false,
- backdrop: 'static'
-});
-
-$("#search_available_ip").on("click", function () {
- $ipModal.toggle();
- let $allowed_ips = $("#allowed_ips");
- if ($allowed_ips.val().length > 0){
- let s = $allowed_ips.val().split(",");
- for (let i = 0; i < s.length; i++){
- s[i] = s[i].trim();
- trigger_ip(s[i]);
- }
- }
-}).tooltip();
-
-$("#confirm_ip").on("click", () => {
- $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) => trigger_ip(ele));
+/**
+ * Handle when user clicked the regenerate button
+ */
+$("#re_generate_key").on("click",function (){
+ $("#public_key").attr("disabled","disabled");
+ $("#re_generate_key i").addClass("rotating");
+ window.configurations.generateKeyPair();
});
+/**
+ * Handle when user is editing in allowed ips textbox
+ */
$("#allowed_ips").on("keyup", function(){
- let s = clean_ip($(this).val());
+ 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")
@@ -331,140 +590,41 @@ $("#allowed_ips").on("keyup", function(){
$("#allowed_ips_indicator").removeClass().addClass("text-warning")
.html('');
}
-})
-
-
-$('#add_modal').on('show.bs.modal', function (event) {
- generate_key();
- get_available_ip();
-}).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");
- generate_key();
+/**
+ * Change peer name when user typing in peer name textbox
+ */
+$("#peer_name_textbox").on("keyup", function(){
+ $(".peer_name").html($(this).val());
});
-let $addModal = new bootstrap.Modal(document.getElementById('add_modal'), {
- keyboard: false,
- backdrop: 'static'
-});
-
-function clean_ip(val){
- let clean_ip = val.split(',');
- for (let i = 0; i < clean_ip.length; i++) clean_ip[i] = clean_ip[i].trim(' ');
- return clean_ip.filter(Boolean).join(",");
-}
-
-
-$("#new_add_amount").on("keyup", function(){
- let $bulk_amount_validation = $("#bulk_amount_validation");
- // $(this).removeClass("is-valid").addClass("is-invalid");
- if ($(this).val().length > 0){
- if (isNaN($(this).val())){
- $(this).removeClass("is-valid").addClass("is-invalid");
- $bulk_amount_validation.html("Please enter a valid integer");
- }else if ($(this).val() > available_ips.length){
- $(this).removeClass("is-valid").addClass("is-invalid");
- $bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`);
- }else if ($(this).val() < 1){
- $(this).removeClass("is-valid").addClass("is-invalid");
- $bulk_amount_validation.html("Please enter at least 1 or more.");
- }else{
- $(this).removeClass("is-invalid").addClass("is-valid");
- }
- }else{
- $(this).removeClass("is-invalid").removeClass("is-valid");
- }
-});
-
-
-function bulk_add_peers() {
- let $new_add_amount = $("#new_add_amount");
- $save_peer.attr("disabled","disabled");
- $save_peer.html("Adding "+$new_add_amount.val()+" peers...");
- let $new_add_DNS = $("#new_add_DNS");
- $new_add_DNS.val(clean_ip($new_add_DNS.val()));
- let $new_add_endpoint_allowed_ip = $("#new_add_endpoint_allowed_ip");
- $new_add_endpoint_allowed_ip.val(clean_ip($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 = $save_peer.attr('conf_id');
- let keys = [];
- for (let i = 0; i < $new_add_amount.val(); i++) {
- keys.push(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"));
- $save_peer.removeAttr("disabled").html("Save");
- }
- else{
- load_data("");
- data_list.forEach((ele) => ele.removeAttr("disabled"));
- $("#add_peer_form").trigger("reset");
- $save_peer.removeAttr("disabled").html("Save");
- showToast($new_add_amount.val()+" peers added successful!");
- $addModal.toggle();
- }
- }
- });
- }else{
- $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");
- $save_peer.removeAttr("disabled");
- $save_peer.html("Add");
- }
- }else{
- $save_peer.removeAttr("disabled").html("Add");
- }
-}
-
-
-$save_peer.on("click",function(){
+/**
+ * When Add Peer button got clicked
+ */
+$add_peer.addEventListener("click",function(){
let $bulk_add = $("#bulk_add");
if ($bulk_add.prop("checked")){
if (!$("#new_add_amount").hasClass("is-invalid")){
- bulk_add_peers()
+ window.configurations.addPeersByBulk();
}
- }else {
+ } else {
let $public_key = $("#public_key");
let $private_key = $("#private_key");
let $allowed_ips = $("#allowed_ips");
- $allowed_ips.val(clean_ip($allowed_ips.val()));
+ $allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));
let $new_add_DNS = $("#new_add_DNS");
- $new_add_DNS.val(clean_ip($new_add_DNS.val()));
+ $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(clean_ip($new_add_endpoint_allowed_ip.val()));
+ $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");
- $(this).attr("disabled","disabled");
- $(this).html("Adding...");
+ $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 = $(this).attr('conf_id');
+ 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({
@@ -489,108 +649,199 @@ $save_peer.on("click",function(){
if(response !== "true"){
$("#add_peer_alert").html(response).removeClass("d-none");
data_list.forEach((ele) => ele.removeAttr("disabled"));
- $save_peer.removeAttr("disabled").html("Save");
+ $add_peer.removeAttribute("disabled");
+ $add_peer.innerHTML = "Save";
}
else{
- load_data("");
+ window.configurations.loadPeers("");
data_list.forEach((ele) => ele.removeAttr("disabled"));
$("#add_peer_form").trigger("reset");
- $save_peer.removeAttr("disabled").html("Save");
- showToast("Add peer successful!");
- $addModal.toggle();
+ $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");
- $(this).removeAttr("disabled");
- $(this).html("Add");
+ $add_peer.removeAttribute("disabled");
+ $add_peer.innerHTML = "Add";
}
}
});
-// QR Code
-let qrcodeModal = new bootstrap.Modal(document.getElementById('qrcode_modal'), {
- keyboard: false
+/**
+ * Handle when user is typing the amount of peers they want to add, and will check if the amount is less than 1 or
+ * is larger than the amount of available ips
+ */
+$("#new_add_amount").on("keyup", function(){
+ let $bulk_amount_validation = $("#bulk_amount_validation");
+ // $(this).removeClass("is-valid").addClass("is-invalid");
+ if ($(this).val().length > 0){
+ if (isNaN($(this).val())){
+ $(this).removeClass("is-valid").addClass("is-invalid");
+ $bulk_amount_validation.html("Please enter a valid integer");
+ }else if ($(this).val() > available_ips.length){
+ $(this).removeClass("is-valid").addClass("is-invalid");
+ $bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`);
+ }else if ($(this).val() < 1){
+ $(this).removeClass("is-valid").addClass("is-invalid");
+ $bulk_amount_validation.html("Please enter at least 1 or more.");
+ }else{
+ $(this).removeClass("is-invalid").addClass("is-valid");
+ }
+ }else{
+ $(this).removeClass("is-invalid").removeClass("is-valid");
+ }
});
+
+/**
+ * Handle when user toggled add peers by bulk
+ */
+$("#bulk_add").on("change", function (){
+ let hide = $(".non-bulk").find("input");
+ let amount = $("#new_add_amount");
+ if ($(this).prop("checked") === true){
+ for(let i = 0; i < hide.length; i++){
+ $(hide[i]).attr("disabled", "disabled");
+ }
+ amount.removeAttr("disabled");
+ }
+ else{
+ for(let i = 0; i < hide.length; i++){
+ if ($(hide[i]).attr('id') !== "public_key"){
+ $(hide[i]).removeAttr("disabled");
+ }
+ }
+ amount.attr("disabled", "disabled");
+ }
+});
+
+
+/**
+ * =======================
+ * Available IP Related
+ * =======================
+ */
+
+/**
+ * Handle when available ip modal show and hide
+ */
+$("#available_ip_modal").on("show.bs.modal", () => {
+ document.querySelector('#add_modal').classList.add("ip_modal_open");
+}).on("hidden.bs.modal", () => {
+ document.querySelector('#add_modal').classList.remove("ip_modal_open");
+ let ips = [];
+ let $selected_ip_list = document.querySelector("#selected_ip_list");
+ for (let i = 0; i < $selected_ip_list.childElementCount; i++){
+ ips.push($selected_ip_list.children[i].dataset.ip);
+ }
+ ips.forEach((ele) => window.configurations.triggerIp(ele));
+});
+
+/**
+ * When IP Badge got click
+ */
+$body.on("click", ".available-ip-badge", function(){
+ $(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");
+ $(this).remove();
+});
+
+/**
+ * When available ip item got click
+ */
+$body.on("click", ".available-ip-item", function () {
+ window.configurations.triggerIp($(this).data("ip"));
+});
+
+/**
+ * When search IP button got clicked
+ */
+$("#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 < s.length; i++){
+ s[i] = s[i].trim();
+ window.configurations.triggerIp(s[i]);
+ }
+ }
+}).tooltip();
+
+/**
+ * When confirm IP is clicked
+ */
+$("#confirm_ip").on("click", () => {
+ 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));
+});
+
+/**
+ * =======
+ * QR Code
+ * =======
+ */
+
+/**
+ * When the QR-code button got clicked on each peer
+ */
$body.on("click", ".btn-qrcode-peer", function (){
- let src = $(this).attr('img_src');
+ let src = $(this).data('imgsrc');
$.ajax({
"url": src,
"method": "GET"
}).done(function(res){
$("#qrcode_img").attr('src', res);
- qrcodeModal.toggle();
+ window.configurations.qrcodeModal().toggle();
});
});
-// Delete Peer Modal
-let deleteModal = new bootstrap.Modal(document.getElementById('delete_modal'), {
- keyboard: false,
- backdrop: 'static'
-});
+/**
+ * ===========
+ * Delete Peer
+ * ===========
+ */
+/**
+ * When the delete button got clicked on each peer
+ */
$body.on("click", ".btn-delete-peer", function(){
let peer_id = $(this).attr("id");
$("#delete_peer").attr("peer_id", peer_id);
- deleteModal.toggle();
+ window.configurations.deleteModal().toggle();
});
+/**
+ * When the confirm delete button clicked
+ */
$("#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];
- deletePeers(config, peer_ids);
+ window.configurations.deletePeers(config, peer_ids);
});
-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 (deleteModal._isShown) {
- $("#remove_peer_alert").html(response+$("#add_peer_alert").html())
- .removeClass("d-none");
- }
- if (deleteBulkModal._isShown){
- $("#bulk_remove_peer_alert").html(response+$("#bulk_remove_peer_alert").html())
- .removeClass("d-none");
- }
+/**
+ * =============
+ * Peer Settings
+ * =============
+ */
- }
- else{
- if (deleteModal._isShown) {
- deleteModal.toggle()
- }
- if (deleteBulkModal._isShown){
- $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");
- $("#selected_peer_list").html('');
- $(".delete-bulk-peer-item.active").removeClass('active');
- deleteBulkModal.toggle();
- }
- load_data($('#search_peer_textbox').val());
- $('#alertToast').toast('show');
- $('#alertToast .toast-body').html("Peer deleted!");
- $("#delete_peer").removeAttr("disabled").html("Delete");
- }
- }
- });
-}
-
-// Peer Setting Modal
-let settingModal = new bootstrap.Modal(document.getElementById('setting_modal'), {
- keyboard: false,
- backdrop: 'static'
-});
+/**
+ * Handle when setting button got clicked for each peer
+ */
$body.on("click", ".btn-setting-peer", function(){
- startProgressBar();
+ window.configurations.startProgressBar();
let peer_id = $(this).attr("id");
$("#save_peer_setting").attr("peer_id", peer_id);
$.ajax({
@@ -601,7 +852,7 @@ $body.on("click", ".btn-setting-peer", function(){
},
data: JSON.stringify({"id": peer_id}),
success: function(response){
- let peer_name = ((response.name === "") ? "Untitled Peer" : response.name);
+ 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);
@@ -611,16 +862,22 @@ $body.on("click", ".btn-setting-peer", function(){
$("#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);
- settingModal.toggle();
- endProgressBar();
+ window.configurations.settingModal().toggle();
+ window.configurations.endProgressBar();
}
});
});
-$('#setting_modal').on('hidden.bs.modal', function (event) {
+/**
+ * Handle when setting modal is closing
+ */
+$('#setting_modal').on('hidden.bs.modal', function () {
$("#setting_peer_alert").addClass("d-none");
});
+/**
+ * Handle when private key text box in setting modal got changed
+ */
$("#peer_private_key_textbox").on("change",function(){
let $save_peer_setting = $("#save_peer_setting");
if ($(this).val().length > 0){
@@ -642,6 +899,9 @@ $("#peer_private_key_textbox").on("change",function(){
}
});
+/**
+ * When save peer setting button got clicked
+ */
$("#save_peer_setting").on("click",function (){
$(this).attr("disabled","disabled");
$(this).html("Saving...");
@@ -681,8 +941,8 @@ $("#save_peer_setting").on("click",function (){
if (response.status === "failed"){
$("#setting_peer_alert").html(response.msg).removeClass("d-none");
}else{
- settingModal.toggle();
- load_data($('#search_peer_textbox').val());
+ window.configurations.settingModal().toggle();
+ window.configurations.loadPeers($('#search_peer_textbox').val());
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Peer Saved!");
}
@@ -696,6 +956,9 @@ $("#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 (){
let $peer_private_key_textbox = $("#peer_private_key_textbox");
let mode = (($peer_private_key_textbox.attr('type') === 'password') ? "text":"password");
@@ -704,37 +967,49 @@ $(".peer_private_key_textbox_switch").on("click",function (){
$(".peer_private_key_textbox_switch i").removeClass().addClass(icon);
});
-// Search Peer
-let typingTimer;
-let doneTypingInterval = 200;
-let $input = $('#search_peer_textbox');
-$input.on('keyup', function () {
- clearTimeout(typingTimer);
- typingTimer = setTimeout(doneTyping, doneTypingInterval);
-});
+/**
+ * ===========
+ * Search Peer
+ * ===========
+ */
-$input.on('keydown', function () {
+let typingTimer; // Timeout object
+let doneTypingInterval = 200; // Timeout interval
+
+/**
+ * Handle when the user keyup and keydown on the search textbox
+ */
+$('#search_peer_textbox').on('keyup', function () {
+ clearTimeout(typingTimer);
+ typingTimer = setTimeout(() => {
+ window.configurations.loadPeers($(this).val());
+ }, doneTypingInterval);
+}).on('keydown', function () {
clearTimeout(typingTimer);
});
-function doneTyping () {
- load_data($input.val());
-}
+/**
+ * Manage Peers
+ */
-// Sorting
+/**
+ * Handle when sort peers changed
+ */
$body.on("change", "#sort_by_dropdown", function (){
$.ajax({
method:"POST",
data: JSON.stringify({'sort':$("#sort_by_dropdown option:selected").val()}),
headers:{"Content-Type": "application/json"},
url: "/update_dashboard_sort",
- success: function (res){
- load_data($('#search_peer_textbox').val());
+ success: function (){
+ window.configurations.loadPeers($('#search_peer_textbox').val());
}
});
});
-// Click key to copy animation
+/**
+ * Handle copy public key
+ */
$body.on("mouseenter", ".key", function(){
let label = $(this).parent().siblings().children()[1];
label.style.opacity = "100";
@@ -745,24 +1020,14 @@ $body.on("mouseenter", ".key", function(){
label.innerHTML = "CLICK TO COPY";
},200);
}).on("click", ".key", function(){
- var label = $(this).parent().siblings().children()[1];
- copyToClipboard($(this));
+ let label = $(this).parent().siblings().children()[1];
+ window.configurations.copyToClipboard($(this));
label.innerHTML = "COPIED!";
});
/**
- * CopyToClipboard
- * @param element
+ * Handle when interval button got clicked
*/
-function copyToClipboard(element) {
- let $temp = $("");
- $body.append($temp);
- $temp.val($(element).text()).trigger( "select" );
- document.execCommand("copy");
- $temp.remove();
-}
-
-// Update Interval
$body.on("click", ".update_interval", function(){
$(".interval-btn-group button").removeClass("active");
let _new = $(this);
@@ -773,28 +1038,21 @@ $body.on("click", ".update_interval", function(){
data: "interval="+$(this).data("refresh-interval"),
url: "/update_dashboard_refresh_interval",
success: function (res){
- if (res === "true"){
- load_interval = interval;
- clearInterval(load_timeout);
- load_timeout = setInterval(function (){
- load_data($('#search_peer_textbox').val());
- }, interval);
- showToast("Refresh Interval set to "+Math.round(interval/1000)+" seconds");
- }else{
- $(".interval-btn-group button").removeClass("active");
- $('.interval-btn-group button[data-refresh-interval="'+load_interval+'"]').addClass("active");
- showToast("Refresh Interval set unsuccessful");
- }
+ window.configurations.updateRefreshInterval(res, interval);
}
});
});
-// Refresh Button
+/**
+ * Handle when refresh button got clicked
+ */
$body.on("click", ".refresh", function (){
- load_data($('#search_peer_textbox').val());
+ window.configurations.loadPeers($('#search_peer_textbox').val());
});
-// Switch display mode
+/**
+ * Handle when display mode button got clicked
+ */
$body.on("click", ".display_mode", function(){
$(".display-btn-group button").removeClass("active");
$(this).addClass("active");
@@ -808,56 +1066,48 @@ $body.on("click", ".display_mode", function(){
Array($(".peer_list").children()).forEach(function(child){
$(child).removeClass().addClass("col-12");
});
- showToast("Displaying as List");
+ window.configurations.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");
+ window.configurations.showToast("Displaying as Grids");
}
}
}
});
});
-// Toggle bulk add mode
-$("#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 < hide.length; i++){
- $(hide[i]).attr("disabled", "disabled");
- }
- amount.removeAttr("disabled");
- }
- else{
- for(let i = 0; i < hide.length; i++){
- if ($(hide[i]).attr('id') !== "public_key"){
- $(hide[i]).removeAttr("disabled");
- }
- }
- amount.attr("disabled", "disabled");
- }
-});
-// Configuration sub menu
+/**
+ * =================
+ * Configuration Menu
+ * =================
+ */
let $setting_btn_menu = $(".setting_btn_menu");
$setting_btn_menu.css("top", ($setting_btn_menu.height() + 54)*(-1));
let $setting_btn = $(".setting_btn");
+
+/**
+ * When the menu button got clicked
+ */
$setting_btn.on("click", function(){
if ($setting_btn_menu.hasClass("show")){
$setting_btn_menu.removeClass("showing");
setTimeout(function(){
$setting_btn_menu.removeClass("show");
}, 201);
-
}else{
$setting_btn_menu.addClass("show");
setTimeout(function(){
$setting_btn_menu.addClass("showing");
},10);
}
-})
+});
+
+/**
+ * Whenever the user clicked, if it is outside the menu and the menu is opened, hide the menu
+ */
$("html").on("click", function(r){
if (document.querySelector(".setting_btn") !== r.target){
if (!document.querySelector(".setting_btn").contains(r.target)){
@@ -871,45 +1121,45 @@ $("html").on("click", function(r){
}
});
-// Delete peers by bulk
-let deleteBulkModal = new bootstrap.Modal(document.getElementById('delete_bulk_modal'), {
- keyboard: false,
- backdrop: 'static'
-});
+
+/**
+ * ====================
+ * Delete Peers by Bulk
+ * ====================
+ */
+
+/**
+ * When delete peers by bulk clicked
+ */
$("#delete_peers_by_bulk_btn").on("click", () => {
let $delete_bulk_modal_list = $("#delete_bulk_modal .list-group");
$delete_bulk_modal_list.html('');
peers.forEach((peer) => {
- let name = ""
- if (peer["name"] === "") { name = "Untitled Peer"; }
- else { name = peer["name"]; }
- $delete_bulk_modal_list.append(''+name+'
'+peer['id']+'
');
+ let name;
+ if (peer.name === "") { name = "Untitled Peer"; }
+ else { name = peer.name; }
+ $delete_bulk_modal_list.append(''+name+'
'+peer.id+'
');
});
- deleteBulkModal.toggle();
+ window.configurations.deleteBulkModal().toggle();
});
-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+'')
- }
-}
-
+/**
+ * When the item or tag of delete peers by bulk got clicked
+ */
$body.on("click", ".delete-bulk-peer-item", function(){
- toggleBulkIP($(this));
+ window.configurations.toggleDeleteByBulkIP($(this));
}).on("click", ".delete-peer-bulk-badge", function(){
- toggleBulkIP($(".delete-bulk-peer-item[data-id='" + $(this).data("id") + "']"));
+ 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(mutationsList, observer){
+
+/**
+ * The change observer to observe when user choose 1 or more peers to delete
+ * @type {MutationObserver}
+ */
+let changeObserver = new MutationObserver(function(){
if ($selected_peer_list.hasChildNodes()){
$("#confirm_delete_bulk_peers").removeAttr("disabled");
}else{
@@ -920,10 +1170,13 @@ changeObserver.observe($selected_peer_list, {
attributes: true,
childList: true,
characterData: true
-})
+});
+let confirm_delete_bulk_peers_interval;
-let confirm_delete_bulk_peers_interval = undefined;
+/**
+ * When the user clicked the delete button in the delete peers by bulk
+ */
$("#confirm_delete_bulk_peers").on("click", function(){
let btn = $(this);
if (confirm_delete_bulk_peers_interval !== undefined){
@@ -941,43 +1194,45 @@ $("#confirm_delete_bulk_peers").on("click", function(){
btn.attr("disabled", "disabled");
let ips = [];
$selected_peer_list.childNodes.forEach((ele) => ips.push(ele.dataset.id));
- deletePeers(btn.data("conf"), ips);
+ window.configurations.deletePeers(btn.data("conf"), ips);
clearInterval(confirm_delete_bulk_peers_interval);
confirm_delete_bulk_peers_interval = undefined;
}
- }, 1000)
+ }, 1000);
}
});
+/**
+ * Select all peers to delete
+ */
$("#select_all_delete_bulk_peers").on("click", function(){
$(".delete-bulk-peer-item").each(function(){
if (!$(this).hasClass("active")) {
- toggleBulkIP($(this));
+ window.configurations.toggleDeleteByBulkIP($(this));
}
});
});
-$(deleteBulkModal._element).on("hidden.bs.modal", function(){
+/**
+ * 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")) {
- toggleBulkIP($(this));
+ window.configurations.toggleDeleteByBulkIP($(this));
}
});
});
-// Download Peers
-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 download_all_config(confs){
- wireguard.generateZipFiles(confs);
-}
+/**
+ * ==============
+ * Download Peers
+ * ==============
+ */
+/**
+ * When the download peers button got clicked
+ */
$body.on("click", ".btn-download-peer", function(e){
e.preventDefault();
let link = $(this).attr("href");
@@ -985,22 +1240,25 @@ $body.on("click", ".btn-download-peer", function(e){
"url": link,
"method": "GET",
success: function(res){
- download_one_config(res);
+ window.configurations.downloadOneConfig(res);
}
});
});
+/**
+ * When the download all peers got clicked
+ */
$("#download_all_peers").on("click", function(){
$.ajax({
"url": $(this).data("url"),
"method": "GET",
success: function(res){
if (res.peers.length > 0){
- download_all_config(res);
+ 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/configuration.min.js b/src/static/js/configuration.min.js
index b140d2e..eda4ebf 100644
--- a/src/static/js/configuration.min.js
+++ b/src/static/js/configuration.min.js
@@ -1 +1 @@
-function load_data(search){startProgressBar();let result="";$.ajax({method:"GET",url:"/get_config/"+conf_name+"?search="+encodeURIComponent(search),headers:{"Content-Type":"application/json"},success:function(response){removeNoResponding();peers=response.peer_data;if(response.listen_port===""&&response.status==="stopped"){$("config_info_alert").append('Peer QR Code and configuration file download required a specified Listen Port.
')}if(response.conf_address==="N/A"){$("config_info_alert").append('Configuration Address need to be specified to have peers connect to it.
')}let $conf_status_btn=$("#conf_status_btn");if(response.checked==="checked"){$conf_status_btn.html(' ON')}else{$conf_status_btn.html(' OFF')}$("#sort_by_dropdown option").removeAttr("selected");$("#sort_by_dropdown option[value="+response.sort_tag+"]").attr("selected","selected");$(".interval-btn-group button").removeClass("active");$("button[data-refresh-interval="+response.dashboard_refresh_interval+"]").addClass("active");$(".display-btn-group button").removeClass("active");$("button[data-display-mode="+response.peer_display_mode+"]").addClass("active");$("#conf_status").html(response.status+'');$("#conf_connected_peers").html(response.running_peer);$("#conf_total_data_usage").html(response.total_data_usage[0]+" GB");$("#conf_total_data_received").html(response.total_data_usage[2]+" GB");$("#conf_total_data_sent").html(response.total_data_usage[1]+" GB");$("#conf_public_key").html(response.public_key);$("#conf_listen_port").html(response.listen_port===""?"N/A":response.listen_port);$("#conf_address").html(response.conf_address);$(".info h6").removeClass("info_loading");$conf_status_btn.removeClass("info_loading");if(response.peer_data.length===0){$(".peer_list").html('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='
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});$(".peer_list").html(result);if(response.dashboard_refresh_interval!==load_interval){load_interval=response.dashboard_refresh_interval;clearInterval(load_timeout);load_timeout=setInterval(function(){load_data($("#search_peer_textbox").val())},response.dashboard_refresh_interval)}}$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar()}}).fail(function(){noResponding()})}function noResponding(){$(".no-response").addClass("active");setTimeout(function(){$(".no-response").addClass("show");$("#right_body").addClass("no-responding");$(".navbar").addClass("no-responding")},10)}function removeNoResponding(){$(".no-response").removeClass("show");$("#right_body").removeClass("no-responding");$(".navbar").removeClass("no-responding");setTimeout(function(){$(".no-response").removeClass("active")},1010)}$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();let $body=$("body");let $progress_bar=$(".progress-bar");let available_ips=[];let $save_peer=$("#save_peer");$(".add_btn").on("click",function(){$addModal.toggle()});function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}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 showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}$body.on("click",".switch",function(){$(this).siblings($(".spinner-border")).css("display","inline-block");$(this).remove();location.replace("/switch/"+$(this).attr("id"))});function generate_key(){let keys=wireguard.generateKeypair();$("#private_key").val(keys.privateKey);$("#public_key").val(keys.publicKey);$("#add_peer_alert").addClass("d-none");$("#re_generate_key i").removeClass("rotating");$("#enable_preshare_key").val(keys.presharedKey)}$("#private_key").on("change",function(){if($(this).val().length===44){$("#re_generate_key i").addClass("rotating");$("#public_key").val(wireguard.generatePublicKey($("#private_key").val()))}else{$("#public_key").removeAttr("disabled").val("")}});function trigger_ip(ip){let $ip_ele=$(".available-ip-item[data-ip='"+ip+"']");if($ip_ele.html()){if($ip_ele.hasClass("active")){$ip_ele.removeClass("active");$("#selected_ip_list .badge[data-ip='"+ip+"']").remove()}else{$ip_ele.addClass("active");$("#selected_ip_list").append(''+ip+"")}}}function get_available_ip(){$.ajax({url:"/available_ips/"+$save_peer.attr("conf_id"),method:"GET"}).done(function(res){available_ips=res;let $list_group=$("#available_ip_modal .modal-body .list-group");$list_group.html("");$("#allowed_ips").val(available_ips[0]);available_ips.forEach(ip=>$list_group.append(''+ip+""))})}$("#available_ip_modal").on("show.bs.modal",()=>{$("#add_modal").addClass("ip_modal_open")}).on("hidden.bs.modal",function(){$("#add_modal").removeClass("ip_modal_open");let ips=[];let $selected_ip_list=$("#selected_ip_list");$selected_ip_list.children().each(function(){ips.push($(this).data("ip"))});ips.forEach(ele=>trigger_ip(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(){trigger_ip($(this).data("ip"))});let $ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),{keyboard:false,backdrop:"static"});$("#search_available_ip").on("click",function(){$ipModal.toggle();let $allowed_ips=$("#allowed_ips");if($allowed_ips.val().length>0){let s=$allowed_ips.val().split(",");for(let i=0;i{$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=>trigger_ip(ele))});$("#allowed_ips").on("keyup",function(){let s=clean_ip($(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('')}});$("#add_modal").on("show.bs.modal",function(event){generate_key();get_available_ip()}).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");generate_key()});let $addModal=new bootstrap.Modal(document.getElementById("add_modal"),{keyboard:false,backdrop:"static"});function clean_ip(val){let clean_ip=val.split(",");for(let i=0;i0){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")}});function bulk_add_peers(){let $new_add_amount=$("#new_add_amount");$save_peer.attr("disabled","disabled");$save_peer.html("Adding "+$new_add_amount.val()+" peers...");let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(clean_ip($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(clean_ip($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=$save_peer.attr("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(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"));$save_peer.removeAttr("disabled").html("Save")}else{load_data("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$save_peer.removeAttr("disabled").html("Save");showToast($new_add_amount.val()+" peers added successful!");$addModal.toggle()}}})}else{$("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");$save_peer.removeAttr("disabled");$save_peer.html("Add")}}else{$save_peer.removeAttr("disabled").html("Add")}}$save_peer.on("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){bulk_add_peers()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(clean_ip($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(clean_ip($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(clean_ip($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");$(this).attr("disabled","disabled");$(this).html("Adding...");if($allowed_ips.val()!==""&&$public_key.val()!==""&&$new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$(this).attr("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"));$save_peer.removeAttr("disabled").html("Save")}else{load_data("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$save_peer.removeAttr("disabled").html("Save");showToast("Add peer successful!");$addModal.toggle()}}})}else{$("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");$(this).removeAttr("disabled");$(this).html("Add")}}});let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),{keyboard:false});$body.on("click",".btn-qrcode-peer",function(){let src=$(this).attr("img_src");$.ajax({url:src,method:"GET"}).done(function(res){$("#qrcode_img").attr("src",res);qrcodeModal.toggle()})});let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),{keyboard:false,backdrop:"static"});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);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];deletePeers(config,peer_ids)});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(deleteModal._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none")}if(deleteBulkModal._isShown){$("#bulk_remove_peer_alert").html(response+$("#bulk_remove_peer_alert").html()).removeClass("d-none")}}else{if(deleteModal._isShown){deleteModal.toggle()}if(deleteBulkModal._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");deleteBulkModal.toggle()}load_data($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),{keyboard:false,backdrop:"static"});$body.on("click",".btn-setting-peer",function(){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 Peer":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);settingModal.toggle();endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(event){$("#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{settingModal.toggle();load_data($("#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;let $input=$("#search_peer_textbox");$input.on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(doneTyping,doneTypingInterval)});$input.on("keydown",function(){clearTimeout(typingTimer)});function doneTyping(){load_data($input.val())}$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(res){load_data($("#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(){var label=$(this).parent().siblings().children()[1];copyToClipboard($(this));label.innerHTML="COPIED!"});function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}$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){if(res==="true"){load_interval=interval;clearInterval(load_timeout);load_timeout=setInterval(function(){load_data($("#search_peer_textbox").val())},interval);showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+load_interval+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}})});$body.on("click",".refresh",function(){load_data($("#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")});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")}}}})});$("#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{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"]+"
")});deleteBulkModal.toggle()});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+"")}}$body.on("click",".delete-bulk-peer-item",function(){toggleBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){toggleBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");let changeObserver=new MutationObserver(function(mutationsList,observer){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=undefined;$("#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));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")){toggleBulkIP($(this))}})});$(deleteBulkModal._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){toggleBulkIP($(this))}})});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 download_all_config(confs){wireguard.generateZipFiles(confs)}$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){download_one_config(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){download_all_config(res)}}})});
\ 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='
";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();$.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()}).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
diff --git a/src/static/js/configurationsTools.js b/src/static/js/configurationsTools.js
new file mode 100644
index 0000000..e69de29
diff --git a/src/static/js/configurationsTools.min.js b/src/static/js/configurationsTools.min.js
new file mode 100644
index 0000000..e69de29
diff --git a/src/templates/configuration.html b/src/templates/configuration.html
index e888aee..041df3d 100644
--- a/src/templates/configuration.html
+++ b/src/templates/configuration.html
@@ -246,7 +246,7 @@
×
- This action is not reversible.
+ This action is not reversible.