diff --git a/README.md b/README.md index b83bfac..44ca4dd 100644 --- a/README.md +++ b/README.md @@ -536,5 +536,4 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! - +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! \ No newline at end of file diff --git a/src/api.py b/src/api.py new file mode 100644 index 0000000..22696d7 --- /dev/null +++ b/src/api.py @@ -0,0 +1,2 @@ +from dashboard import request, jsonify, app + diff --git a/src/dashboard.py b/src/dashboard.py index ad6e1f9..7380c35 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -28,8 +28,7 @@ from icmplib import ping, traceroute from flask_socketio import SocketIO # Import other python files -from util import regex_match, check_DNS, check_Allowed_IPs, check_remote_endpoint, \ - check_IP_with_range, clean_IP_with_range +from util import * # Dashboard Version DASHBOARD_VERSION = 'v3.0.5' @@ -375,6 +374,12 @@ def get_all_peers_data(config_name): get_endpoint(config_name) get_allowed_ip(conf_peer_data, config_name) +def getLockAccessPeers(config_name): + col = g.cur.execute(f"PRAGMA table_info({config_name}_restrict_access)").fetchall() + col = [a[1] for a in col] + data = g.cur.execute(f"SELECT * FROM {config_name}_restrict_access").fetchall() + result = [{col[i]: data[k][i] for i in range(len(col))} for k in range(len(data))] + return result def get_peers(config_name, search, sort_t): """ @@ -499,7 +504,19 @@ def get_conf_list(): total_sent FLOAT NULL, total_data FLOAT NULL, endpoint VARCHAR NULL, status VARCHAR NULL, latest_handshake VARCHAR NULL, allowed_ip VARCHAR NULL, cumu_receive FLOAT NULL, cumu_sent FLOAT NULL, cumu_data FLOAT NULL, mtu INT NULL, - keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, + keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, + PRIMARY KEY (id) + ) + """ + g.cur.execute(create_table) + create_table = f""" + CREATE TABLE IF NOT EXISTS {i}_restrict_access ( + id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, + endpoint_allowed_ip VARCHAR NULL, name VARCHAR NULL, total_receive FLOAT NULL, + total_sent FLOAT NULL, total_data FLOAT NULL, endpoint VARCHAR NULL, + status VARCHAR NULL, latest_handshake VARCHAR NULL, allowed_ip VARCHAR NULL, + cumu_receive FLOAT NULL, cumu_sent FLOAT NULL, cumu_data FLOAT NULL, mtu INT NULL, + keepalive INT NULL, remote_endpoint VARCHAR NULL, preshared_key VARCHAR NULL, PRIMARY KEY (id) ) """ @@ -620,7 +637,6 @@ def f_available_ips(config_name): Flask Functions """ - @app.teardown_request def close_DB(exception): """ @@ -1056,7 +1072,8 @@ def get_conf(config_name): "wg_ip": wg_ip, "sort_tag": sort, "dashboard_refresh_interval": int(config.get("Server", "dashboard_refresh_interval")), - "peer_display_mode": peer_display_mode + "peer_display_mode": peer_display_mode, + "lock_access_peers": getLockAccessPeers(config_name) } if result['data']['status'] == "stopped": result['data']['checked'] = "nope" @@ -1087,16 +1104,15 @@ def switch(config_name): shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: session["switch_msg"] = exc.output.strip().decode("utf-8") - return redirect('/') + return jsonify({"status": False, "reason":"Can't stop peer"}) elif status == "stopped": try: subprocess.check_output("wg-quick up " + config_name, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: session["switch_msg"] = exc.output.strip().decode("utf-8") - return redirect('/') - return redirect(request.referrer) - + return jsonify({"status": False, "reason":"Can't turn on peer"}) + return jsonify({"status": True, "reason":""}) @app.route('/add_peer_bulk/', methods=['POST']) def add_peer_bulk(config_name): @@ -1240,24 +1256,7 @@ def remove_peer(config_name): if not isinstance(keys, list): return config_name + " is not running." else: - sql_command = [] - wg_command = ["wg", "set", config_name] - for delete_key in delete_keys: - if delete_key not in keys: - return "This key does not exist" - sql_command.append("DELETE FROM " + config_name + " WHERE id = '" + delete_key + "';") - wg_command.append("peer") - wg_command.append(delete_key) - wg_command.append("remove") - try: - remove_wg = subprocess.check_output(" ".join(wg_command), - shell=True, stderr=subprocess.STDOUT) - save_wg = subprocess.check_output(f"wg-quick save {config_name}", shell=True, stderr=subprocess.STDOUT) - g.cur.executescript(' '.join(sql_command)) - g.db.commit() - except subprocess.CalledProcessError as exc: - return exc.output.strip() - return "true" + return deletePeers(config_name, delete_keys, g.cur, g.db) @app.route('/save_peer_setting/', methods=['POST']) @@ -1530,6 +1529,51 @@ def switch_display_mode(mode): return "false" +# APIs +@app.route('/api/togglePeerAccess', methods=['POST']) +def togglePeerAccess(): + data = request.get_json() + print(data['peerID']) + returnData = {"status": True, "reason": ""} + required = ['peerID', 'config'] + if checkJSONAllParameter(required, data): + checkUnlock = g.cur.execute(f"SELECT * FROM {data['config']} WHERE id='{data['peerID']}'").fetchone() + if checkUnlock: + moveUnlockToLock = g.cur.execute(f"INSERT INTO {data['config']}_restrict_access SELECT * FROM {data['config']} WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + print(g.cur.rowcount) + print(deletePeers(data['config'], [data['peerID']], g.cur, g.db)) + else: + moveLockToUnlock = g.cur.execute(f"SELECT * FROM {data['config']}_restrict_access WHERE id='{data['peerID']}'").fetchone() + try: + if len(moveLockToUnlock[-1]) == 0: + status = subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]}", + shell=True, stderr=subprocess.STDOUT) + else: + now = str(datetime.now().strftime("%m%d%Y%H%M%S")) + f_name = now + "_tmp_psk.txt" + f = open(f_name, "w+") + f.write(moveLockToUnlock[-1]) + f.close() + subprocess.check_output(f"wg set {data['config']} peer {moveLockToUnlock[0]} allowed-ips {moveLockToUnlock[11]} preshared-key {f_name}", + shell=True, stderr=subprocess.STDOUT) + os.remove(f_name) + status = subprocess.check_output(f"wg-quick save {data['config']}", shell=True, stderr=subprocess.STDOUT) + g.cur.execute(f"INSERT INTO {data['config']} SELECT * FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + if g.cur.rowcount == 1: + g.cur.execute(f"DELETE FROM {data['config']}_restrict_access WHERE id = '{data['peerID']}'") + + except subprocess.CalledProcessError as exc: + returnData["status"] = False + returnData["reason"] = exc.output.strip() + else: + returnData["status"] = False + returnData["reason"] = "Please provide all required parameters." + + return jsonify(returnData) + + + """ Dashboard Tools Related """ @@ -1624,6 +1668,7 @@ def init_dashboard(): """ Create dashboard default configuration. """ + # Set Default INI File if not os.path.isfile(DASHBOARD_CONF): diff --git a/src/static/css/dashboard.css b/src/static/css/dashboard.css index 71b7831..0c425e0 100644 --- a/src/static/css/dashboard.css +++ b/src/static/css/dashboard.css @@ -9,7 +9,7 @@ body { vertical-align: text-bottom; } -.btn-primary{ +.btn-primary { font-weight: bold; } @@ -22,8 +22,10 @@ body { top: 0; bottom: 0; left: 0; - z-index: 100; /* Behind the navbar */ - padding: 48px 0 0; /* Height of navbar */ + z-index: 100; + /* Behind the navbar */ + padding: 48px 0 0; + /* Height of navbar */ box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1); } @@ -33,7 +35,8 @@ body { height: calc(100vh - 48px); padding-top: .5rem; overflow-x: hidden; - overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */ + overflow-y: auto; + /* Scrollable contents if viewport is shorter than content. */ } @supports ((position: -webkit-sticky) or (position: sticky)) { @@ -73,6 +76,7 @@ body { text-transform: uppercase; } + /* * Navbar */ @@ -90,11 +94,11 @@ body { right: 1rem; } -.form-control{ +.form-control { transition: all 0.2s ease-in-out; } -.form-control:disabled{ +.form-control:disabled { cursor: not-allowed; } @@ -115,7 +119,7 @@ body { box-shadow: 0 0 0 3px rgba(255, 255, 255, .25); } -.dot{ +.dot { width: 10px; height: 10px; border-radius: 50px; @@ -123,157 +127,171 @@ body { margin-left: auto !important; } -.dot-running{ +.dot-running { background-color: #28a745!important; box-shadow: 0 0 0 0.2rem #28a74545; } -.h6-dot-running{ +.h6-dot-running { margin-left: 0.3rem; } -.dot-stopped{ +.dot-stopped { background-color: #6c757d!important; } -.card-running{ +.card-running { border-color: #28a745; } -.info h6{ +.info h6 { line-break: anywhere; - transition: 0.2s ease-in-out; + transition: all 0.4s cubic-bezier(0.96, -0.07, 0.34, 1.01); + opacity: 1; } -.info .row .col-sm{ +.info .row .col-sm { display: flex; flex-direction: column; } -.info .row .col-sm small{ +.info .row .col-sm small { display: flex; - } -.info .row .col-sm small strong:last-child(1){ +.info .row .col-sm small strong:last-child(1) { margin-left: auto !important; } -.btn-control{ +.btn-control { border: none !important; padding: 0 1rem 0 0; } -.btn-control:active, .btn-control:focus{ +.btn-control:active, +.btn-control:focus { background-color: transparent !important; border: none !important; box-shadow: none; } -.btn-qrcode-peer{ +.btn-qrcode-peer { padding: 0 !important; } -.btn-qrcode-peer:active, .btn-qrcode-peer:hover{ +.btn-qrcode-peer:active, +.btn-qrcode-peer:hover { transform: scale(0.9) rotate(180deg); border: 0 !important; } -.btn-download-peer:active, .btn-download-peer:hover{ +.btn-download-peer:active, +.btn-download-peer:hover { color: #17a2b8 !important; transform: translateY(5px); } -.share_peer_btn_group .btn-control{ +.share_peer_btn_group .btn-control { margin: 0 0 0 1rem; padding: 0 !important; transition: all 0.4s cubic-bezier(1, -0.43, 0, 1.37); } -.btn-control:hover{ +.btn-control:hover { background: white; } -.btn-delete-peer:hover{ +.btn-delete-peer:hover { color: #dc3545; } -.btn-lock-peer:hover{ - color: #6c757d; +.btn-lock-peer:hover { + color: #28a745; } -.btn-setting-peer:hover{ - color:#007bff +.btn-lock-peer.lock{ + color: #6c757d } -.btn-download-peer:hover{ +.btn-lock-peer.lock:hover{ + color: #6c757d +} + +.btn-setting-peer:hover { + color: #007bff +} + +.btn-download-peer:hover { color: #17a2b8; } -.login-container{ +.login-container { padding: 2rem; } -@media (max-width: 992px){ - .card-col{ +@media (max-width: 992px) { + .card-col { margin-bottom: 1rem; } } -.switch{ +.switch { font-size: 2rem; } -.switch:hover{ + +.switch:hover { text-decoration: none } -.btn-group-label:hover{ +.btn-group-label:hover { color: #007bff; border-color: #007bff; background: white; } -.peer_data_group{ +.peer_data_group { text-align: right; display: flex; margin-bottom: 0.5rem } -.peer_data_group p{ +.peer_data_group p { text-transform: uppercase; margin-bottom: 0; margin-right: 1rem } @media (max-width: 768px) { - .peer_data_group{ + .peer_data_group { text-align: left; } } -.index-switch{ +.index-switch { text-align: right; + display: flex; + align-items: center; + justify-content: flex-end; } -main{ +main { margin-bottom: 3rem; } -.peer_list{ +.peer_list { margin-bottom: 7rem } @media (max-width: 768px) { - .add_btn{ + .add_btn { bottom: 1.5rem !important; } - - .peer_list{ + .peer_list { margin-bottom: 7rem !important; } } -.btn-manage-group{ +.btn-manage-group { z-index: 99; position: fixed; bottom: 3rem; @@ -281,7 +299,7 @@ main{ display: flex; } -.btn-manage-group .setting_btn_menu{ +.btn-manage-group .setting_btn_menu { position: absolute; top: -124px; background-color: white; @@ -296,16 +314,16 @@ main{ transition: all 0.3s cubic-bezier(0.58, 0.03, 0.05, 1.28); } -.btn-manage-group .setting_btn_menu.show{ +.btn-manage-group .setting_btn_menu.show { display: block; } -.setting_btn_menu.showing{ +.setting_btn_menu.showing { transform: translateY(0px); opacity: 1; } -.setting_btn_menu a{ +.setting_btn_menu a { display: flex; padding: 0.5rem 1rem; transition: all 0.1s ease-in-out; @@ -314,36 +332,38 @@ main{ cursor: pointer; } -.setting_btn_menu a:hover{ +.setting_btn_menu a:hover { background-color: #efefef; text-decoration: none; } -.setting_btn_menu a i{ +.setting_btn_menu a i { margin-right: auto !important; } -.add_btn{ +.add_btn { height: 54px; z-index: 99; border-radius: 100px !important; padding: 0 14px; - box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); margin-right: 1rem; font-size: 1.5rem; } -.setting_btn{ +.setting_btn { height: 54px; z-index: 99; border-radius: 100px !important; padding: 0 14px; - box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); + box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); font-size: 1.5rem; } +@-webkit-keyframes rotating +/* Safari and Chrome */ -@-webkit-keyframes rotating /* Safari and Chrome */ { +{ from { -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); @@ -355,6 +375,7 @@ main{ transform: rotate(360deg); } } + @keyframes rotating { from { -ms-transform: rotate(0deg); @@ -380,7 +401,7 @@ main{ animation: rotating 0.75s linear infinite; } -.peer_private_key_textbox_switch{ +.peer_private_key_textbox_switch { position: absolute; right: 2rem; transform: translateY(-28px); @@ -388,139 +409,153 @@ main{ cursor: pointer; } -#peer_private_key_textbox, #private_key, #public_key, #peer_preshared_key_textbox{ - font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; +#peer_private_key_textbox, +#private_key, +#public_key, +#peer_preshared_key_textbox { + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } -.progress-bar{ +.progress-bar { transition: 0.3s ease-in-out; } -.key{ +.key { transition: 0.2s ease-in-out; cursor: pointer; } -.key:hover{ +.key:hover { color: #007bff; } -.card{ +.card { border-radius: 10px; } -.peer_list .card .button-group{ +.peer_list .card .button-group { height: 22px; } -.form-control{ +.form-control { border-radius: 10px; } -.btn{ +.btn { border-radius: 8px; /*padding: 0.6rem 0.9em;*/ } -#username, #password{ - padding: 0.6rem calc( 0.9rem + 32px ); +#username, +#password { + padding: 0.6rem calc( 0.9rem + 32px); height: inherit; } -label[for="username"], label[for="password"]{ +label[for="username"], +label[for="password"] { font-size: 1rem; margin: 0 !important; transform: translateY(30px) translateX(16px); padding: 0; } + /*label[for="password"]{*/ + + /* transform: translateY(32px) translateX(16px);*/ + + /*}*/ - -.modal-content{ +.modal-content { border-radius: 10px; } -.tooltip-inner{ +.tooltip-inner { font-size: 0.8rem; } @-webkit-keyframes loading { - 0%{ + 0% { background-color: #dfdfdf; } - 50%{ + 50% { background-color: #adadad; } - 100%{ - background-color: #dfdfdf; - } -} -@-moz-keyframes loading { - 0%{ - background-color: #dfdfdf; - } - 50%{ - background-color: #adadad; - } - 100%{ + 100% { background-color: #dfdfdf; } } -.conf_card{ +@-moz-keyframes loading { + 0% { + background-color: #dfdfdf; + } + 50% { + background-color: #adadad; + } + 100% { + background-color: #dfdfdf; + } +} + +.conf_card { transition: 0.2s ease-in-out; } -.conf_card:hover{ +.conf_card:hover { border-color: #007bff; cursor: pointer; } -.info_loading{ - animation: loading 2s infinite ease-in-out; - border-radius: 5px; - height: 19px; - transition: 0.3s ease-in-out; +.info_loading { + /* animation: loading 2s infinite ease-in-out; + /* border-radius: 5px; */ + height: 19.19px; + /* transition: 0.3s ease-in-out; */ + + /* transform: translateX(40px); */ + opacity: 0 !important; } -#conf_status_btn{ +#conf_status_btn { transition: 0.2s ease-in-out; } -#conf_status_btn.info_loading{ +#conf_status_btn.info_loading { height: 38px; border-radius: 5px; animation: loading 3s infinite ease-in-out; } -#qrcode_img img{ +#qrcode_img img { width: 100%; } -#selected_ip_list .badge, #selected_peer_list .badge{ +#selected_ip_list .badge, +#selected_peer_list .badge { margin: 0.1rem } -#add_modal.ip_modal_open{ +#add_modal.ip_modal_open { transition: filter 0.2s ease-in-out; filter: brightness(0.5); } -#delete_bulk_modal .list-group a.active{ +#delete_bulk_modal .list-group a.active { background-color: #dc3545; border-color: #dc3545; } -#selected_peer_list{ +#selected_peer_list { max-height: 80px; overflow-y: scroll; overflow-x: hidden; } -.no-response{ +.no-response { width: 100%; height: 100%; position: fixed; @@ -534,93 +569,195 @@ label[for="username"], label[for="password"]{ transition: all 1s ease-in-out; } -.no-response.active{ +.no-response.active { display: flex; } -.no-response.active.show{ +.no-response.active.show { opacity: 100; } -.no-response .container > *{ +.no-response .container>* { text-align: center; } -.no-responding{ +.no-responding { transition: all 1s ease-in-out; filter: blur(10px); } -pre.index-alert{ +pre.index-alert { margin-bottom: 0; padding: 1rem; background-color: #343a40; - border: 1px solid rgba(0,0,0,.125); + border: 1px solid rgba(0, 0, 0, .125); border-radius: .25rem; margin-top: 1rem; color: white; } -.peerNameCol{ +.peerNameCol { display: flex; align-items: center; margin-bottom: 0.2rem } -.peerName{ - margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +.peerName { + margin: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } -.peerLightContainer{ - text-transform: uppercase; margin: 0; margin-left: auto !important; +.peerLightContainer { + text-transform: uppercase; + margin: 0; + margin-left: auto !important; } -.conf_card .dot, .info .dot { +.conf_card .dot, +.info .dot { transform: translateX(10px); } -#config_body{ +#config_body { transition: 0.3s ease-in-out; } -#config_body.firstLoading{ +#config_body.firstLoading { opacity: 0.2; } -.chartTitle{ +.chartTitle { display: flex; } -.chartControl{ - margin-bottom: 1rem; +.chartControl { + margin-bottom: 1rem; display: flex; align-items: center; } -.chartTitle h6{ +.chartTitle h6 { margin-bottom: 0; line-height: 1; margin-right: 0.5rem; } -.chartContainer.fullScreen{ +.chartContainer.fullScreen { position: fixed; z-index: 9999; background-color: white; top: 0; left: 0; - width: calc( 100% + 15px ); + width: calc( 100% + 15px); height: 100%; padding: 32px; } -.chartContainer.fullScreen .col-sm{ +.chartContainer.fullScreen .col-sm { padding-right: 0; height: 100%; } -.chartContainer.fullScreen .chartCanvasContainer{ +.chartContainer.fullScreen .chartCanvasContainer { width: 100%; - height: calc( 100% - 47px ) !important; - max-height: calc( 100% - 47px ) !important; + height: calc( 100% - 47px) !important; + max-height: calc( 100% - 47px) !important; } + +#switch{ + transition: all 350ms ease-in; +} + +.toggle--switch{ + display: none; +} + +.toggleLabel{ + width: 64px; + height: 32px; + background-color: #6c757d17; + display: flex; + position: relative; + border: 2px solid #6c757d8c; + border-radius: 100px; + transition: all 350ms ease-in; + cursor: pointer; + margin: 0; +} + +.toggle--switch.waiting + .toggleLabel{ + opacity: 0.5; +} + +.toggleLabel::before{ + background-color: #6c757d; + height: 26px; + width: 26px; + content: ""; + border-radius: 100px; + margin: 1px; + position: absolute; + animation-name: off; + animation-duration: 350ms; + animation-fill-mode: forwards; + transition: all 350ms ease-in; + cursor: pointer; +} + +.toggle--switch:checked + .toggleLabel{ + background-color: #007bff17 !important; + border: 2px solid #007bff8c; +} + +.toggle--switch:checked + .toggleLabel::before{ + background-color: #007bff; + animation-name: on; + animation-duration: 350ms; + animation-fill-mode: forwards; +} + +@keyframes on { + 0%{ + left: 0px; + } + 60%{ + left: 0px; + width: 40px; + } + 100%{ + left: 32px; + width: 26px; + } +} + +@keyframes off { + 0%{ + left: 32px; + } + 60%{ + left: 18px; + width: 40px; + } + 100%{ + left: 0px; + width: 26px; + } +} + +.toast{ + min-width: 300px; + background-color: rgba(255,255,255,1); +} + +.toast-header{ + background-color: rgba(255,255,255); +} + +.toast-progressbar{ + width: 100%; + height: 4px; + background-color: #007bff; + border-bottom-left-radius: .25rem; +} \ No newline at end of file diff --git a/src/static/css/dashboard.min.css b/src/static/css/dashboard.min.css index 7a8b84c..6459c8b 100644 --- a/src/static/css/dashboard.min.css +++ b/src/static/css/dashboard.min.css @@ -1 +1 @@ -@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(360deg);-moz-transform:rotate(360deg);-webkit-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}@-moz-keyframes loading{0%,to{background-color:#dfdfdf}50%{background-color:#adadad}}body{font-size:.875rem}.feather{width:16px;height:16px;vertical-align:text-bottom}.btn-primary{font-weight:700}.sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;padding:48px 0 0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1)}.sidebar-sticky{position:relative;top:0;height:calc(100vh - 48px);padding-top:.5rem;overflow-x:hidden;overflow-y:auto}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{font-weight:500;color:#333;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{padding-left:30px;background-color:#dfdfdf}.sidebar .nav-link .feather{margin-right:4px;color:#999}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{padding-top:.75rem;padding-bottom:.75rem;font-size:1rem;background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25)}.navbar .navbar-toggler{top:.25rem;right:1rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{padding:.75rem 1rem;border-width:0;border-radius:0}.form-control-dark{color:#fff;background-color:rgba(255,255,255,.1);border-color:rgba(255,255,255,.1)}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px rgba(255,255,255,.25)}.dot{width:10px;height:10px;border-radius:50px;display:inline-block;margin-left:auto!important}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;transition:.2s ease-in-out}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:0!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:0!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{transform:scale(.9) rotate(180deg);border:0!important}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{color:#007bff;border-color:#007bff;background:#fff}.peer_data_group{text-align:right;display:flex;margin-bottom:.5rem}.peer_data_group p{text-transform:uppercase;margin-bottom:0;margin-right:1rem}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{z-index:99;position:fixed;bottom:3rem;right:2rem;display:flex}.btn-manage-group .setting_btn_menu{position:absolute;top:-124px;background-color:#fff;padding:1rem 0;right:0;box-shadow:0 10px 20px rgb(0 0 0/19%),0 6px 6px rgb(0 0 0/23%);border-radius:10px;min-width:200px;display:none;transform:translateY(-30px);opacity:0;transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{transform:translateY(0);opacity:1}.setting_btn_menu a{display:flex;padding:.5rem 1rem;transition:all .1s ease-in-out;font-size:1rem;align-items:center;cursor:pointer}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{height:54px;z-index:99;border-radius:100px!important;padding:0 14px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem}.rotating::before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{position:absolute;right:2rem;transform:translateY(-28px);font-size:1.2rem;cursor:pointer}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.progress-bar{transition:.3s ease-in-out}.key{transition:.2s ease-in-out;cursor:pointer}.key:hover{color:#007bff}.card,.form-control{border-radius:10px}.peer_list .card .button-group{height:22px}.btn{border-radius:8px}#password,#username{padding:.6rem calc(.9rem + 32px);height:inherit}label[for=password],label[for=username]{font-size:1rem;margin:0!important;transform:translateY(30px) translateX(16px);padding:0}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}#conf_status_btn,.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{animation:loading 2s infinite ease-in-out;border-radius:5px;height:19px;transition:.3s ease-in-out}#conf_status_btn.info_loading{height:38px;border-radius:5px;animation:loading 3s infinite ease-in-out}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{transition:filter .2s ease-in-out;filter:brightness(.5)}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-y:scroll;overflow-x:hidden}.no-responding,.no-response{transition:all 1s ease-in-out}.no-response{width:100%;height:100%;position:fixed;background:#000000ba;z-index:10000;display:none;flex-direction:column;align-items:center;justify-content:center;opacity:0}.no-response.active{display:flex}.no-response.active.show{opacity:100}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px)}pre.index-alert{margin-bottom:0;padding:1rem;background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;margin-top:1rem;color:#fff}.peerNameCol{display:flex;align-items:center;margin-bottom:.2rem}.peerName{margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.peerLightContainer{text-transform:uppercase;margin:0;margin-left:auto!important}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{margin-bottom:1rem;display:flex;align-items:center}.chartTitle h6{margin-bottom:0;line-height:1;margin-right:.5rem}.chartContainer.fullScreen{position:fixed;z-index:9999;background-color:#fff;top:0;left:0;width:calc(100% + 15px);height:100%;padding:32px}.chartContainer.fullScreen .col-sm{padding-right:0;height:100%}.chartContainer.fullScreen .chartCanvasContainer{width:100%;height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important} \ No newline at end of file +body{font-size:.875rem}.feather{height:16px;vertical-align:text-bottom;width:16px}.btn-primary{font-weight:700}.sidebar{bottom:0;box-shadow:inset -1px 0 0 rgba(0,0,0,.1);left:0;padding:48px 0 0;position:fixed;top:0;z-index:100}.sidebar-sticky{height:calc(100vh - 48px);overflow-x:hidden;overflow-y:auto;padding-top:.5rem;position:relative;top:0}@supports ((position:-webkit-sticky) or (position:sticky)){.sidebar-sticky{position:-webkit-sticky;position:sticky}}.sidebar .nav-link{color:#333;font-weight:500;transition:.2s cubic-bezier(.82,-.07,0,1.01)}.nav-link:hover{background-color:#dfdfdf;padding-left:30px}.sidebar .nav-link .feather{color:#999;margin-right:4px}.sidebar .nav-link.active{color:#007bff}.sidebar .nav-link.active .feather,.sidebar .nav-link:hover .feather{color:inherit}.sidebar-heading{font-size:.75rem;text-transform:uppercase}.navbar-brand{background-color:rgba(0,0,0,.25);box-shadow:inset -1px 0 0 rgba(0,0,0,.25);font-size:1rem;padding-bottom:.75rem;padding-top:.75rem}.navbar .navbar-toggler{right:1rem;top:.25rem}.form-control{transition:all .2s ease-in-out}.form-control:disabled{cursor:not-allowed}.navbar .form-control{border-radius:0;border-width:0;padding:.75rem 1rem}.form-control-dark{background-color:hsla(0,0%,100%,.1);border-color:hsla(0,0%,100%,.1);color:#fff}.form-control-dark:focus{border-color:transparent;box-shadow:0 0 0 3px hsla(0,0%,100%,.25)}.dot{border-radius:50px;display:inline-block;height:10px;margin-left:auto!important;width:10px}.dot-running{background-color:#28a745!important;box-shadow:0 0 0 .2rem #28a74545}.h6-dot-running{margin-left:.3rem}.dot-stopped{background-color:#6c757d!important}.card-running{border-color:#28a745}.info h6{line-break:anywhere;opacity:1;transition:all .4s cubic-bezier(.96,-.07,.34,1.01)}.info .row .col-sm{display:flex;flex-direction:column}.info .row .col-sm small{display:flex}.info .row .col-sm small strong:last-child(1){margin-left:auto!important}.btn-control{border:none!important;padding:0 1rem 0 0}.btn-control:active,.btn-control:focus{background-color:transparent!important;border:none!important;box-shadow:none}.btn-qrcode-peer{padding:0!important}.btn-qrcode-peer:active,.btn-qrcode-peer:hover{border:0!important;transform:scale(.9) rotate(180deg)}.btn-download-peer:active,.btn-download-peer:hover{color:#17a2b8!important;transform:translateY(5px)}.share_peer_btn_group .btn-control{margin:0 0 0 1rem;padding:0!important;transition:all .4s cubic-bezier(1,-.43,0,1.37)}.btn-control:hover{background:#fff}.btn-delete-peer:hover{color:#dc3545}.btn-lock-peer:hover{color:#28a745}.btn-lock-peer.lock,.btn-lock-peer.lock:hover{color:#6c757d}.btn-setting-peer:hover{color:#007bff}.btn-download-peer:hover{color:#17a2b8}.login-container{padding:2rem}@media (max-width:992px){.card-col{margin-bottom:1rem}}.switch{font-size:2rem}.switch:hover{text-decoration:none}.btn-group-label:hover{background:#fff;border-color:#007bff;color:#007bff}.peer_data_group{display:flex;margin-bottom:.5rem;text-align:right}.peer_data_group p{margin-bottom:0;margin-right:1rem;text-transform:uppercase}@media (max-width:768px){.peer_data_group{text-align:left}}.index-switch{align-items:center;display:flex;justify-content:flex-end;text-align:right}main{margin-bottom:3rem}.peer_list{margin-bottom:7rem}@media (max-width:768px){.add_btn{bottom:1.5rem!important}.peer_list{margin-bottom:7rem!important}}.btn-manage-group{bottom:3rem;display:flex;position:fixed;right:2rem;z-index:99}.btn-manage-group .setting_btn_menu{background-color:#fff;border-radius:10px;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);display:none;min-width:200px;opacity:0;padding:1rem 0;position:absolute;right:0;top:-124px;transform:translateY(-30px);transition:all .3s cubic-bezier(.58,.03,.05,1.28)}.btn-manage-group .setting_btn_menu.show{display:block}.setting_btn_menu.showing{opacity:1;transform:translateY(0)}.setting_btn_menu a{align-items:center;cursor:pointer;display:flex;font-size:1rem;padding:.5rem 1rem;transition:all .1s ease-in-out}.setting_btn_menu a:hover{background-color:#efefef;text-decoration:none}.setting_btn_menu a i{margin-right:auto!important}.add_btn{margin-right:1rem}.add_btn,.setting_btn{border-radius:100px!important;box-shadow:0 10px 20px rgba(0,0,0,.19),0 6px 6px rgba(0,0,0,.23);font-size:1.5rem;height:54px;padding:0 14px;z-index:99}@-webkit-keyframes rotating{0%{-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotating{0%{-ms-transform:rotate(0deg);-moz-transform:rotate(0deg);-webkit-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-ms-transform:rotate(1turn);-moz-transform:rotate(1turn);-webkit-transform:rotate(1turn);-o-transform:rotate(1turn);transform:rotate(1turn)}}.rotating:before{-webkit-animation:rotating .75s linear infinite;-moz-animation:rotating .75s linear infinite;-ms-animation:rotating .75s linear infinite;-o-animation:rotating .75s linear infinite;animation:rotating .75s linear infinite}.peer_private_key_textbox_switch{cursor:pointer;font-size:1.2rem;position:absolute;right:2rem;transform:translateY(-28px)}#peer_preshared_key_textbox,#peer_private_key_textbox,#private_key,#public_key{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.progress-bar{transition:.3s ease-in-out}.key{cursor:pointer;transition:.2s ease-in-out}.key:hover{color:#007bff}.card{border-radius:10px}.peer_list .card .button-group{height:22px}.form-control{border-radius:10px}.btn{border-radius:8px}#password,#username{height:inherit;padding:.6rem calc(.9rem + 32px)}label[for=password],label[for=username]{font-size:1rem;margin:0!important;padding:0;transform:translateY(30px) translateX(16px)}.modal-content{border-radius:10px}.tooltip-inner{font-size:.8rem}@-webkit-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}@-moz-keyframes loading{0%{background-color:#dfdfdf}50%{background-color:#adadad}to{background-color:#dfdfdf}}.conf_card{transition:.2s ease-in-out}.conf_card:hover{border-color:#007bff;cursor:pointer}.info_loading{height:19.19px;opacity:0!important}#conf_status_btn{transition:.2s ease-in-out}#conf_status_btn.info_loading{animation:loading 3s ease-in-out infinite;border-radius:5px;height:38px}#qrcode_img img{width:100%}#selected_ip_list .badge,#selected_peer_list .badge{margin:.1rem}#add_modal.ip_modal_open{filter:brightness(.5);transition:filter .2s ease-in-out}#delete_bulk_modal .list-group a.active{background-color:#dc3545;border-color:#dc3545}#selected_peer_list{max-height:80px;overflow-x:hidden;overflow-y:scroll}.no-response{align-items:center;background:#000000ba;display:none;flex-direction:column;height:100%;justify-content:center;opacity:0;position:fixed;transition:all 1s ease-in-out;width:100%;z-index:10000}.no-response.active{display:flex}.no-response.active.show{opacity:1}.no-response .container>*{text-align:center}.no-responding{filter:blur(10px);transition:all 1s ease-in-out}pre.index-alert{background-color:#343a40;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;color:#fff;margin-bottom:0;margin-top:1rem;padding:1rem}.peerNameCol{align-items:center;display:flex;margin-bottom:.2rem}.peerName{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.peerLightContainer{margin:0;margin-left:auto!important;text-transform:uppercase}.conf_card .dot,.info .dot{transform:translateX(10px)}#config_body{transition:.3s ease-in-out}#config_body.firstLoading{opacity:.2}.chartTitle{display:flex}.chartControl{align-items:center;display:flex;margin-bottom:1rem}.chartTitle h6{line-height:1;margin-bottom:0;margin-right:.5rem}.chartContainer.fullScreen{background-color:#fff;height:100%;left:0;padding:32px;position:fixed;top:0;width:calc(100% + 15px);z-index:9999}.chartContainer.fullScreen .col-sm{height:100%;padding-right:0}.chartContainer.fullScreen .chartCanvasContainer{height:calc(100% - 47px)!important;max-height:calc(100% - 47px)!important;width:100%}#switch{transition:all .35s ease-in}.toggle--switch{display:none}.toggleLabel{background-color:#6c757d17;border:2px solid #6c757d8c;border-radius:100px;cursor:pointer;display:flex;height:32px;margin:0;position:relative;transition:all .35s ease-in;width:64px}.toggle--switch.waiting+.toggleLabel{opacity:.5}.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:off;background-color:#6c757d;border-radius:100px;content:"";cursor:pointer;height:26px;margin:1px;position:absolute;transition:all .35s ease-in;width:26px}.toggle--switch:checked+.toggleLabel{background-color:#007bff17!important;border:2px solid #007bff8c}.toggle--switch:checked+.toggleLabel:before{animation-duration:.35s;animation-fill-mode:forwards;animation-name:on;background-color:#007bff}@keyframes on{0%{left:0}60%{left:0;width:40px}to{left:32px;width:26px}}@keyframes off{0%{left:32px}60%{left:18px;width:40px}to{left:0;width:26px}}.toast{min-width:300px}.toast,.toast-header{background-color:#fff}.toast-progressbar{background-color:#007bff;border-bottom-left-radius:.25rem;height:4px;width:100%} \ No newline at end of file diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index 021d851..09ff7a6 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -5,23 +5,22 @@ -(function(){ +(function() { /** * Definitions */ - let peers = []; let configuration_name; let configuration_interval; let configuration_timeout = window.localStorage.getItem("configurationTimeout"); - if (configuration_timeout === null || !["5000", "10000", "30000", "60000"].includes(configuration_timeout)){ + if (configuration_timeout === null || !["5000", "10000", "30000", "60000"].includes(configuration_timeout)) { window.localStorage.setItem("configurationTimeout", "10000"); configuration_timeout = window.localStorage.getItem("configurationTimeout"); } document.querySelector(`button[data-refresh-interval="${configuration_timeout}"]`).classList.add("active"); let display_mode = window.localStorage.getItem("displayMode"); - if (display_mode === null || !["grid", "list"].includes(display_mode)){ + if (display_mode === null || !["grid", "list"].includes(display_mode)) { window.localStorage.setItem("displayMode", "grid"); display_mode = "grid"; } @@ -48,11 +47,11 @@ */ let chartUnit = window.localStorage.chartUnit; let chartUnitAvailable = ["GB", "MB", "KB"]; - - if (chartUnit === null || !chartUnitAvailable.includes(chartUnit)){ + + if (chartUnit === null || !chartUnitAvailable.includes(chartUnit)) { window.localStorage.setItem("chartUnit", "GB"); $('.switchUnit[data-unit="GB"]').addClass("active"); - }else{ + } else { $(`.switchUnit[data-unit="${chartUnit}"]`).addClass("active"); } chartUnit = window.localStorage.getItem("chartUnit"); @@ -63,8 +62,7 @@ type: 'line', data: { labels: [], - datasets: [ - { + datasets: [{ label: 'Data Sent', data: [], stroke: '#FFFFFF', @@ -85,7 +83,7 @@ options: { maintainAspectRatio: false, showScale: false, - responsive:false, + responsive: false, scales: { y: { min: 0, @@ -108,21 +106,21 @@ } } }); - + let $totalDataUsageChartObj = $("#totalDataUsageChartObj"); $totalDataUsageChartObj.css("width", "100%"); totalDataUsageChartObj.width = $totalDataUsageChartObj.parent().width(); totalDataUsageChartObj.resize(); $(window).on("resize", function() { - totalDataUsageChartObj.resize(); + totalDataUsageChartObj.resize(); }); - $(".fullScreen").on("click", function(){ + $(".fullScreen").on("click", function() { let $chartContainer = $(".chartContainer"); - if ($chartContainer.hasClass("fullScreen")){ + if ($chartContainer.hasClass("fullScreen")) { $(this).children().removeClass("bi-fullscreen-exit").addClass("bi-fullscreen"); $chartContainer.removeClass("fullScreen"); - }else{ + } else { $(this).children().removeClass("bi-fullscreen").addClass("bi-fullscreen-exit"); $chartContainer.addClass("fullScreen"); } @@ -130,32 +128,32 @@ }); let mul = 1; - $(".switchUnit").on("click", function(){ + $(".switchUnit").on("click", function() { $(".switchUnit").removeClass("active"); $(this).addClass("active"); - if ($(this).data('unit') !== chartUnit){ + if ($(this).data('unit') !== chartUnit) { switch ($(this).data('unit')) { case "GB": - if (chartUnit === "MB"){ - mul = 1/1024; + if (chartUnit === "MB") { + mul = 1 / 1024; } - if (chartUnit === "KB"){ - mul = 1/1048576; + if (chartUnit === "KB") { + mul = 1 / 1048576; } break; case "MB": - if (chartUnit === "GB"){ + if (chartUnit === "GB") { mul = 1024; } - if (chartUnit === "KB"){ - mul = 1/1024; + if (chartUnit === "KB") { + mul = 1 / 1024; } break; case "KB": - if (chartUnit === "GB"){ + if (chartUnit === "GB") { mul = 1048576; } - if (chartUnit === "MB"){ + if (chartUnit === "MB") { mul = 1024; } break; @@ -176,7 +174,7 @@ * @param response */ function configurationAlert(response) { - if (response.listen_port === "" && response.status === "stopped"){ + if (response.listen_port === "" && response.status === "stopped") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -184,7 +182,7 @@ configAlert.innerHTML = 'Peer QR Code and configuration file download required a specified Listen Port.'; document.querySelector("#config_info_alert").appendChild(configAlert); } - if (response.conf_address === "N/A"){ + if (response.conf_address === "N/A") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -194,21 +192,21 @@ } } - function setActiveConfigurationName(){ + function setActiveConfigurationName() { $(".nav-conf-link").removeClass("active"); $(`.sb-${configuration_name}-url`).addClass("active"); } let firstLoading = true; - $(".nav-conf-link").on("click", function(e){ + $(".nav-conf-link").on("click", function(e) { e.preventDefault(); - if (configuration_name !== $(this).data("conf-id")){ + if (configuration_name !== $(this).data("conf-id")) { firstLoading = true; $("#config_body").addClass("firstLoading"); configuration_name = $(this).data("conf-id"); - if(loadPeers($('#search_peer_textbox').val())){ + if (loadPeers($('#search_peer_textbox').val())) { setActiveConfigurationName(); - window.history.pushState(null,null,`/configuration/${configuration_name}`); + window.history.pushState(null, null, `/configuration/${configuration_name}`); $("title").text(`${configuration_name} | WGDashboard`); totalDataUsageChartObj.data.labels = []; @@ -224,26 +222,28 @@ * @param response */ function configurationHeader(response) { - let $conf_status_btn = document.getElementById("conf_status_btn"); - if (response.checked === "checked"){ - $conf_status_btn.innerHTML = ` ON`; - }else{ - $conf_status_btn.innerHTML = ` OFF`; - } + let $conf_status_btn = $(".toggle--switch"); - if (response.running_peer > 0){ + if (response.checked === "checked") { + $conf_status_btn.prop("checked", true) + }else{ + $conf_status_btn.prop("checked", false) + } + $conf_status_btn.data("conf-id", configuration_name) + + + if (response.running_peer > 0) { let d = new Date(); - let time = d.toLocaleString("en-us", - {hour: '2-digit', minute: '2-digit', second: "2-digit", hourCycle: 'h23'}); + let time = d.toLocaleString("en-us", { hour: '2-digit', minute: '2-digit', second: "2-digit", hourCycle: 'h23' }); totalDataUsageChartObj.data.labels.push(`${time}`); - if (totalDataUsageChartObj.data.datasets[0].data.length === 0){ + if (totalDataUsageChartObj.data.datasets[0].data.length === 0) { totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; totalDataUsageChartObj.data.datasets[0].data.push(0); totalDataUsageChartObj.data.datasets[1].data.push(0); - }else{ - if (totalDataUsageChartObj.data.datasets[0].data.length === 50 && totalDataUsageChartObj.data.datasets[1].data.length === 50){ + } else { + if (totalDataUsageChartObj.data.datasets[0].data.length === 50 && totalDataUsageChartObj.data.datasets[1].data.length === 50) { totalDataUsageChartObj.data.labels.shift(); totalDataUsageChartObj.data.datasets[0].data.shift(); totalDataUsageChartObj.data.datasets[1].data.shift(); @@ -252,16 +252,15 @@ let newTotalReceive = response.total_data_usage[2] - totalDataUsageChartObj.data.datasets[1].lastData; let newTotalSent = response.total_data_usage[1] - totalDataUsageChartObj.data.datasets[0].lastData; let k = 0; - if (chartUnit === "MB"){ + if (chartUnit === "MB") { k = 1024; - } - else if (chartUnit === "KB"){ + } else if (chartUnit === "KB") { k = 1048576; - }else{ + } else { k = 1; } - totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive*k); - totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent*k); + totalDataUsageChartObj.data.datasets[1].data.push(newTotalReceive * k); + totalDataUsageChartObj.data.datasets[0].data.push(newTotalSent * k); totalDataUsageChartObj.data.datasets[0].lastData = response.total_data_usage[1]; totalDataUsageChartObj.data.datasets[1].lastData = response.total_data_usage[2]; } @@ -270,11 +269,9 @@ } document.querySelector("#conf_name").textContent = configuration_name; - $conf_status_btn.classList.remove("info_loading"); + $("#switch").removeClass("info_loading"); document.querySelectorAll("#sort_by_dropdown option").forEach(ele => ele.removeAttribute("selected")); document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected", "selected"); - // document.querySelectorAll(".interval-btn-group button").forEach(ele => ele.classList.remove("active")); - // document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active"); document.querySelector("#conf_status").innerHTML = `${response.status}`; document.querySelector("#conf_connected_peers").innerHTML = response.running_peer; document.querySelector("#conf_total_data_usage").innerHTML = `${response.total_data_usage[0]} GB`; @@ -283,20 +280,26 @@ document.querySelector("#conf_public_key").innerHTML = response.public_key; document.querySelector("#conf_listen_port").innerHTML = response.listen_port === "" ? "N/A" : response.listen_port; document.querySelector("#conf_address").innerHTML = response.conf_address; - document.querySelectorAll(".info h6").forEach(ele => ele.classList.remove("info_loading")); + let delay = 0; + let h6 = $(".info h6"); + for (let i = 0; i < h6.length; i++){ + setTimeout(function(){ + $(h6[i]).removeClass("info_loading"); + }, delay) + delay += 40 + } } - /** * Parse all responded information onto the peers list * @param response */ function configurationPeers(response) { let result = ""; - if (response.peer_data.length === 0){ + if (response.peer_data.length === 0) { document.querySelector(".peer_list").innerHTML = `

