7 Commits

Author SHA1 Message Date
Yannik Schmidt
c256a8ae3b whitespaces: infowidget fixes 2025-02-15 20:07:57 +01:00
Yannik Schmidt
554b4ece7a fix: add database.db to gitignore 2025-02-15 19:44:08 +01:00
Yannik Schmidt
a01d8992c0 feat: spawn info widget from client.py 2025-02-15 19:43:35 +01:00
Yannik Schmidt
e35803ce1a feat: basic download tracking in db 2025-02-15 19:43:20 +01:00
Yannik Schmidt
0d4fd8852d add: info widget basic idea 2025-02-15 16:44:15 +01:00
Yannik Schmidt
7719764604 fix: handle callback crash after view-switch 2025-02-15 16:44:00 +01:00
Yannik Schmidt
b0741929a3 fix: remove pg bar and various output problems 2025-02-15 16:16:13 +01:00
10 changed files with 216 additions and 57 deletions

1
.gitignore vendored
View File

@@ -15,3 +15,4 @@ example_software_root/
# windows dir on linux ä
**\\install-dir/
server/data/
database.db

View File

@@ -10,6 +10,7 @@ import cache_utils
import imagetools
import webbrowser
import statekeeper
import infowidget
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("blue")
@@ -27,6 +28,8 @@ details_elements = []
non_disabled_entry_color = None
all_metadata = None
infowidget_window = None
db = None # app data-backend (i.e. LocalFS or FTP)
CONFIG_FILE = "gamevault_config.json"
@@ -180,9 +183,13 @@ def load_main():
'''Load the main page overview'''
global all_metadata
global infowidget_window
app.title("Lan Vault: Overview")
if not infowidget_window:
infowidget_window = infowidget.ProgressBarApp(app)
# navbar should not expand when window is resized
app.grid_rowconfigure(0, weight=0)
# buttongrid (scrollable frame) should expand when window is resized

View File

