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

Hmmmm... What about SocketIO?

This commit is contained in:
Donald Cheng Hong Zou 2022-01-19 10:27:17 -05:00
parent fcfd816cec
commit 84c9846f7b
4 changed files with 79 additions and 31 deletions

View File

@ -25,6 +25,8 @@ import ifcfg
from flask import Flask, request, render_template, redirect, url_for, session, jsonify from flask import Flask, request, render_template, redirect, url_for, session, jsonify
from flask_qrcode import QRcode from flask_qrcode import QRcode
from icmplib import ping, traceroute from icmplib import ping, traceroute
# TESTING
from flask_socketio import SocketIO
# Import other python files # Import other python files
from util import regex_match, check_DNS, check_Allowed_IPs, check_remote_endpoint, \ from util import regex_match, check_DNS, check_Allowed_IPs, check_remote_endpoint, \
@ -49,7 +51,7 @@ app.secret_key = secrets.token_urlsafe(16)
app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['TEMPLATES_AUTO_RELOAD'] = True
# Enable QR Code Generator # Enable QR Code Generator
QRcode(app) QRcode(app)
socketio = SocketIO(app)
# TODO: use class and object oriented programming # TODO: use class and object oriented programming
@ -1001,17 +1003,26 @@ def configuration(config_name):
# Get configuration details # Get configuration details
@app.route('/get_config/<config_name>', methods=['GET']) @socketio.on("get_config")
def get_conf(config_name): # @app.route('/get_config/<config_name>', methods=['GET'])
def get_conf(data):
""" """
Get configuration setting of wireguard interface. Get configuration setting of wireguard interface.
@param config_name: Name of WG interface @param config_name: Name of WG interface
@type config_name: str @type config_name: str
@return: TODO @return: TODO
""" """
if getattr(g, 'db', None) is None:
g.db = connect_db()
g.cur = g.db.cursor()
print(data)
config_name = data['config']
print(config_name)
config_interface = read_conf_file_interface(config_name) config_interface = read_conf_file_interface(config_name)
search = request.args.get('search') search = data['search']
print(search)
# search = request.args.get('search')
if len(search) == 0: if len(search) == 0:
search = "" search = ""
search = urllib.parse.unquote(search) search = urllib.parse.unquote(search)
@ -1042,7 +1053,8 @@ def get_conf(config_name):
else: else:
conf_data['checked'] = "checked" conf_data['checked'] = "checked"
config.clear() config.clear()
return jsonify(conf_data) socketio.emit("get_config", conf_data, json=True)
# return jsonify(conf_data)
# Turn on / off a configuration # Turn on / off a configuration
@ -1714,4 +1726,5 @@ if __name__ == "__main__":
app_port = config.get("Server", "app_port") app_port = config.get("Server", "app_port")
WG_CONF_PATH = config.get("Server", "wg_conf_path") WG_CONF_PATH = config.get("Server", "wg_conf_path")
config.clear() config.clear()
app.run(host=app_ip, debug=False, port=app_port) socketio.run(app, host=app_ip, debug=False, port=app_port)
# app.run(host=app_ip, debug=False, port=app_port)

View File

@ -338,29 +338,56 @@
* Load Peers from server to configuration page * Load Peers from server to configuration page
* @param searchString * @param searchString
*/ */
let time = 0;
let count = 0;
let d1 = new Date();
function loadPeers(searchString){ function loadPeers(searchString){
d1 = new Date();
startProgressBar(); startProgressBar();
let d1 = new Date(); socket.emit('get_config', {"config": conf_name, "search": searchString});
$.ajax({
method: "GET", // let d1 = new Date();
url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`, // $.ajax({
headers:{"Content-Type": "application/json"} // method: "GET",
}).done(function(response){ // url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`,
removeNoResponding(); // headers:{"Content-Type": "application/json"}
peers = response.peer_data; // }).done(function(response){
configurationAlert(response); // removeNoResponding();
configurationHeader(response); // peers = response.peer_data;
configurationPeers(response); // configurationAlert(response);
$(".dot.dot-running").attr("title","Peer Connected").tooltip(); // configurationHeader(response);
$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); // configurationPeers(response);
$("i[data-toggle='tooltip']").tooltip(); // $(".dot.dot-running").attr("title","Peer Connected").tooltip();
endProgressBar(); // $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();
let d2 = new Date(); // $("i[data-toggle='tooltip']").tooltip();
let seconds = (d2 - d1); // endProgressBar();
$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); // let d2 = new Date();
}).fail(function(){ // let seconds = (d2 - d1);
noResponding(); // $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);
}); // }).fail(function(){
// noResponding();
// });
}
function parsePeers(response){
let d2 = new Date();
let seconds = (d2 - d1);
time += seconds
count += 1
window.console.log(`Average time: ${time/count}ms`);
$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`);
removeNoResponding();
peers = response.peer_data;
configurationAlert(response);
configurationHeader(response);
configurationPeers(response);
$(".dot.dot-running").attr("title","Peer Connected").tooltip();
$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();
$("i[data-toggle='tooltip']").tooltip();
endProgressBar();
} }
/** /**
@ -502,7 +529,7 @@
loadPeers: (searchString) => { loadPeers(searchString); }, loadPeers: (searchString) => { loadPeers(searchString); },
addPeersByBulk: () => { addPeersByBulk(); }, addPeersByBulk: () => { addPeersByBulk(); },
deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); }, deletePeers: (config, peers_ids) => { deletePeers(config, peers_ids); },
parsePeers: (response) => { parsePeers(response); },
getAvailableIps: () => { getAvailableIps(); }, getAvailableIps: () => { getAvailableIps(); },
generateKeyPair: () => { generate_key(); }, generateKeyPair: () => { generate_key(); },

File diff suppressed because one or more lines are too long

View File

@ -410,7 +410,7 @@
{% include "tools.html" %} {% include "tools.html" %}
</body> </body>
{% include "footer.html" %} {% include "footer.html" %}
<script src="{{ url_for('static',filename='js/wireguard.min.js') }}"></script> <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script><script src="{{ url_for('static',filename='js/wireguard.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/configuration.min.js') }}"></script> <script src="{{ url_for('static',filename='js/configuration.min.js') }}"></script>
<script> <script>
/* global peers */ /* global peers */
@ -419,8 +419,16 @@
let conf_name = "{{ conf_data['name'] }}" let conf_name = "{{ conf_data['name'] }}"
let peers = []; let peers = [];
$(".sb-"+conf_name+"-url").addClass("active"); $(".sb-"+conf_name+"-url").addClass("active");
let socket = io();
$(function(){ $(function(){
configurations.loadPeers($('#search_peer_textbox').val()); socket.on('connect', function() {
configurations.loadPeers($('#search_peer_textbox').val());
});
socket.on('get_config', function(res){
window.console.log(res);
configurations.parsePeers(res);
});
}); });
</script> </script>
</html> </html>