Oops! No peers found ‘︿’

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

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

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

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

+

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

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

Oops! No peers found ‘︿’

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

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

-

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

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

Oops! No peers found ‘︿’

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

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

\n

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

\n
`,peer_key='
PEERCLICK TO COPY
'+peer.id+"
",peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
",peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
",peer_endpoint='
END POINT
'+peer.endpoint+"
",peer_control=`\n
\n
\n
\n \n \n `;""!==peer.private_key&&(peer_control+=''),peer_control+="
";let html='
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
";result+=html})),document.querySelector(".peer_list").innerHTML=result,void 0===configuration_interval&&setConfigurationInterval()}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key"),data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid"))if(""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=configuration_name,keys=[];for(let i=0;i<$new_add_amount.val();i++)keys.push(window.wireguard.generateKeypair());$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({DNS:$new_add_DNS.val(),endpoint_allowed_ip:$new_add_endpoint_allowed_ip.val(),MTU:$new_add_MTU.val(),keep_alive:$new_add_keep_alive.val(),enable_preshared_key:$enable_preshare_key.prop("checked"),keys:keys,amount:$new_add_amount.val()}),success:function(response){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast($new_add_amount.val()+" peers added successful!"),window.configurations.addModal().toggle())}})}else $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Add";else $add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Add"}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if("true"!==response){if(window.configurations.deleteModal()._isShown&&($("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none"),$("#delete_peer").removeAttr("disabled").html("Delete")),window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none"),$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else window.configurations.deleteModal()._isShown&&window.configurations.deleteModal().toggle(),window.configurations.deleteBulkModal()._isShown&&($("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"),$("#selected_peer_list").html(""),$(".delete-bulk-peer-item.active").removeClass("active"),window.configurations.deleteBulkModal().toggle()),window.configurations.loadPeers($("#search_peer_textbox").val()),$("#alertToast").toast("show"),$("#alertToast .toast-body").html("Peer deleted!"),$("#delete_peer").removeAttr("disabled").html("Delete")}})}function noResponding(message="Opps!
I can't connect to the server."){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active")),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show")),document.querySelector("#right_body").classList.add("no-responding"),document.querySelector(".navbar").classList.add("no-responding"),document.querySelector(".no-response .container h4").innerHTML=message}),10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show")),document.querySelector("#right_body").classList.remove("no-responding"),document.querySelector(".navbar").classList.remove("no-responding"),setTimeout((function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))}),1010)}function setConfigurationInterval(){configuration_interval=setInterval((function(){loadPeers($("#search_peer_textbox").val())}),configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%"),setTimeout((function(){stillLoadingProgressBar()}),300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%"),setTimeout((function(){$progress_bar.css("opacity","0")}),250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}$(".nav-conf-link").on("click",(function(e){e.preventDefault(),configuration_name!==$(this).data("conf-id")&&(firstLoading=!0,$("#config_body").addClass("firstLoading"),configuration_name=$(this).data("conf-id"),loadPeers($("#search_peer_textbox").val())&&(setActiveConfigurationName(),window.history.pushState(null,null,`/configuration/${configuration_name}`),$("title").text(`${configuration_name} | WGDashboard`),totalDataUsageChartObj.data.labels=[],totalDataUsageChartObj.data.datasets[0].data=[],totalDataUsageChartObj.data.datasets[1].data=[],totalDataUsageChartObj.update()))}));let time=0,count=0,d1=new Date;function loadPeers(searchString){d1=new Date;let good=!0;return $.ajax({method:"GET",url:`/get_config/${configuration_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done((function(response){console.log(response),parsePeers(response)})).fail((function(){noResponding(),good=!1})),good}function parsePeers(response){if(response.status){let d2,seconds=new Date-d1;time+=seconds,count+=1,window.console.log(`Average time: ${time/count}ms`),$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`),removeNoResponding(),peers=response.data.peer_data,configurationAlert(response.data),configurationHeader(response.data),configurationPeers(response.data),$(".dot.dot-running").attr("title","Peer Connected").tooltip(),$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(),$("i[data-toggle='tooltip']").tooltip(),$("#configuration_name").text(configuration_name),firstLoading&&(firstLoading=!1,$("#config_body").removeClass("firstLoading"))}else noResponding(response.message),removeConfigurationInterval()}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey,document.querySelector("#public_key").value=keys.publicKey,document.querySelector("#add_peer_alert").classList.add("d-none"),document.querySelector("#re_generate_key i").classList.remove("rotating"),document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show"),$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(interval){configuration_timeout=interval,window.localStorage.setItem("configurationTimeout",configuration_timeout.toString()),removeConfigurationInterval(),setConfigurationInterval(),showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`))}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob),link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list"),id=element.data("id"),name=""===element.data("name")?"Untitled Peer":element.data("name");element.hasClass("active")?(element.removeClass("active"),$("#selected_peer_list .badge[data-id='"+id+"']").remove()):(element.addClass("active"),$selected_peer_list.append(''+name+" - "+id+""))}function copyToClipboard(element){let $temp=$("");$body.append($temp),$temp.val($(element).text()).trigger("select"),document.execCommand("copy"),$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${configuration_name}`,method:"GET"}).done((function(res){if(!0===res.status){available_ips=res.data;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="",document.querySelector("#allowed_ips").value=available_ips[0],available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)}else document.querySelector("#allowed_ips").value=res.message,document.querySelector("#search_available_ip").setAttribute("disabled","disabled")}))}window.configurations={addModal:()=>addModal,deleteBulkModal:()=>deleteBulkModal,deleteModal:()=>deleteModal,ipModal:()=>ipModal,qrcodeModal:()=>qrcodeModal,settingModal:()=>settingModal,configurationTimeout:()=>configuration_timeout,updateDisplayMode:()=>{display_mode=window.localStorage.getItem("displayMode")},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},parsePeers:response=>{parsePeers(response)},setConfigurationName:confName=>{configuration_name=confName},getConfigurationName:()=>configuration_name,setActiveConfigurationName:()=>{setActiveConfigurationName()},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:interval=>{updateRefreshInterval(interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>cleanIp(val),startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}}();let $body=$("body"),available_ips=[],$add_peer=document.getElementById("save_peer"),typingTimer;document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()}),document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");selector.contains(event.target)&&(selector.style.display="none",document.querySelector("div[role=status]").style.display="inline-block",location.replace(`/switch/${selector.getAttribute("id")}`))}),document.querySelector("#private_key").addEventListener("change",event=>{let publicKey=document.querySelector("#public_key");44===event.target.value.length?(publicKey.value=window.wireguard.generatePublicKey(event.target.value),publicKey.setAttribute("disabled","disabled")):(publicKey.attributes.removeNamedItem("disabled"),publicKey.value="")}),$("#add_modal").on("show.bs.modal",(function(){window.configurations.generateKeyPair(),window.configurations.getAvailableIps()})).on("hide.bs.modal",(function(){$("#allowed_ips_indicator").html("")})),$("#re_generate_key").on("click",(function(){$("#public_key").attr("disabled","disabled"),$("#re_generate_key i").addClass("rotating"),window.configurations.generateKeyPair()})),$("#allowed_ips").on("keyup",(function(){let s=window.configurations.cleanIp($(this).val());s=s.split(","),available_ips.includes(s[s.length-1])?$("#allowed_ips_indicator").removeClass().addClass("text-success").html(''):$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')})),$("#peer_name_textbox").on("keyup",(function(){$(".peer_name").html($(this).val())})),$add_peer.addEventListener("click",(function(){let $bulk_add;if($("#bulk_add").prop("checked"))$("#new_add_amount").hasClass("is-invalid")||window.configurations.addPeersByBulk();else{let $public_key=$("#public_key"),$private_key=$("#private_key"),$allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_name=$("#new_add_name"),$new_add_MTU=$("#new_add_MTU"),$new_add_keep_alive=$("#new_add_keep_alive"),$enable_preshare_key=$("#enable_preshare_key");if($add_peer.setAttribute("disabled","disabled"),$add_peer.innerHTML="Adding...",""!==$allowed_ips.val()&&""!==$public_key.val()&&""!==$new_add_DNS.val()&&""!==$new_add_endpoint_allowed_ip.val()){let conf=window.configurations.getConfigurationName(),data_list=[$private_key,$allowed_ips,$new_add_name,$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];data_list.forEach(ele=>ele.attr("disabled","disabled")),$.ajax({method:"POST",url:"/add_peer/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({private_key:$private_key.val(),public_key:$public_key.val(),allowed_ips:$allowed_ips.val(),name:$new_add_name.val(),DNS:$new_add_DNS.val(),endpoint_allowed_ip:$new_add_endpoint_allowed_ip.val(),MTU:$new_add_MTU.val(),keep_alive:$new_add_keep_alive.val(),enable_preshared_key:$enable_preshare_key.prop("checked"),preshared_key:$enable_preshare_key.val()}),success:function(response){"true"!==response?($("#add_peer_alert").html(response).removeClass("d-none"),data_list.forEach(ele=>ele.removeAttr("disabled")),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save"):(window.configurations.loadPeers(""),data_list.forEach(ele=>ele.removeAttr("disabled")),$("#add_peer_form").trigger("reset"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Save",window.configurations.showToast("Add peer successful!"),window.configurations.addModal().toggle())}})}else $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"),$add_peer.removeAttribute("disabled"),$add_peer.innerHTML="Add"}})),$("#new_add_amount").on("keyup",(function(){let $bulk_amount_validation=$("#bulk_amount_validation");$(this).val().length>0?isNaN($(this).val())?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter a valid integer")):$(this).val()>available_ips.length?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`)):$(this).val()<1?($(this).removeClass("is-valid").addClass("is-invalid"),$bulk_amount_validation.html("Please enter at least 1 or more.")):$(this).removeClass("is-invalid").addClass("is-valid"):$(this).removeClass("is-invalid").removeClass("is-valid")})),$("#bulk_add").on("change",(function(){let hide=$(".non-bulk"),amount=$("#new_add_amount");if(!0===$(this).prop("checked")){for(let i=0;i{document.querySelector("#add_modal").classList.add("ip_modal_open")}).on("hidden.bs.modal",()=>{document.querySelector("#add_modal").classList.remove("ip_modal_open");let ips=[],$selected_ip_list=document.querySelector("#selected_ip_list");for(let i=0;i<$selected_ip_list.childElementCount;i++)ips.push($selected_ip_list.children[i].dataset.ip);ips.forEach(ele=>window.configurations.triggerIp(ele))}),$body.on("click",".available-ip-badge",(function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active"),$(this).remove()})),$body.on("click",".available-ip-item",(function(){window.configurations.triggerIp($(this).data("ip"))})),$("#search_available_ip").on("click",(function(){window.configurations.ipModal().toggle();let $allowed_ips=document.querySelector("#allowed_ips");if($allowed_ips.value.length>0){let s=$allowed_ips.value.split(",");for(let i=0;i{window.configurations.ipModal().toggle();let ips=[],$selected_ip_list;$("#selected_ip_list").children().each((function(){ips.push($(this).data("ip"))})),$("#allowed_ips").val(ips.join(", ")),ips.forEach(ele=>window.configurations.triggerIp(ele))}),$body.on("click",".btn-qrcode-peer",(function(){let src=$(this).data("imgsrc");$.ajax({url:src,method:"GET"}).done((function(res){$("#qrcode_img").attr("src",res),window.configurations.qrcodeModal().toggle()}))})),$body.on("click",".btn-delete-peer",(function(){let peer_id=$(this).attr("id");$("#delete_peer").data("peer-id",peer_id),window.configurations.deleteModal().toggle()})),$body.on("click",".btn-lock-peer",(function(){let $lockGlyph="bi-lock-fill",$unlockGlyph="bi-unlock-fill";$(this).children().hasClass($lockGlyph)?($(this).children().removeClass($lockGlyph).addClass($unlockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Lock Peer").tooltip("show")):($(this).children().removeClass($unlockGlyph).addClass($lockGlyph),$(this).children().tooltip("hide").attr("data-original-title","Unlock Peer").tooltip("show"))})),$("#delete_peer").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Deleting...");let config=window.configurations.getConfigurationName(),peer_ids=[$(this).data("peer-id")];window.configurations.deletePeers(config,peer_ids)})),$body.on("click",".btn-setting-peer",(function(){let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id),$.ajax({method:"POST",url:"/get_peer_data/"+window.configurations.getConfigurationName(),headers:{"Content-Type":"application/json"},data:JSON.stringify({id:peer_id}),success:function(response){let peer_name=""===response.name?"Untitled":response.name;$("#setting_modal .peer_name").html(peer_name),$("#setting_modal #peer_name_textbox").val(response.name),$("#setting_modal #peer_private_key_textbox").val(response.private_key),$("#setting_modal #peer_DNS_textbox").val(response.DNS),$("#setting_modal #peer_allowed_ip_textbox").val(response.allowed_ip),$("#setting_modal #peer_endpoint_allowed_ips").val(response.endpoint_allowed_ip),$("#setting_modal #peer_mtu").val(response.mtu),$("#setting_modal #peer_keep_alive").val(response.keep_alive),$("#setting_modal #peer_preshared_key_textbox").val(response.preshared_key),window.configurations.settingModal().toggle(),window.configurations.endProgressBar()}})})),$("#setting_modal").on("hidden.bs.modal",(function(){$("#setting_peer_alert").addClass("d-none")})),$("#peer_private_key_textbox").on("change",(function(){let $save_peer_setting=$("#save_peer_setting");$(this).val().length>0&&$.ajax({url:"/check_key_match/"+window.configurations.getConfigurationName(),method:"POST",headers:{"Content-Type":"application/json"},data:JSON.stringify({private_key:$("#peer_private_key_textbox").val(),public_key:$save_peer_setting.attr("peer_id")})}).done((function(res){"failed"===res.status?$("#setting_peer_alert").html(res.status).removeClass("d-none"):$("#setting_peer_alert").addClass("d-none")}))})),$("#save_peer_setting").on("click",(function(){$(this).attr("disabled","disabled"),$(this).html("Saving...");let $peer_DNS_textbox=$("#peer_DNS_textbox"),$peer_allowed_ip_textbox=$("#peer_allowed_ip_textbox"),$peer_endpoint_allowed_ips=$("#peer_endpoint_allowed_ips"),$peer_name_textbox=$("#peer_name_textbox"),$peer_private_key_textbox=$("#peer_private_key_textbox"),$peer_preshared_key_textbox=$("#peer_preshared_key_textbox"),$peer_mtu=$("#peer_mtu"),$peer_keep_alive=$("#peer_keep_alive");if(""!==$peer_DNS_textbox.val()&&""!==$peer_allowed_ip_textbox.val()&&""!==$peer_endpoint_allowed_ips.val()){let peer_id=$(this).attr("peer_id"),conf_id=$(this).attr("conf_id"),data_list=[$peer_name_textbox,$peer_DNS_textbox,$peer_private_key_textbox,$peer_preshared_key_textbox,$peer_allowed_ip_textbox,$peer_endpoint_allowed_ips,$peer_mtu,$peer_keep_alive];data_list.forEach(ele=>ele.attr("disabled","disabled")),$.ajax({method:"POST",url:"/save_peer_setting/"+conf_id,headers:{"Content-Type":"application/json"},data:JSON.stringify({id:peer_id,name:$peer_name_textbox.val(),DNS:$peer_DNS_textbox.val(),private_key:$peer_private_key_textbox.val(),allowed_ip:$peer_allowed_ip_textbox.val(),endpoint_allowed_ip:$peer_endpoint_allowed_ips.val(),MTU:$peer_mtu.val(),keep_alive:$peer_keep_alive.val(),preshared_key:$peer_preshared_key_textbox.val()}),success:function(response){"failed"===response.status?$("#setting_peer_alert").html(response.msg).removeClass("d-none"):(window.configurations.settingModal().toggle(),window.configurations.loadPeers($("#search_peer_textbox").val()),$("#alertToast").toast("show"),$("#alertToast .toast-body").html("Peer Saved!")),$("#save_peer_setting").removeAttr("disabled").html("Save"),data_list.forEach(ele=>ele.removeAttr("disabled"))}})}else $("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none"),$("#save_peer_setting").removeAttr("disabled").html("Save")})),$(".peer_private_key_textbox_switch").on("click",(function(){let $peer_private_key_textbox=$("#peer_private_key_textbox"),mode="password"===$peer_private_key_textbox.attr("type")?"text":"password",icon="password"===$peer_private_key_textbox.attr("type")?"bi bi-eye-slash-fill":"bi bi-eye-fill";$peer_private_key_textbox.attr("type",mode),$(".peer_private_key_textbox_switch i").removeClass().addClass(icon)}));let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",(function(){clearTimeout(typingTimer),typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)})).on("keydown",(function(){clearTimeout(typingTimer)})),$body.on("change","#sort_by_dropdown",(function(){$.ajax({method:"POST",data:JSON.stringify({sort:$("#sort_by_dropdown option:selected").val()}),headers:{"Content-Type":"application/json"},url:"/update_dashboard_sort",success:function(){window.configurations.loadPeers($("#search_peer_textbox").val())}})})),$body.on("mouseenter",".key",(function(){let label;$(this).parent().siblings().children()[1].style.opacity="100"})).on("mouseout",".key",(function(){let label=$(this).parent().siblings().children()[1];label.style.opacity="0",setTimeout((function(){label.innerHTML="CLICK TO COPY"}),200)})).on("click",".key",(function(){let label=$(this).parent().siblings().children()[1];window.configurations.copyToClipboard($(this)),label.innerHTML="COPIED!"})),$body.on("click",".update_interval",(function(){let _new;$(".interval-btn-group button").removeClass("active"),$(this).addClass("active");let interval=$(this).data("refresh-interval");[5e3,1e4,3e4,6e4].includes(interval)&&window.configurations.updateRefreshInterval(interval)})),$body.on("click",".refresh",(function(){window.configurations.loadPeers($("#search_peer_textbox").val())})),$body.on("click",".display_mode",(function(){$(".display-btn-group button").removeClass("active"),$(this).addClass("active"),window.localStorage.setItem("displayMode",$(this).data("display-mode")),window.configurations.updateDisplayMode(),"list"===$(this).data("display-mode")?(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-12")})),window.configurations.showToast("Displaying as List")):(Array($(".peer_list").children()).forEach((function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")})),window.configurations.showToast("Displaying as Grids"))}));let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",-1*($setting_btn_menu.height()+54));let $setting_btn=$(".setting_btn");$setting_btn.on("click",(function(){$setting_btn_menu.hasClass("show")?($setting_btn_menu.removeClass("showing"),setTimeout((function(){$setting_btn_menu.removeClass("show")}),201)):($setting_btn_menu.addClass("show"),setTimeout((function(){$setting_btn_menu.addClass("showing")}),10))})),$("html").on("click",(function(r){document.querySelector(".setting_btn")!==r.target&&(document.querySelector(".setting_btn").contains(r.target)||document.querySelector(".setting_btn_menu").contains(r.target)||($setting_btn_menu.removeClass("showing"),setTimeout((function(){$setting_btn_menu.removeClass("show")}),310)))})),$("#delete_peers_by_bulk_btn").on("click",()=>{let $delete_bulk_modal_list=$("#delete_bulk_modal .list-group");$delete_bulk_modal_list.html(""),peers.forEach(peer=>{let name;name=""===peer.name?"Untitled Peer":peer.name,$delete_bulk_modal_list.append(''+name+"
"+peer.id+"
")}),window.configurations.deleteBulkModal().toggle()}),$body.on("click",".delete-bulk-peer-item",(function(){window.configurations.toggleDeleteByBulkIP($(this))})).on("click",".delete-peer-bulk-badge",(function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))}));let $selected_peer_list=document.getElementById("selected_peer_list"),changeObserver=new MutationObserver((function(){$selected_peer_list.hasChildNodes()?$("#confirm_delete_bulk_peers").removeAttr("disabled"):$("#confirm_delete_bulk_peers").attr("disabled","disabled")})),confirm_delete_bulk_peers_interval;changeObserver.observe($selected_peer_list,{attributes:!0,childList:!0,characterData:!0}),$("#confirm_delete_bulk_peers").on("click",(function(){let btn=$(this);if(void 0!==confirm_delete_bulk_peers_interval)clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0,btn.html("Delete");else{let timer=5;btn.html(`Deleting in ${timer} secs... Click to cancel`),confirm_delete_bulk_peers_interval=setInterval((function(){if(timer-=1,btn.html(`Deleting in ${timer} secs... Click to cancel`),0===timer){btn.html("Deleting..."),btn.attr("disabled","disabled");let ips=[];$selected_peer_list.childNodes.forEach(ele=>ips.push(ele.dataset.id)),window.configurations.deletePeers(window.configurations.getConfigurationName(),ips),clearInterval(confirm_delete_bulk_peers_interval),confirm_delete_bulk_peers_interval=void 0}}),1e3)}})),$("#select_all_delete_bulk_peers").on("click",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")||window.configurations.toggleDeleteByBulkIP($(this))}))})),$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",(function(){$(".delete-bulk-peer-item").each((function(){$(this).hasClass("active")&&window.configurations.toggleDeleteByBulkIP($(this))}))})),$body.on("click",".btn-download-peer",(function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})})),$("#download_all_peers").on("click",(function(){$.ajax({url:`/download_all/${window.configurations.getConfigurationName()}`,method:"GET",success:function(res){res.peers.length>0?(window.wireguard.generateZipFiles(res),window.configurations.showToast("Peers' zip file download successful!")):window.configurations.showToast("Oops! There are no peer can be download.")}})})); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index 2f659a4..70c5b67 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -27,9 +27,10 @@
SWITCH
-
-
@@ -424,8 +425,8 @@
-
-