Compare commits

..

12 Commits

Author SHA1 Message Date
Donald Zou 3c50e4768a Merge pull request #317 from donaldzou/v4.0-fix3
Fixed recursive use of cursor
2024-08-20 00:02:46 -07:00
Donald Zou 63dc9834be Fixed recursive use of cursor 2024-08-20 00:02:00 -07:00
Donald Zou f042e42633 Adjust version to v4.0.2 2024-08-19 21:30:47 -04:00
Donald Zou 39b80a2e7e Fixed the issue where updating is not working 2024-08-19 19:17:07 -04:00
Donald Zou fb6e948358 Update production UI 2024-08-19 16:55:18 -04:00
Donald Zou 181b0845bf Merge pull request #313 from donaldzou/v4.0-fix2
Fixed #312, #311
2024-08-19 16:50:48 -04:00
Donald Zou b2a82dcfe5 Fixed #312, #311
- Fixed issue in #312: The dashboard will automatically get the actual Dashboard version number.
- Fixed issue in #311: WGDashboard was not treating restricted peers correctly.
2024-08-19 16:50:00 -04:00
Donald Zou cd73aef0c9 Merge pull request #307 from donaldzou/donaldzou-patch-3
Update README.md
2024-08-17 20:34:29 -04:00
Donald Zou ed522ec024 Update README.md 2024-08-17 20:34:20 -04:00
Donald Zou 16998d1e16 Merge pull request #306 from donaldzou/v4.0-fix1
Fixed peer status is not refreshing correctly
2024-08-17 20:25:34 -04:00
Donald Zou 11421d2d32 Try now 2024-08-17 20:19:52 -04:00
Donald Zou 1af708aaea Update 2024-08-17 01:11:48 -04:00
11 changed files with 334 additions and 256 deletions
+1 -1
View File
@@ -502,7 +502,7 @@ Endpoint = 0.0.0.0:51820
2. Update the dashboard 2. Update the dashboard
```shell ```shell
git pull https://github.com/donaldzou/WGDashboard.git v4.0 --force git pull https://github.com/donaldzou/WGDashboard.git --force
``` ```
3. Install 3. Install
+247 -190
View File
@@ -33,7 +33,7 @@ import threading
from flask.json.provider import DefaultJSONProvider from flask.json.provider import DefaultJSONProvider
DASHBOARD_VERSION = 'v4.0' DASHBOARD_VERSION = 'v4.0.2'
CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.') CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.')
DB_PATH = os.path.join(CONFIGURATION_PATH, 'db') DB_PATH = os.path.join(CONFIGURATION_PATH, 'db')
if not os.path.isdir(DB_PATH): if not os.path.isdir(DB_PATH):
@@ -119,26 +119,30 @@ class DashboardLogger:
self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'), self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'),
check_same_thread=False) check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row self.loggerdb.row_factory = sqlite3.Row
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase() self.__createLogDatabase()
self.log(Message="WGDashboard started") self.log(Message="WGDashboard started")
def __createLogDatabase(self): def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.loggerdb:
existingTable = [t['name'] for t in existingTable] loggerdbCursor = self.loggerdb.cursor()
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
if "DashboardLog" not in existingTable: existingTable = [t['name'] for t in existingTable]
self.loggerdbCursor.execute( if "DashboardLog" not in existingTable:
"CREATE TABLE DashboardLog (LogID VARCHAR NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), URL VARCHAR, IP VARCHAR, Status VARCHAR, Message VARCHAR, PRIMARY KEY (LogID))") loggerdbCursor.execute(
self.loggerdb.commit() "CREATE TABLE DashboardLog (LogID VARCHAR NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), URL VARCHAR, IP VARCHAR, Status VARCHAR, Message VARCHAR, PRIMARY KEY (LogID))")
if self.loggerdb.in_transaction:
self.loggerdb.commit()
def log(self, URL: str = "", IP: str = "", Status: str = "true", Message: str = "") -> bool: def log(self, URL: str = "", IP: str = "", Status: str = "true", Message: str = "") -> bool:
try: try:
self.loggerdbCursor.execute( with self.loggerdb:
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,)) loggerdbCursor = self.loggerdb.cursor()
self.loggerdb.commit() loggerdbCursor.execute(
return True "INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
if self.loggerdb.in_transaction:
self.loggerdb.commit()
return True
except Exception as e: except Exception as e:
print(e) print(f"[WGDashboard] Access Log Error: {str(e)}")
return False return False
class PeerJobLogger: class PeerJobLogger:
@@ -147,23 +151,29 @@ class PeerJobLogger:
check_same_thread=False) check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row self.loggerdb.row_factory = sqlite3.Row
self.logs:list(Log) = [] self.logs:list(Log) = []
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase() self.__createLogDatabase()
def __createLogDatabase(self): def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.loggerdb:
existingTable = [t['name'] for t in existingTable] loggerdbCursor = self.loggerdb.cursor()
if "JobLog" not in existingTable: existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
self.loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))") existingTable = [t['name'] for t in existingTable]
self.loggerdb.commit()
if "JobLog" not in existingTable:
loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))")
if self.loggerdb.in_transaction:
self.loggerdb.commit()
def log(self, JobID: str, Status: bool = True, Message: str = "") -> bool: def log(self, JobID: str, Status: bool = True, Message: str = "") -> bool:
try: try:
self.loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)", with self.loggerdb:
(str(uuid.uuid4()), JobID, Status, Message,)) loggerdbCursor = self.loggerdb.cursor()
self.loggerdb.commit() loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
(str(uuid.uuid4()), JobID, Status, Message,))
if self.loggerdb.in_transaction:
self.loggerdb.commit()
except Exception as e: except Exception as e:
print(e) print(f"[WGDashboard] Peer Job Log Error: {str(e)}")
return False return False
return True return True
@@ -172,11 +182,13 @@ class PeerJobLogger:
try: try:
allJobs = AllPeerJobs.getAllJobs(configName) allJobs = AllPeerJobs.getAllJobs(configName)
allJobsID = ", ".join([f"'{x.JobID}'" for x in allJobs]) allJobsID = ", ".join([f"'{x.JobID}'" for x in allJobs])
table = self.loggerdb.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall() with self.loggerdb:
self.logs.clear() loggerdbCursor = self.loggerdb.cursor()
for l in table: table = loggerdbCursor.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
logs.append( self.logs.clear()
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"])) for l in table:
logs.append(
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"]))
except Exception as e: except Exception as e:
return logs return logs
return logs return logs
@@ -217,41 +229,47 @@ class PeerJobs:
self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'), self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'),
check_same_thread=False) check_same_thread=False)
self.jobdb.row_factory = sqlite3.Row self.jobdb.row_factory = sqlite3.Row
self.jobdbCursor = self.jobdb.cursor()
self.__createPeerJobsDatabase() self.__createPeerJobsDatabase()
self.__getJobs() self.__getJobs()
def __getJobs(self): def __getJobs(self):
self.Jobs.clear() self.Jobs.clear()
jobs = self.jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall() with self.jobdb:
for job in jobs: jobdbCursor = self.jobdb.cursor()
self.Jobs.append(PeerJob( jobs = jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'], for job in jobs:
job['CreationDate'], job['ExpireDate'], job['Action'])) self.Jobs.append(PeerJob(
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
def getAllJobs(self, configuration: str = None): def getAllJobs(self, configuration: str = None):
if configuration is not None: if configuration is not None:
jobs = self.jobdbCursor.execute( with self.jobdb:
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall() jobdbCursor = self.jobdb.cursor()
j = [] jobs = jobdbCursor.execute(
for job in jobs: f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
j.append(PeerJob( j = []
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'], for job in jobs:
job['CreationDate'], job['ExpireDate'], job['Action'])) j.append(PeerJob(
return j job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
return j
return [] return []
def __createPeerJobsDatabase(self): def __createPeerJobsDatabase(self):
existingTable = self.jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.jobdb:
existingTable = [t['name'] for t in existingTable] jobdbCursor = self.jobdb.cursor()
if "PeerJobs" not in existingTable: existingTable = jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
self.jobdbCursor.execute(''' existingTable = [t['name'] for t in existingTable]
CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME, if "PeerJobs" not in existingTable:
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID)) jobdbCursor.execute('''
''') CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
self.jobdb.commit() Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME,
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
''')
self.jobdb.commit()
def toJson(self): def toJson(self):
return [x.toJson() for x in self.Jobs] return [x.toJson() for x in self.Jobs]
@@ -261,22 +279,25 @@ class PeerJobs:
def saveJob(self, Job: PeerJob) -> tuple[bool, list] | tuple[bool, str]: def saveJob(self, Job: PeerJob) -> tuple[bool, list] | tuple[bool, str]:
try: try:
if (len(str(Job.CreationDate))) == 0: with self.jobdb:
self.jobdbCursor.execute(''' jobdbCursor = self.jobdb.cursor()
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
else: if (len(str(Job.CreationDate))) == 0:
currentJob = self.jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone() jobdbCursor.execute('''
if currentJob is not None: INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
self.jobdbCursor.execute(''' ''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ? JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
JobLogger.log(Job.JobID, else:
Message=f"Job is updated from if {currentJob['Field']} {currentJob['Operator']} {currentJob['value']} then {currentJob['Action']}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}") currentJob = jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
self.jobdb.commit() if currentJob is not None:
self.__getJobs() jobdbCursor.execute('''
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
JobLogger.log(Job.JobID,
Message=f"Job is updated from if {currentJob['Field']} {currentJob['Operator']} {currentJob['value']} then {currentJob['Action']}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
self.jobdb.commit()
self.__getJobs()
return True, list( return True, list(
filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID, filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID,
@@ -288,10 +309,12 @@ class PeerJobs:
try: try:
if (len(str(Job.CreationDate))) == 0: if (len(str(Job.CreationDate))) == 0:
return False, "Job does not exist" return False, "Job does not exist"
self.jobdbCursor.execute(''' with self.jobdb:
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ? jobdbCursor = self.jobdb.cursor()
''', (Job.JobID,)) jobdbCursor.execute('''
self.jobdb.commit() UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
''', (Job.JobID,))
self.jobdb.commit()
JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.") JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.")
self.__getJobs() self.__getJobs()
return True, list( return True, list(
@@ -364,10 +387,9 @@ class PeerShareLink:
class PeerShareLinks: class PeerShareLinks:
def __init__(self): def __init__(self):
self.Links: list[PeerShareLink] = [] self.Links: list[PeerShareLink] = []
self.PeerShareLinkCursor = sqldb.cursor() existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
existingTables = self.PeerShareLinkCursor.execute("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
if len(existingTables) == 0: if len(existingTables) == 0:
self.PeerShareLinkCursor.execute( sqlUpdate(
""" """
CREATE TABLE PeerShareLinks ( CREATE TABLE PeerShareLinks (
ShareID VARCHAR NOT NULL PRIMARY KEY, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL, ShareID VARCHAR NOT NULL PRIMARY KEY, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
@@ -376,12 +398,12 @@ class PeerShareLinks:
) )
""" """
) )
sqldb.commit() # sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
# print(self.Links) # print(self.Links)
def __getSharedLinks(self): def __getSharedLinks(self):
self.Links.clear() self.Links.clear()
allLinks = self.PeerShareLinkCursor.execute("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall() allLinks = sqlSelect("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall()
for link in allLinks: for link in allLinks:
self.Links.append(PeerShareLink(*link)) self.Links.append(PeerShareLink(*link))
@@ -397,18 +419,17 @@ class PeerShareLinks:
try: try:
newShareID = str(uuid.uuid4()) newShareID = str(uuid.uuid4())
if len(self.getLink(Configuration, Peer)) > 0: if len(self.getLink(Configuration, Peer)) > 0:
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, )) sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
self.PeerShareLinkCursor.execute("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, )) sqlUpdate("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
sqldb.commit() # sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
except Exception as e: except Exception as e:
return False, str(e) return False, str(e)
return True, newShareID return True, newShareID
def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]: def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]:
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, )) # sqldb.commit()
sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
return True, "" return True, ""
@@ -490,12 +511,13 @@ class WireguardConfiguration:
# Create tables in database # Create tables in database
self.__createDatabase() self.__createDatabase()
self.getPeersList() self.getPeersList()
self.getRestrictedPeersList()
def __createDatabase(self): def __createDatabase(self):
existingTables = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
existingTables = [t['name'] for t in existingTables] existingTables = [t['name'] for t in existingTables]
if self.Name not in existingTables: if self.Name not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s'( CREATE TABLE '%s'(
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -508,10 +530,10 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_restrict_access' not in existingTables: if f'{self.Name}_restrict_access' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_restrict_access' ( CREATE TABLE '%s_restrict_access' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -524,9 +546,9 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_transfer' not in existingTables: if f'{self.Name}_transfer' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_transfer' ( CREATE TABLE '%s_transfer' (
id VARCHAR NOT NULL, total_receive FLOAT NULL, id VARCHAR NOT NULL, total_receive FLOAT NULL,
@@ -535,9 +557,9 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_deleted' not in existingTables: if f'{self.Name}_deleted' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_deleted' ( CREATE TABLE '%s_deleted' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -550,7 +572,7 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
@@ -563,85 +585,85 @@ class WireguardConfiguration:
def __getRestrictedPeers(self): def __getRestrictedPeers(self):
self.RestrictedPeers = [] self.RestrictedPeers = []
restricted = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall() restricted = sqlSelect("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
for i in restricted: for i in restricted:
self.RestrictedPeers.append(Peer(i, self)) self.RestrictedPeers.append(Peer(i, self))
def __getPeers(self): def __getPeers(self):
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf')) mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt: # if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
self.Peers = [] self.Peers = []
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile: with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
p = [] p = []
pCounter = -1 pCounter = -1
content = configFile.read().split('\n') content = configFile.read().split('\n')
try: try:
peerStarts = content.index("[Peer]") peerStarts = content.index("[Peer]")
content = content[peerStarts:] content = content[peerStarts:]
for i in content: for i in content:
if not regex_match("#(.*)", i) and not regex_match(";(.*)", i): if not regex_match("#(.*)", i) and not regex_match(";(.*)", i):
if i == "[Peer]": if i == "[Peer]":
pCounter += 1 pCounter += 1
p.append({}) p.append({})
p[pCounter]["name"] = "" p[pCounter]["name"] = ""
else: else:
if len(i) > 0: if len(i) > 0:
split = re.split(r'\s*=\s*', i, 1) split = re.split(r'\s*=\s*', i, 1)
if len(split) == 2: if len(split) == 2:
p[pCounter][split[0]] = split[1] p[pCounter][split[0]] = split[1]
if regex_match("#Name# = (.*)", i): if regex_match("#Name# = (.*)", i):
split = re.split(r'\s*=\s*', i, 1) split = re.split(r'\s*=\s*', i, 1)
print(split) print(split)
if len(split) == 2: if len(split) == 2:
p[pCounter]["name"] = split[1] p[pCounter]["name"] = split[1]
for i in p: for i in p:
if "PublicKey" in i.keys(): if "PublicKey" in i.keys():
checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name, checkIfExist = sqlSelect("SELECT * FROM '%s' WHERE id = ?" % self.Name,
((i['PublicKey']),)).fetchone() ((i['PublicKey']),)).fetchone()
if checkIfExist is None: if checkIfExist is None:
newPeer = { newPeer = {
"id": i['PublicKey'], "id": i['PublicKey'],
"private_key": "", "private_key": "",
"DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1], "DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1],
"endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[ "endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[
1], 1],
"name": i.get("name"), "name": i.get("name"),
"total_receive": 0, "total_receive": 0,
"total_sent": 0, "total_sent": 0,
"total_data": 0, "total_data": 0,
"endpoint": "N/A", "endpoint": "N/A",
"status": "stopped", "status": "stopped",
"latest_handshake": "N/A", "latest_handshake": "N/A",
"allowed_ip": i.get("AllowedIPs", "N/A"), "allowed_ip": i.get("AllowedIPs", "N/A"),
"cumu_receive": 0, "cumu_receive": 0,
"cumu_sent": 0, "cumu_sent": 0,
"cumu_data": 0, "cumu_data": 0,
"traffic": [], "traffic": [],
"mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1], "mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1],
"keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1], "keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1],
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1], "remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else "" "preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
} }
sqldb.cursor().execute( sqlUpdate(
""" """
INSERT INTO '%s' INSERT INTO '%s'
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent, VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
:total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent, :total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key); :cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
""" % self.Name """ % self.Name
, newPeer) , newPeer)
sqldb.commit() # sqldb.commit()
self.Peers.append(Peer(newPeer, self)) self.Peers.append(Peer(newPeer, self))
else: else:
sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name, sqlUpdate("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
(i.get("AllowedIPs", "N/A"), i['PublicKey'],)) (i.get("AllowedIPs", "N/A"), i['PublicKey'],))
sqldb.commit() # sqldb.commit()
self.Peers.append(Peer(checkIfExist, self)) self.Peers.append(Peer(checkIfExist, self))
except Exception as e: except Exception as e:
print(f"[WGDashboard] {self.Name} Error: {str(e)}") print(f"[WGDashboard] {self.Name} Error: {str(e)}")
self.__configFileModifiedTime = mt self.__configFileModifiedTime = mt
def addPeers(self, peers: list): def addPeers(self, peers: list):
@@ -665,11 +687,11 @@ class WireguardConfiguration:
self.toggleConfiguration() self.toggleConfiguration()
for i in listOfPublicKeys: for i in listOfPublicKeys:
p = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone() p = sqlSelect("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone()
if p is not None: if p is not None:
sqldb.cursor().execute("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?" sqlUpdate("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?"
% (self.Name, self.Name,), (p['id'],)) % (self.Name, self.Name,), (p['id'],))
sqldb.cursor().execute("DELETE FROM '%s_restrict_access' WHERE id = ?" sqlUpdate("DELETE FROM '%s_restrict_access' WHERE id = ?"
% self.Name, (p['id'],)) % self.Name, (p['id'],))
subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}", subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}",
shell=True, stderr=subprocess.STDOUT) shell=True, stderr=subprocess.STDOUT)
@@ -692,11 +714,12 @@ class WireguardConfiguration:
try: try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove", subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT) shell=True, stderr=subprocess.STDOUT)
sqldb.cursor().execute("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" % sqlUpdate("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" %
(self.Name, self.Name,), (pf.id,)) (self.Name, self.Name,), (pf.id,))
sqldb.cursor().execute("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" % sqlUpdate("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" %
(self.Name,), (pf.id,)) (self.Name,), (pf.id,))
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,)) sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
# sqldb.commit()
numOfRestrictedPeers += 1 numOfRestrictedPeers += 1
except Exception as e: except Exception as e:
numOfFailedToRestrictPeers += 1 numOfFailedToRestrictPeers += 1
@@ -723,7 +746,7 @@ class WireguardConfiguration:
try: try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove", subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT) shell=True, stderr=subprocess.STDOUT)
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,)) sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
numOfDeletedPeers += 1 numOfDeletedPeers += 1
except Exception as e: except Exception as e:
numOfFailedToDeletePeers += 1 numOfFailedToDeletePeers += 1
@@ -799,7 +822,7 @@ class WireguardConfiguration:
data_usage = [p.split("\t") for p in data_usage] data_usage = [p.split("\t") for p in data_usage]
for i in range(len(data_usage)): for i in range(len(data_usage)):
if len(data_usage[i]) == 3: if len(data_usage[i]) == 3:
cur_i = sqldb.cursor().execute( cur_i = sqlSelect(
"SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? " "SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? "
% self.Name, (data_usage[i][0],)).fetchone() % self.Name, (data_usage[i][0],)).fetchone()
if cur_i is not None: if cur_i is not None:
@@ -814,7 +837,7 @@ class WireguardConfiguration:
total_sent = cur_total_sent total_sent = cur_total_sent
total_receive = cur_total_receive total_receive = cur_total_receive
else: else:
sqldb.cursor().execute( sqlUpdate(
"UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" % "UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" %
self.Name, (cumulative_receive, cumulative_sent, self.Name, (cumulative_receive, cumulative_sent,
cumulative_sent + cumulative_receive, cumulative_sent + cumulative_receive,
@@ -824,7 +847,7 @@ class WireguardConfiguration:
total_receive = 0 total_receive = 0
_, p = self.searchPeer(data_usage[i][0]) _, p = self.searchPeer(data_usage[i][0])
if p.total_receive != total_receive or p.total_sent != total_sent: if p.total_receive != total_receive or p.total_sent != total_sent:
sqldb.cursor().execute( sqlUpdate(
"UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?" "UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?"
% self.Name, (total_receive, total_sent, % self.Name, (total_receive, total_sent,
total_receive + total_sent, data_usage[i][0],)) total_receive + total_sent, data_usage[i][0],))
@@ -845,7 +868,7 @@ class WireguardConfiguration:
for _ in range(int(len(data_usage) / 2)): for _ in range(int(len(data_usage) / 2)):
sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name
, (data_usage[count + 1], data_usage[count],)) , (data_usage[count + 1], data_usage[count],))
sqldb.commit() # sqldb.commit()
count += 2 count += 2
def toggleConfiguration(self) -> [bool, str]: def toggleConfiguration(self) -> [bool, str]:
@@ -980,7 +1003,7 @@ class Peer:
if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'): if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'):
return ResponseObject(False, return ResponseObject(False,
"Update peer failed when saving the configuration.") "Update peer failed when saving the configuration.")
sqldb.cursor().execute( sqlUpdate(
'''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?, '''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?,
keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name, keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name,
(name, private_key, dns_addresses, endpoint_allowed_ip, mtu, (name, private_key, dns_addresses, endpoint_allowed_ip, mtu,
@@ -1033,11 +1056,11 @@ PersistentKeepalive = {str(self.keepalive)}
def resetDataUsage(self, type): def resetDataUsage(self, type):
try: try:
if type == "total": if type == "total":
sqldb.cursor().execute("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, )) sqlUpdate("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
elif type == "receive": elif type == "receive":
sqldb.cursor().execute("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, )) sqlUpdate("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
elif type == "sent": elif type == "sent":
sqldb.cursor().execute("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, )) sqlUpdate("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
else: else:
return False return False
except Exception as e: except Exception as e:
@@ -1115,15 +1138,17 @@ class DashboardConfig:
self.__createAPIKeyTable() self.__createAPIKeyTable()
self.DashboardAPIKeys = self.__getAPIKeys() self.DashboardAPIKeys = self.__getAPIKeys()
self.APIAccessed = False self.APIAccessed = False
self.SetConfig("Server", "version", DASHBOARD_VERSION)
def __createAPIKeyTable(self): def __createAPIKeyTable(self):
existingTable = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall() existingTable = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall()
if len(existingTable) == 0: if len(existingTable) == 0:
sqldb.cursor().execute("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)") sqlUpdate("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
sqldb.commit() # sqldb.commit()
def __getAPIKeys(self) -> list[DashboardAPIKey]: def __getAPIKeys(self) -> list[DashboardAPIKey]:
keys = sqldb.cursor().execute("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall() keys = sqlSelect("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall()
fKeys = [] fKeys = []
for k in keys: for k in keys:
fKeys.append(DashboardAPIKey(*k)) fKeys.append(DashboardAPIKey(*k))
@@ -1131,13 +1156,13 @@ class DashboardConfig:
def createAPIKeys(self, ExpiredAt = None): def createAPIKeys(self, ExpiredAt = None):
newKey = secrets.token_urlsafe(32) newKey = secrets.token_urlsafe(32)
sqldb.cursor().execute('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,)) sqlUpdate('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
sqldb.commit() # sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys() self.DashboardAPIKeys = self.__getAPIKeys()
def deleteAPIKey(self, key): def deleteAPIKey(self, key):
sqldb.cursor().execute("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, )) sqlUpdate("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
sqldb.commit() # sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys() self.DashboardAPIKeys = self.__getAPIKeys()
@@ -1344,6 +1369,14 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
for i in add: for i in add:
a, c = i.split('/') a, c = i.split('/')
existedAddress.append(ipaddress.ip_address(a.replace(" ", ""))) existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
for p in configuration.getRestrictedPeersList():
if len(p.allowed_ip) > 0:
add = p.allowed_ip.split(',')
for i in add:
a, c = i.split('/')
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
for i in address: for i in address:
addressSplit, cidr = i.split('/') addressSplit, cidr = i.split('/')
existedAddress.append(ipaddress.ip_address(addressSplit.replace(" ", ""))) existedAddress.append(ipaddress.ip_address(addressSplit.replace(" ", "")))
@@ -1365,6 +1398,17 @@ sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db')
sqldb.row_factory = sqlite3.Row sqldb.row_factory = sqlite3.Row
cursor = sqldb.cursor() cursor = sqldb.cursor()
def sqlSelect(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
with sqldb:
cursor = sqldb.cursor()
return cursor.execute(statement, paramters)
def sqlUpdate(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
with sqldb:
cursor = sqldb.cursor()
cursor.execute(statement, paramters)
sqldb.commit()
DashboardConfig = DashboardConfig() DashboardConfig = DashboardConfig()
_, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix") _, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix")
cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": { cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": {
@@ -1419,6 +1463,7 @@ def auth_req():
and f"{(APP_PREFIX if len(APP_PREFIX) > 0 else '')}" != request.path) and f"{(APP_PREFIX if len(APP_PREFIX) > 0 else '')}" != request.path)
and "validateAuthentication" not in request.path and "authenticate" not in request.path and "validateAuthentication" not in request.path and "authenticate" not in request.path
and "getDashboardConfiguration" not in request.path and "getDashboardTheme" not in request.path and "getDashboardConfiguration" not in request.path and "getDashboardTheme" not in request.path
and "getDashboardVersion" not in request.path
and "sharePeer/get" not in request.path and "sharePeer/get" not in request.path
and "isTotpEnabled" not in request.path and "isTotpEnabled" not in request.path
): ):
@@ -1751,10 +1796,13 @@ def API_addPeers(configName):
return ResponseObject(False, "Please fill in all required box.") return ResponseObject(False, "Please fill in all required box.")
if not config.getStatus(): if not config.getStatus():
config.toggleConfiguration() config.toggleConfiguration()
availableIps = _getWireguardConfigurationAvailableIP(configName)
if bulkAdd: if bulkAdd:
if bulkAddAmount < 1: if bulkAddAmount < 1:
return ResponseObject(False, "Please specify amount of peers you want to add") return ResponseObject(False, "Please specify amount of peers you want to add")
availableIps = _getWireguardConfigurationAvailableIP(configName)
if not availableIps[0]: if not availableIps[0]:
return ResponseObject(False, "No more available IP can assign") return ResponseObject(False, "No more available IP can assign")
if bulkAddAmount > len(availableIps[1]): if bulkAddAmount > len(availableIps[1]):
@@ -1788,6 +1836,11 @@ def API_addPeers(configName):
return ResponseObject(False, f"This peer already exist.") return ResponseObject(False, f"This peer already exist.")
name = data['name'] name = data['name']
private_key = data['private_key'] private_key = data['private_key']
for i in allowed_ips:
if i not in availableIps[1]:
return ResponseObject(False, f"This IP is not available: {i}")
config.addPeers([{"id": public_key, "allowed_ip": ''.join(allowed_ips)}]) config.addPeers([{"id": public_key, "allowed_ip": ''.join(allowed_ips)}])
# subprocess.check_output( # subprocess.check_output(
# f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}", # f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
@@ -1857,6 +1910,10 @@ def API_getConfigurationInfo():
def API_getDashboardTheme(): def API_getDashboardTheme():
return ResponseObject(data=DashboardConfig.GetConfig("Server", "dashboard_theme")[1]) return ResponseObject(data=DashboardConfig.GetConfig("Server", "dashboard_theme")[1])
@app.route(f'{APP_PREFIX}/api/getDashboardVersion')
def API_getDashboardVersion():
return ResponseObject(data=DashboardConfig.GetConfig("Server", "version")[1])
@app.route(f'{APP_PREFIX}/api/savePeerScheduleJob/', methods=["POST"]) @app.route(f'{APP_PREFIX}/api/savePeerScheduleJob/', methods=["POST"])
def API_savePeerScheduleJob(): def API_savePeerScheduleJob():
@@ -2006,8 +2063,7 @@ def API_traceroute_execute():
@app.route(f'{APP_PREFIX}/api/getDashboardUpdate') @app.route(f'{APP_PREFIX}/api/getDashboardUpdate')
def API_getDashboardUpdate(): def API_getDashboardUpdate():
import urllib.request as req; import urllib.request as req
try: try:
r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read() r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read()
data = dict(json.loads(r)) data = dict(json.loads(r))
@@ -2020,8 +2076,8 @@ def API_getDashboardUpdate():
return ResponseObject(message="You're on the latest version") return ResponseObject(message="You're on the latest version")
return ResponseObject(False) return ResponseObject(False)
except urllib.error.HTTPError as e: except urllib.error.HTTPError and urllib.error.URLError as e:
return ResponseObject(False, f"Request to GitHub API failed. Returned a {e.code} status.") return ResponseObject(False, f"Request to GitHub API failed.")
''' '''
Sign Up Sign Up
@@ -2102,6 +2158,7 @@ def backGroundThread():
c.getPeersLatestHandshake() c.getPeersLatestHandshake()
c.getPeersEndpoint() c.getPeersEndpoint()
c.getPeersList() c.getPeersList()
c.getRestrictedPeersList()
except Exception as e: except Exception as e:
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True) print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
time.sleep(10) time.sleep(10)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 MiB

File diff suppressed because one or more lines are too long
+16 -16
View File
File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 MiB

+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "app", "name": "app",
"version": "4.0.0", "version": "4.0.2",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder", "build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder --mac --win",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@@ -36,8 +36,11 @@ export default {
addAllowedIp(ip){ addAllowedIp(ip){
if(this.store.checkCIDR(ip)){ if(this.store.checkCIDR(ip)){
this.data.allowed_ips.push(ip); this.data.allowed_ips.push(ip);
this.customAvailableIp = ''
return true; return true;
} }
this.allowedIpFormatError = true;
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')
return false; return false;
} }
}, },
@@ -80,10 +83,7 @@ export default {
:disabled="bulk"> :disabled="bulk">
<button class="btn btn-outline-success btn-sm rounded-end-3" <button class="btn btn-outline-success btn-sm rounded-end-3"
:disabled="bulk || !this.customAvailableIp" :disabled="bulk || !this.customAvailableIp"
@click="this.addAllowedIp(this.customAvailableIp) @click="this.addAllowedIp(this.customAvailableIp)"
? this.customAvailableIp = '' :
this.allowedIpFormatError = true;
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')"
type="button" id="button-addon2"> type="button" id="button-addon2">
<i class="bi bi-plus-lg"></i> <i class="bi bi-plus-lg"></i>
</button> </button>
@@ -200,7 +200,8 @@ export default {
}) })
this.loading = false; this.loading = false;
if (this.configurationPeers.length > 0){ if (this.configurationPeers.length > 0){
const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent).reduce((x,y) => x + y).toFixed(4); const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent)
.reduce((x,y) => x + y).toFixed(4);
const receive = this.configurationPeers.map(x => x.total_receive + x.cumu_receive).reduce((x,y) => x + y).toFixed(4); const receive = this.configurationPeers.map(x => x.total_receive + x.cumu_receive).reduce((x,y) => x + y).toFixed(4);
if ( if (
this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent
@@ -259,13 +260,13 @@ export default {
connectedPeers: this.configurationPeers.filter(x => x.status === "running").length, connectedPeers: this.configurationPeers.filter(x => x.status === "running").length,
totalUsage: this.configurationPeers.length > 0 ? totalUsage: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted) this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b).toFixed(4) : 0, .map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b, 0).toFixed(4) : 0,
totalReceive: this.configurationPeers.length > 0 ? totalReceive: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted) this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b).toFixed(4) : 0, .map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b, 0).toFixed(4) : 0,
totalSent: this.configurationPeers.length > 0 ? totalSent: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted) this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b).toFixed(4) : 0 .map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b, 0).toFixed(4) : 0
} }
return k return k
+14 -8
View File
@@ -11,16 +11,22 @@ export default {
const store = DashboardConfigurationStore() const store = DashboardConfigurationStore()
let theme = "dark" let theme = "dark"
let totpEnabled = false; let totpEnabled = false;
let version = undefined;
if (!store.IsElectronApp){ if (!store.IsElectronApp){
await fetchGet("/api/getDashboardTheme", {}, (res) => { await Promise.all([
theme = res.data fetchGet("/api/getDashboardTheme", {}, (res) => {
}); theme = res.data
await fetchGet("/api/isTotpEnabled", {}, (res) => { }),
totpEnabled = res.data fetchGet("/api/isTotpEnabled", {}, (res) => {
}); totpEnabled = res.data
}),
fetchGet("/api/getDashboardVersion", {}, (res) => {
version = res.data
})
]);
} }
store.removeActiveCrossServer(); store.removeActiveCrossServer();
return {store, theme, totpEnabled} return {store, theme, totpEnabled, version}
}, },
data(){ data(){
return { return {
@@ -146,7 +152,7 @@ export default {
</div> </div>
</div> </div>
<small class="text-muted pb-3 d-block w-100 text-center mt-3"> <small class="text-muted pb-3 d-block w-100 text-center mt-3">
WGDashboard v4.0 | Developed with by WGDashboard {{ this.version }} | Developed with by
<a href="https://github.com/donaldzou" target="_blank"><strong>Donald Zou</strong></a> <a href="https://github.com/donaldzou" target="_blank"><strong>Donald Zou</strong></a>
</small> </small>
<div class="messageCentre text-body position-absolute end-0 m-3"> <div class="messageCentre text-body position-absolute end-0 m-3">
+38 -24
View File
@@ -2,7 +2,7 @@
# wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou] # wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou]
# Under Apache-2.0 License # Under Apache-2.0 License
trap "kill $TOP_PID" #trap "kill $TOP_PID"
export TOP_PID=$$ export TOP_PID=$$
app_name="dashboard.py" app_name="dashboard.py"
@@ -220,7 +220,7 @@ _checkPythonVersion(){
else else
printf "[WGDashboard] %s Could not find a compatible version of Python. Current Python is %s.\n" "$heavy_crossmark" "$version" printf "[WGDashboard] %s Could not find a compatible version of Python. Current Python is %s.\n" "$heavy_crossmark" "$version"
printf "[WGDashboard] WGDashboard required Python 3.10, 3.11 or 3.12. Halting install now.\n" printf "[WGDashboard] WGDashboard required Python 3.10, 3.11 or 3.12. Halting install now.\n"
kill $TOP_PID kill $TOP_PID
fi fi
} }
@@ -337,28 +337,42 @@ start_wgd_debug() {
} }
update_wgd() { update_wgd() {
new_ver=$(venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
printf "%s\n" "$dashes" _determineOS
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver" if ! python3 --version > /dev/null 2>&1
read up then
if [ "$up" = "Y" ] || [ "$up" = "y" ]; then printf "[WGDashboard] Python is not installed, trying to install now\n"
printf "[WGDashboard] Shutting down WGDashboard\n" _installPython
if check_wgd_status; then else
stop_wgd printf "[WGDashboard] %s Python is installed\n" "$heavy_checkmark"
fi fi
mv wgd.sh wgd.sh.old
printf "[WGDashboard] Downloading %s from GitHub..." "$new_ver" _checkPythonVersion
{ date; git stash; git pull https://github.com/donaldzou/WGDashboard.git $new_ver --force; } >> ./log/update.txt _installPythonVenv
chmod +x ./wgd.sh _installPythonPip
sudo ./wgd.sh install
printf "[WGDashboard] Update completed!\n" new_ver=$($venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
rm wgd.sh.old printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
else read up
printf "%s\n" "$dashes" if [ "$up" = "Y" ] || [ "$up" = "y" ]; then
printf "| Update Canceled. |\n" printf "[WGDashboard] Shutting down WGDashboard\n"
printf "%s\n" "$dashes" if check_wgd_status; then
fi stop_wgd
fi
mv wgd.sh wgd.sh.old
printf "[WGDashboard] Downloading %s from GitHub..." "$new_ver"
{ date; git stash; git pull https://github.com/donaldzou/WGDashboard.git $new_ver --force; } >> ./log/update.txt
chmod +x ./wgd.sh
sudo ./wgd.sh install
printf "[WGDashboard] Update completed!\n"
printf "%s\n" "$dashes"
rm wgd.sh.old
else
printf "%s\n" "$dashes"
printf "[WGDashboard] Update Canceled.\n"
printf "%s\n" "$dashes"
fi
} }
if [ "$#" != 1 ]; if [ "$#" != 1 ];