replace more "with open"

This commit is contained in:
Désiré Werner Menrath 2025-04-29 15:09:56 +02:00
parent 5fb4e68867
commit 5dcfc91621

134
wirepy.py
View File

@ -23,6 +23,8 @@ Create.decrypt()
tcl_path: Path = Path("/usr/share/TK-Themes") tcl_path: Path = Path("/usr/share/TK-Themes")
set_file: Path = Path(Path.home() / ".config/wire_py/settings") set_file: Path = Path(Path.home() / ".config/wire_py/settings")
keys: Path = Path(Path.home() / ".config/wire_py/keys")
tips = LxTools.if_tip(set_file) tips = LxTools.if_tip(set_file)
folder_path: Path = Path("/tmp/tlecdcwg/") folder_path: Path = Path("/tmp/tlecdcwg/")
user_file = Path("/tmp/.log_user") user_file = Path("/tmp/.log_user")
@ -140,7 +142,7 @@ class FrameWidgets(ttk.Frame):
# About BTN Menu / Label # About BTN Menu / Label
self.about_btn = ttk.Button( self.about_btn = ttk.Button(
self.menu_frame, text=_("About"), style="Toolbutton", command=self.info) self.menu_frame, text=_("About"), style="Toolbutton", command=self.about)
self.about_btn.grid(column=2, columnspan=2, row=0) self.about_btn.grid(column=2, columnspan=2, row=0)
self.readme = tk.Menu(self) self.readme = tk.Menu(self)
@ -332,7 +334,10 @@ class FrameWidgets(ttk.Frame):
self.on_off() self.on_off()
@staticmethod @staticmethod
def info(): def about() -> None:
"""
a tk.Toplevel window
"""
def link_btn() -> str | None: def link_btn() -> str | None:
webbrowser.open("https://git.ilunix.de/punix/Wire-Py") webbrowser.open("https://git.ilunix.de/punix/Wire-Py")
@ -343,7 +348,7 @@ class FrameWidgets(ttk.Frame):
LxTools.msg_window(img_i, img_i, _("Info"), msg_t, _("Go to Wire-Py git"), link_btn) LxTools.msg_window(img_i, img_i, _("Info"), msg_t, _("Go to Wire-Py git"), link_btn)
def theme_change_light(self): def theme_change_light(self) -> None:
""" """
Set a light theme Set a light theme
""" """
@ -354,7 +359,7 @@ class FrameWidgets(ttk.Frame):
Path(set_file).write_text(''.join(lines), encoding="utf-8") Path(set_file).write_text(''.join(lines), encoding="utf-8")
self.color_label() self.color_label()
def theme_change_dark(self): def theme_change_dark(self) -> None:
""" """
Set a dark theme Set a dark theme
""" """
@ -435,7 +440,7 @@ class FrameWidgets(ttk.Frame):
if is_encrypt.is_file(): if is_encrypt.is_file():
Path.unlink(f"{Path.home()}/.config/wire_py/{select_tl}.dat") Path.unlink(f"{Path.home()}/.config/wire_py/{select_tl}.dat")
Path.unlink(f"/tmp/tlecdcwg/{select_tl}.conf") Path.unlink(f"/tmp/tlecdcwg/{select_tl}.conf")
with open(f"{Path.home()}/.config/wire_py/keys", "r", encoding="utf-8") as readfile: with open(keys, "r", encoding="utf-8") as readfile:
with open(f"{Path.home()}/.config/wire_py/keys2", "w", encoding="utf-8") as writefile: with open(f"{Path.home()}/.config/wire_py/keys2", "w", encoding="utf-8") as writefile:
for line in readfile: for line in readfile:
if pre_key not in line.strip("\n"): if pre_key not in line.strip("\n"):
@ -475,7 +480,9 @@ class FrameWidgets(ttk.Frame):
LxTools.msg_window(img_w, img_i2, sl, pfit) LxTools.msg_window(img_w, img_i2, sl, pfit)
def tl_rename(self) -> None: def tl_rename(self) -> None:
"""
method to rename a tunnel
"""
special_characters = ["\\", "/", "{", "}", " "] special_characters = ["\\", "/", "{", "}", " "]
if len(self.lb_rename.get()) > 12: if len(self.lb_rename.get()) > 12:
@ -531,19 +538,8 @@ class FrameWidgets(ttk.Frame):
def import_sl(self) -> None: def import_sl(self) -> None:
""" """
Import Methode for Wireguard config Files. validity check of wireguard config files
Before importing, it is checked whether PrivateKey and PublicKey are in the file.
If True, then it is checked whether the PreSharedKey is already in the key file
to avoid an import error so that no double wgconf are imported.
Thus, tunnels can be renamed without the problems arising.
If False, then the key is written into the file.
Furthermore, it is checked whether the name is longer than 12 characters.
If True, then the name is automatically shortened to 12 characters
and then imported.
If in each case false comes out, a corresponding window comes to
inform the user that something is wrong.
""" """
Create.dir_and_files() Create.dir_and_files()
try: try:
@ -560,70 +556,70 @@ class FrameWidgets(ttk.Frame):
key = Tunnel.con_to_dict(file) key = Tunnel.con_to_dict(file)
pre_key = key[3] pre_key = key[3]
if len(pre_key) != 0: if len(pre_key) != 0:
with open(f"{Path.home()}/.config/wire_py/keys", "r", encoding="utf-8") as readfile:
p_key = readfile.readlines()
if pre_key in p_key or f"{pre_key}\n" in p_key:
msg_t = _("Tunnel already available!\nPlease use another file for import") p_key = keys.read_text(encoding="utf-8")
LxTools.msg_window(img_w2, img_i2, ie, msg_t) if pre_key in p_key or f"{pre_key}\n" in p_key:
else: msg_t = _("Tunnel already available!\nPlease use another file for import")
LxTools.msg_window(img_w2, img_i2, ie, msg_t)
with open(f"{Path.home()}/.config/wire_py/keys", "a", encoding="utf-8") as keyfile: else:
keyfile.write(f"{pre_key}\r")
if len(path_split1) > 17:
p1 = shutil.copy(filepath, "/tmp/tlecdcwg/")
path_split = path_split1[len(path_split1) - 17:]
os.rename(p1, f"/tmp/tlecdcwg/{path_split}")
new_conf = f"/tmp/tlecdcwg/{path_split}"
if self.a != "":
check_call(["nmcli", "connection", "down", self.a])
self.reset_fields()
subprocess.check_output(["nmcli", "connection", "import", "type", with open(keys, "a", encoding="utf-8") as keyfile:
"wireguard", "file", new_conf], text=True) keyfile.write(f"{pre_key}\r")
if len(path_split1) > 17:
p1 = shutil.copy(filepath, "/tmp/tlecdcwg/")
path_split = path_split1[len(path_split1) - 17:]
os.rename(p1, f"/tmp/tlecdcwg/{path_split}")
new_conf = f"/tmp/tlecdcwg/{path_split}"
if self.a != "":
check_call(["nmcli", "connection", "down", self.a])
self.reset_fields()
Create.encrypt() subprocess.check_output(["nmcli", "connection", "import", "type",
"wireguard", "file", new_conf], text=True)
else: Create.encrypt()
shutil.copy(filepath, "/tmp/tlecdcwg/")
if self.a != "":
check_call(["nmcli", "connection", "down", self.a])
self.reset_fields()
subprocess.check_output(["nmcli", "connection", "import", "type", else:
"wireguard", "file", filepath], text=True) shutil.copy(filepath, "/tmp/tlecdcwg/")
if self.a != "":
check_call(["nmcli", "connection", "down", self.a])
self.reset_fields()
Create.encrypt() subprocess.check_output(["nmcli", "connection", "import", "type",
"wireguard", "file", filepath], text=True)
self.str_var.set("") Create.encrypt()
self.a = Tunnel.active()
self.l_box.insert(0, self.a)
self.wg_autostart.configure(state="normal")
self.l_box.selection_clear(0, tk.END)
self.l_box.update()
self.l_box.selection_set(0)
Tooltip(self.wg_autostart, _("To use the autostart, enable this Checkbox"), tips) self.str_var.set("")
self.a = Tunnel.active()
self.l_box.insert(0, self.a)
self.wg_autostart.configure(state="normal")
self.l_box.selection_clear(0, tk.END)
self.l_box.update()
self.l_box.selection_set(0)
# Tooltip(self.l_box, _("List of available tunnels")) Tooltip(self.wg_autostart, _("To use the autostart, enable this Checkbox"), tips)
Tooltip(self.btn_tr, _("Click to delete a Wireguard Tunnel\nSelect from the list!") # Tooltip(self.l_box, _("List of available tunnels"))
, tips,)
Tooltip(self.btn_exp, _(" Click to export all\nWireguard Tunnel to Zipfile") Tooltip(self.btn_tr, _("Click to delete a Wireguard Tunnel\nSelect from the list!")
, tips) , tips,)
Tooltip(self.btn_rename, _("To rename a tunnel, you need to\nselect a tunnel from" Tooltip(self.btn_exp, _(" Click to export all\nWireguard Tunnel to Zipfile")
" the list"), tips) , tips)
self.lb_rename.insert(0, "Max. 12 characters!") Tooltip(self.btn_rename, _("To rename a tunnel, you need to\nselect a tunnel from"
self.str_var = tk.StringVar() " the list"), tips)
self.str_var.set(self.a)
self.color_label() self.lb_rename.insert(0, "Max. 12 characters!")
self.stop() self.str_var = tk.StringVar()
data = self.handle_tunnel_data(self.a) self.str_var.set(self.a)
check_call(["nmcli", "con", "mod", self.a, "connection.autoconnect", "no"]) self.color_label()
self.stop()
data = self.handle_tunnel_data(self.a)
check_call(["nmcli", "con", "mod", self.a, "connection.autoconnect", "no"])
if ("PrivateKey = " in read) and ("Endpoint = " in read): if ("PrivateKey = " in read) and ("Endpoint = " in read):
pass pass
@ -650,7 +646,6 @@ class FrameWidgets(ttk.Frame):
Returns: Returns:
tuple[str, str]: tuple with tunnel data tuple[str, str]: tuple with tunnel data
""" """
wg_read = f"/tmp/tlecdcwg/{tunnel_name}.conf" wg_read = f"/tmp/tlecdcwg/{tunnel_name}.conf"
with open(wg_read, "r", encoding="utf-8") as file: with open(wg_read, "r", encoding="utf-8") as file:
data = Tunnel.con_to_dict(file) data = Tunnel.con_to_dict(file)
@ -719,7 +714,6 @@ class FrameWidgets(ttk.Frame):
Displays the value address, DNS and peer in the labels Displays the value address, DNS and peer in the labels
or empty it again or empty it again
""" """
# Address Label # Address Label
self.add = tk.StringVar() self.add = tk.StringVar()
self.add.set(f"{_("Address: ")}{data[0]}") self.add.set(f"{_("Address: ")}{data[0]}")
@ -731,7 +725,6 @@ class FrameWidgets(ttk.Frame):
def reset_fields(self) -> None: def reset_fields(self) -> None:
""" """
reset data from labels reset data from labels
""" """
fields = [self.add, self.DNS, self.enp] fields = [self.add, self.DNS, self.enp]
for field in fields: for field in fields:
@ -741,7 +734,6 @@ class FrameWidgets(ttk.Frame):
""" """
shows data in the label shows data in the label
""" """
# Address Label # Address Label
self.address = ttk.Label(self.lb_frame, textvariable=self.add, foreground="#0071ff") self.address = ttk.Label(self.lb_frame, textvariable=self.add, foreground="#0071ff")
self.address.grid(column=0, row=5, sticky="w", padx=10, pady=6) self.address.grid(column=0, row=5, sticky="w", padx=10, pady=6)