SyncTk/classes/window_config.py
2023-01-22 00:22:08 +01:00

110 lines
5.4 KiB
Python

import time
import requests
from os import path
from tkinter import ttk, messagebox, IntVar, Toplevel, N, S, W, E, END
from modules.dark_titlebar import dark_title_bar
from modules.utils import configGet, configSet, use_dark_mode
from modules.logger import logger
class WindowConfig(Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.window_width = 430
self.window_height = 247
self.screen_width = self.winfo_screenwidth()
self.screen_height = self.winfo_screenheight()
self.center_x = int(self.screen_width/2 - self.window_width / 2)
self.center_y = int(self.screen_height/2 - self.window_height / 2)
self.title("Configuration")
self.geometry(f'{self.window_width}x{self.window_height}+{self.center_x}+{self.center_y}')
self.resizable(False, False)
self.iconbitmap(path.join("assets", "favicon.ico"))
self.focus_set()
if use_dark_mode() is True:
dark_title_bar(self, "dark")
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=3)
# Address
self.address_label = ttk.Label(self, text="Address:")
self.address_label.grid(column=0, row=0, sticky=W, padx=9, pady=9)
self.address_entry = ttk.Entry(self)
self.address_entry.grid(column=1, row=0, sticky=N+S+E+W, padx=9, pady=9)
if configGet("address") is not None:
self.address_entry.insert(0, configGet("address"))
# =======
# API Key
self.apikey_label = ttk.Label(self, text="API key:")
self.apikey_label.grid(column=0, row=1, sticky=W, padx=9, pady=9)
self.apikey_entry = ttk.Entry(self)
self.apikey_entry.grid(column=1, row=1, sticky=N+S+E+W, padx=9, pady=9)
if configGet("apikey") is not None:
self.apikey_entry.insert(0, configGet("apikey"))
# =======
# Self-signed
if configGet("allow_self_signed") is not None:
self.self_signed_check_bool = IntVar(value=int(configGet("allow_self_signed")))
else:
self.self_signed_check_bool = IntVar()
self.self_signed_check = ttk.Checkbutton(self, text="Allow self-signed certificates", variable=self.self_signed_check_bool)
self.self_signed_check.grid(column=1, row=2, sticky=W, padx=9, pady=9)
# ===========
# Saves location
self.saves_location_label = ttk.Label(self, text="Saves location:")
self.saves_location_label.grid(column=0, row=3, sticky=W, padx=9, pady=9)
self.saves_location_button = ttk.Button(self, text="Browse", width=6)
self.saves_location_button.grid(column=1, row=3, sticky=W, padx=9, pady=9)
# ==============
self.login_button = ttk.Button(self, text="Log in", style="Accent.TButton", width=10, command=self.validate_configuration)
self.login_button.grid(column=1, row=4, sticky=E, padx=9, pady=9)
def validate_configuration(self):
if len(self.address_entry.get()) > 0:
if self.address_entry.get().endswith("/"):
self.address_text = self.address_entry.get()
self.address_entry.delete(0, END)
self.address_entry.insert(0, self.address_text[:-1])
try:
requests.get(self.address_entry.get()+"/check", verify=not bool(self.self_signed_check_bool.get()))
except (requests.exceptions.InvalidURL, requests.exceptions.InvalidSchema, requests.exceptions.MissingSchema) as exp:
logger.error(f"Could not validate '{self.address_entry.get()}' due to {exp}")
messagebox.showerror(title="Invalid address", message="Address entered does not seem to be correct one. Please provide API address starting with http:// or https:// \n\nFor example:\n- https://your-api.com:8043\n- https://your-api.com")
return
except (requests.exceptions.SSLError):
logger.error(f"SSL certificate of '{self.address_entry.get()}' does not seem to be valid or is self-signed")
messagebox.showerror(title="Invalid SSL", message="SSL certificate seems to be invalid or self-signed and thus won't be trusted. You can overwrite this by checking 'Allow self-signed certificates'.")
return
except Exception as exp:
logger.error(f"Could not reach '{self.address_entry.get()}' due to {exp}")
messagebox.showerror(title="Connection error", message="Address entered does not seem to be reachable. Please make sure you've entered the correct API address.")
return
response_apikey = requests.get(self.address_entry.get()+"/apikey", headers={"apikey": self.apikey_entry.get()}, verify=not bool(self.self_signed_check_bool.get()))
if response_apikey.status_code != 200:
logger.error(f"API key seems to be invalid. API returned {response_apikey.status_code} as a status code")
messagebox.showerror(title="Invalid apikey", message="API key provided does not seem to be valid. Please check for any mistakes and if none found - take a look at the docs to learn how to generate one.")
return
configSet(["address"], self.address_entry.get())
configSet(["apikey"], self.apikey_entry.get())
configSet(["allow_self_signed"], bool(self.self_signed_check_bool.get()))
messagebox.showinfo(title="Configuration completed", message="Your client is now configured and ready to use!")
self.destroy()