@@ -49,17 +49,17 @@ def create_details_page(app, software, backswitch_function):
back_button.pack(anchor="nw", side="left")
# progress bar #
progress_bar = software.progress_bar_wrapper.new(navbar)
progress_bar.pack(anchor="nw", side="left", padx=20, pady=5)
#progress_bar = software.progress_bar_wrapper.new(navbar)
#progress_bar.pack(anchor="nw", side="left", padx=20, pady=5)
# progress bar text #
progress_text = software.progress_bar_wrapper.new_text(navbar)
progress_text.pack(anchor="nw", side="left", padx=20, pady=5)
#progress_text = software.progress_bar_wrapper.new_text(navbar)
#progress_text.pack(anchor="nw", side="left", padx=20, pady=5)
elements.append(navbar)
elements.append(back_button)
elements.append(progress_bar)
elements.append(progress_text)
#elements.append(progress_bar)
#elements.append(progress_text)
# thumbnail image #
thumbnail_image = customtkinter.CTkButton(app, text="", image=img, width=500, height=700,
@@ -132,7 +132,7 @@ def create_details_page(app, software, backswitch_function):
remove_text = "Remove (not implemented)" # FIXME: change text once implemented
install_button = customtkinter.CTkButton(button_frame, text=install_text,
command=lambda: software.install())
command=lambda: software.install_async())
# add remove button #
remove_button = customtkinter.CTkButton(button_frame, text=remove_text,

View File

@@ -138,15 +138,13 @@ class HTTP(DataBackend):
# the content is needed for the UI now and not cached, it's needs to be downloaded synchroniously #
# as there cannot be a meaningful UI-draw without it. #
r = requests.get(self._get_url(), params={ "path" : path, "as_string": True })
print("Request Content:", r.text)
# cache the download imediatelly #
with open(local_file, encoding="utf-8", mode="w") as f:
f.write( r.text)
# return the content #
print("Content for", fullpath, ":", r.text)
f.write(r.text)
if return_content:
print("Content for", fullpath, ":", r.text)
return r.text
else:
return local_file

34
db.py Normal file
View File

@@ -0,0 +1,34 @@
from sqlalchemy import Column, String, Integer, Boolean, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
class Download(Base):
__tablename__ = 'files'
path = Column(String, primary_key=True)
size = Column(Integer)
type = Column(String)
finished = Column(Boolean)
class Database:
def __init__(self, db_url="sqlite:///database.db"):
self.engine = create_engine(db_url, echo=True)
self.session_factory = sessionmaker(bind=self.engine)
self.Session = scoped_session(self.session_factory) # Thread-safe sessions
# Automatically create tables
Base.metadata.create_all(self.engine)
def session(self):
"""Returns a new session (or an existing one if in the same thread)."""
return self.Session()
def close_session(self):
"""Closes the current session."""
self.Session.remove()
# Singleton instance of Database
db = Database()

90
infowidget.py Normal file
View File

@@ -0,0 +1,90 @@
# in the background queue write filename in sqlite db
# get filename for sqlitedb
# get the size with info=1 from server
# only display for size>10M
# make a list of pregressbars
# start background thread with main list and main widget
# update list and widget
# update list and widget
import tkinter as tk
from tkinter import ttk
import threading
import random
import time
import string
class ProgressBarApp:
def __init__(self, parent):
self.root = tk.Toplevel(parent)
self.root.title("Dynamic Progress Bars")
self.delete_all_button = tk.Button(self.root, text="Delete All Finished", command=self.delete_all_finished, state=tk.DISABLED)
self.delete_all_button.pack(pady=5)
self.frame = tk.Frame(self.root)
self.frame.pack(pady=10)
self.progress_bars = [] # Store tuples of (progressbar, frame, duration, delete_button)
self.running = True
threading.Thread(target=self.add_progress_bars, daemon=True).start()
def add_progress_bars(self):
while self.running:
frame = tk.Frame(self.frame)
frame.pack(fill=tk.X, pady=2)
progress = ttk.Progressbar(frame, length=200, mode='determinate')
progress.pack(side=tk.LEFT, padx=5)
delete_button = tk.Button(frame, text="Delete", command=lambda f=frame: self.delete_progress(f), state=tk.DISABLED)
delete_button.pack(side=tk.LEFT, padx=5)
random_letter = random.choice(string.ascii_uppercase)
label = tk.Label(frame, text=random_letter)
label.pack(side=tk.LEFT, padx=5)
self.progress_bars.insert(0, (progress, frame, delete_button)) # Insert at the top
frame.pack(fill=tk.X, pady=2, before=self.frame.winfo_children()[-1] if self.frame.winfo_children() else None)
duration = random.randint(1, 10) # Random fill time
threading.Thread(target=self.fill_progress, args=(progress, duration, frame, delete_button), daemon=True).start()
time.sleep(30) # Wait before adding a new progress bar
def fill_progress(self, progress, duration, frame, delete_button):
for i in range(101): # Fill progress bar over 'duration' seconds
time.sleep(duration / 100)
if not progress.winfo_exists(): # Check if progress bar still exists
return
self.root.after(0, progress.config, {"value": i})
self.root.after(0, delete_button.config, {"state": tk.NORMAL})
self.progress_bars.append((progress, frame, duration, delete_button))
self.update_delete_all_button()
def delete_progress(self, frame):
frame.destroy()
self.progress_bars = [(p, f, d, b) for p, f, d, b in self.progress_bars if f != frame]
self.update_delete_all_button()
def delete_all_finished(self):
for _, frame, _, _ in self.progress_bars:
frame.destroy()
self.progress_bars.clear()
self.update_delete_all_button()
def update_delete_all_button(self):
if self.progress_bars:
self.delete_all_button.config(state=tk.NORMAL)
else:
self.delete_all_button.config(state=tk.DISABLED)
def on_close(self):
self.running = False
self.root.destroy()

View File

@@ -17,7 +17,7 @@ def unpack_software(software_cache_path, target_path):
'''Unpack a downloaded software to the target location'''
pass
def install_registry_file(registry_file, game_path=None):
def install_registry_file(registry_file):
'''Install a given registy file'''
# test path:
@@ -27,13 +27,6 @@ def install_registry_file(registry_file, game_path=None):
p = subprocess.Popen(["wine64", "start", "regedit", registry_file],
subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
print("Running regedit for wine..")
else:
# windows sucky sucky #
if not os.path.isabs(registry_file):
registry_file = os.path.join(os.getcwd(), registry_file)
p = subprocess.Popen(["python", "regedit.py", registry_file],
subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
print(p.communicate())
@@ -59,7 +52,7 @@ def run_exe(path, synchronous=False):
paths = path
# sanity check path is list #
if not type(path) == list:
if not type(paths) == list:
raise AssertionError("ERROR: run_exe could not build a list of paths")
if os.name != "nt":
@@ -85,7 +78,10 @@ def run_exe(path, synchronous=False):
p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File",
"windows_run_as_admin.ps1", json.dumps(paths)],
subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
print(p.communicate())
try:
print(p.communicate())
except UnicodeDecodeError as e:
print("WARNING: cannot show you ERROR from exe because output contained illegal characters. This maybe because your refused the admin prompt.")
else:
raise e

View File

@@ -1,14 +0,0 @@
from pyuac.main_decorator import main_requires_admin
import sys
import subprocess
@main_requires_admin(return_output=True)
def main(registry_file):
p = subprocess.Popen(["regedit", registry_file],
subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = p.communicate()
if __name__ == '__main__':
registry_file = sys.argv[-1]
rv = main(registry_file)
print(rv)

View File

@@ -8,6 +8,10 @@ import pathlib
import tqdm
import webbrowser
import jinja_helper
import threading
import sys
import tkinter
import statekeeper
class Software:
@@ -30,10 +34,10 @@ class Software:
raise e
self.invalid = True
if not progress_bar_wrapper:
raise AssertionError()
# if not progress_bar_wrapper:
# raise AssertionError()
self.progress_bar_wrapper = progress_bar_wrapper
# self.progress_bar_wrapper = progress_bar_wrapper
def _load_from_yaml(self):
@@ -90,17 +94,21 @@ class Software:
try:
zip_ref.extract(member, software_path)
count += 1
self.progress_bar_wrapper.get_pb().set(count/len(total_count))
self.progress_bar_wrapper.get_pb().update_idletasks()
self.progress_bar_wrapper.set_text(
text="Extracting: {:.2f}%".format(count/len(total_count)*100))
#self.progress_bar_wrapper.get_pb().set(count/len(total_count))
#self.progress_bar_wrapper.get_pb().update_idletasks()
#self.progress_bar_wrapper.set_text(
# text="Extracting: {:.2f}%".format(count/len(total_count)*100))
except zipfile.error as e:
pass # TODO ???
#zip_ref.extractall(software_path)
self.progress_bar_wrapper.set_text(text="Loading..")
self.progress_bar_wrapper.update()
#self.progress_bar_wrapper.set_text(text="Loading..")
#self.progress_bar_wrapper.update()
def install_async(self):
thread = threading.Thread(target=self.install)
thread.start()
def install(self):
'''Install this software from the backend'''
@@ -115,8 +123,8 @@ class Software:
webbrowser.open(self.link_only)
return
self.progress_bar_wrapper.set_text(text="Please wait..")
self.progress_bar_wrapper.tk_parent.update_idletasks()
#self.progress_bar_wrapper.set_text(text="Please wait..")
#self.progress_bar_wrapper.tk_parent.update_idletasks()
path = os.path.join(self.directory, "main_dir")
try:
@@ -124,7 +132,10 @@ class Software:
except IndexError:
print("No main_dir:", path)
raise AssertionError("No main_dir for this software")
local_file = self.backend.get(remote_file, self.cache_dir)
statekeeper.log_begin_download(remote_file)
local_file = self.backend.get(remote_file, self.cache_dir, wait=True)
statekeeper.log_end_download(remote_file)
# execute or unpack #
if local_file.endswith(".exe"):
@@ -143,8 +154,10 @@ class Software:
print("Install dir Registry:", target_install_dir)
path = jinja_helper.render_path(path, target_install_dir, self.directory)
admin_run_list.append(path)
# localaction.install_registry_file(path)
if sys.platform == "win32":
admin_run_list.append(path)
else:
localaction.install_registry_file(path)
# install dependencies #
if self.dependencies:
@@ -179,11 +192,13 @@ class Software:
os.makedirs(dest_dir, exist_ok=True)
shutil.copy(tmp, dest_dir)
self.progress_bar_wrapper.set_text(text="")
if self.run_button:
self.run_button.configure(state=tkinter.NORMAL)
self.run_button.configure(fg_color="green")
#self.progress_bar_wrapper.set_text(text="")
try:
if self.run_button:
self.run_button.configure(state=tkinter.NORMAL)
self.run_button.configure(fg_color="green")
except tkinter.TclError:
print("INFO: No longer in installation view - no button to update")
def run(self):
'''Run the configured exe for this software'''

View File

@@ -1,6 +1,9 @@
import requests
import os
import sqlalchemy
import threading
from db import db, Download
from sqlalchemy import or_, and_
def add_to_download_queue(url, path):
'''The download is added to the global queue and downloaded eventually'''
@@ -34,3 +37,32 @@ def _download(url, path):
else:
raise AssertionError("Non-200 Response for:", url, path, response.status_code, response.text)
def log_begin_download(path):
session = db.session()
print("Current path", path)
path_exists = session.query(Download).filter(and_(Download.path==path, Download.finished==False)).first()
if path_exists:
print("DAFUG", path_exists)
print("WTF", path_exists.path)
raise AssertionError("ERROR: {} is already downloading.".format(path))
else:
print("Adding to download log:", path)
session.merge(Download(path=path, size=0, type="download", finished=False))
session.commit()
db.close_session()
def log_end_download(path):
session = db.session()
path_exists = session.query(Download).filter(Download.path==path).first()
if not path_exists:
raise AssertionError("ERROR: {} is not downloading/cannot remove.".format(path))
else:
print("Removing from download log:", path)
session.merge(Download(path=path, size=0, type="download", finished=True))
session.commit()
db.close_session()