Compare commits

...

23 Commits

Author SHA1 Message Date
shayaa a56969f19d Add GitHub Actions workflow for building testing executables 2026-03-17 23:43:47 +01:00
shayaa 5bb732072e Merge pull request #48 from KeksPirates/fix/link-updater-to-gui
link updater to gui again
2026-03-16 03:04:35 +01:00
Vxrtrauter f50bfd0aa0 link updater to gui again 2026-03-16 03:04:14 +01:00
shayaa 71adbfcd96 Merge pull request #47 from KeksPirates/fix/invalid-version-detection
Fix invalid version detection
2026-03-16 02:45:46 +01:00
Vxrtrauter 270ee027f7 feat: add semi-dynamic discovering of build info file 2026-03-16 02:31:03 +01:00
Vxrtrauter a443f64501 refactor: move build_info.json to root folder, update workflow to support changes, rename function to more accurate name 2026-03-16 02:02:03 +01:00
Vxrtrauter 0e05f42741 Fix invalid version detection, refactor main.py and add comments for improved code understanding 2026-03-16 01:35:52 +01:00
shayaa d33c01941e Merge pull request #46 from KeksPirates/feat/improve-code-quality
feat: improve output statements on exception blocks
2026-03-15 23:20:19 +01:00
Vxrtrauter 053ea7694d feat: improve output statements on exception blocks 2026-03-15 23:19:32 +01:00
shayaa c25802cb95 Merge pull request #45 from KeksPirates/feat/improve-code-quality
feat: improve code quality
2026-03-15 23:08:30 +01:00
Vxrtrauter 62b24c7111 feat: improve code quality by fixing typos, adding print statements to exception blocks, remove unused imports etc 2026-03-15 23:01:02 +01:00
shayaa b0e4368e25 Merge pull request #44 from KeksPirates/refactor/gui
Refactor GUI - Merge due to changes being stable.
2026-03-15 22:34:00 +01:00
KeksNino 79f9155d76 fix settings dialog being empty 2026-03-13 19:26:38 +01:00
KeksNino 7cc36fb3ed refactor (almost) entire gui to split into multiple files 2026-03-13 18:57:25 +01:00
shayaa 7de83ae6d0 remove contributor image from README 2026-03-13 14:30:30 +01:00
shayaa 0374cbf511 Merge branch 'fix/gofile' into main 2026-03-11 22:26:10 +01:00
KeksNino 7df7d87928 fix gofile downloads by adding custom headers to both direct dl and api request
still needs work: 1. fix restart causing the download to instantly jump to 100%
2026-03-11 22:15:00 +01:00
Vxrtrauter e97f9ffe8a refactor imports 2026-03-11 15:40:25 +01:00
Vxrtrauter c4685dc2de fix: retry file deletion to allow libtorrent to release handles 2026-03-11 00:57:48 +01:00
Vxrtrauter f34d02d3d0 fix: minor inexistent variable in loghandler 2026-03-11 00:44:53 +01:00
Vxrtrauter 91b5c12afa feat: multithreaded update downloads + refactor updater into utils/network 2026-03-11 00:43:00 +01:00
Vxrtrauter b77867b111 feat: QoL features to Updater, workflow trigger. 2026-03-11 00:07:11 +01:00
Vxrtrauter bf20625832 Fix Torrent Handle errors 2026-03-10 22:45:25 +01:00
43 changed files with 1236 additions and 842 deletions
+1 -7
View File
@@ -125,8 +125,6 @@ jobs:
--upx-binary="${{ env.UPX_BINARY }}" \
--noinclude-qt-translations \
--include-data-files=build_info.json=build_info.json \
--include-data-files=build_info.json=src/build_info.json \
--include-data-files=build_info.json=src/core/interface/build_info.json \
--output-filename=${{ env.APP_NAME }}.exe \
--output-dir=nuitka-build \
src/main.py
@@ -137,8 +135,6 @@ jobs:
run: |
pyinstaller --onefile --windowed \
--add-data "build_info.json:." \
--add-data "build_info.json:src/core" \
--add-data "build_info.json:src/core/interface" \
--exclude-module PyQt6 \
--exclude-module PyQt5 \
--hidden-import=backports.tarfile \
@@ -155,8 +151,6 @@ jobs:
run: |
pyinstaller --onefile \
--add-data "build_info.json:." \
--add-data "build_info.json:src/core" \
--add-data "build_info.json:src/core/interface" \
--exclude-module PyQt6 \
--exclude-module PyQt5 \
--hidden-import=backports.tarfile \
@@ -287,4 +281,4 @@ jobs:
release/SoftwareManager-dev-${{ needs.build.outputs.short_sha }}-macos
release/SHA256SUMS.txt
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+185
View File
@@ -0,0 +1,185 @@
name: Build Executables (Test)
on:
workflow_dispatch:
permissions:
contents: read
env:
PYTHON_VERSION: "3.12"
APP_NAME: "SoftwareManager"
jobs:
build:
name: Build ${{ matrix.os }}
strategy:
fail-fast: false # keep other platforms building even if one fails
matrix:
include:
- os: ubuntu-22.04
artifact_name: SoftwareManager-test-${{ github.sha }}-linux
- os: windows-latest
artifact_name: SoftwareManager-test-${{ github.sha }}-windows
- os: macos-latest
artifact_name: SoftwareManager-test-${{ github.sha }}-macos
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
version: "0.9.7"
enable-cache: true
- name: Install Python dependencies
run: |
uv pip install -r requirements.txt
uv pip install Pillow
env:
UV_SYSTEM_PYTHON: 1
- name: Install Nuitka (Windows only)
if: runner.os == 'Windows'
run: uv pip install nuitka
env:
UV_SYSTEM_PYTHON: 1
- name: Generate version
id: version
shell: bash
run: |
SHORT_SHA="${{ github.sha }}"
SHORT_SHA="${SHORT_SHA:0:7}"
BRANCH="${{ github.head_ref || github.ref_name }}"
BRANCH_SLUG="${BRANCH//\//-}" # replace slashes with dashes
VERSION="${BRANCH_SLUG}-${SHORT_SHA}-test"
echo "VERSION=$VERSION" >> $GITHUB_ENV
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "short_sha=$SHORT_SHA" >> $GITHUB_OUTPUT
echo "Generated version: $VERSION"
- name: Inject build info
shell: bash
run: |
cat > build_info.json << EOF
{
"version": "${{ env.VERSION }}"
}
EOF
- name: Install UPX (Windows)
if: runner.os == 'Windows'
shell: bash
run: |
curl -sL https://github.com/upx/upx/releases/download/v5.1.0/upx-5.1.0-win64.zip -o upx.zip
7z x upx.zip -oupx-dir
UPX_DIR="$(pwd)/upx-dir/upx-5.1.0-win64"
echo "$UPX_DIR" >> $GITHUB_PATH
export PATH="$UPX_DIR:$PATH"
echo "UPX_BINARY=$UPX_DIR/upx.exe" >> $GITHUB_ENV
upx --version | head -1
- name: Convert icon for Windows
if: runner.os == 'Windows'
shell: bash
run: |
python -c "
from PIL import Image
img = Image.open('src/core/interface/assets/logo.png')
img.save('app_icon.ico', format='ICO', sizes=[(256,256),(128,128),(64,64),(48,48),(32,32),(16,16)])
print('Icon converted successfully')
"
- name: Build with Nuitka (Windows)
if: runner.os == 'Windows'
shell: bash
run: |
python -m nuitka \
--standalone \
--assume-yes-for-downloads \
--windows-console-mode=disable \
--windows-icon-from-ico=app_icon.ico \
--enable-plugin=pyside6 \
--enable-plugin=upx \
--upx-binary="${{ env.UPX_BINARY }}" \
--noinclude-qt-translations \
--include-data-files=build_info.json=build_info.json \
--output-filename=${{ env.APP_NAME }}.exe \
--output-dir=nuitka-build \
src/main.py
- name: Build with PyInstaller (Linux)
if: runner.os == 'Linux'
shell: bash
run: |
pyinstaller --onefile --windowed \
--add-data "build_info.json:." \
--exclude-module PyQt6 \
--exclude-module PyQt5 \
--hidden-import=backports.tarfile \
--hidden-import=backports \
--hidden-import=jaraco.context \
--hidden-import=jaraco.text \
--hidden-import=jaraco.functools \
--name ${{ env.APP_NAME }} \
src/main.py
- name: Build with PyInstaller (macOS)
if: runner.os == 'macOS'
shell: bash
run: |
pyinstaller --onefile \
--add-data "build_info.json:." \
--exclude-module PyQt6 \
--exclude-module PyQt5 \
--hidden-import=backports.tarfile \
--hidden-import=backports \
--hidden-import=jaraco.context \
--hidden-import=jaraco.text \
--hidden-import=jaraco.functools \
--name ${{ env.APP_NAME }} \
src/main.py
- name: Stage artifact
shell: bash
run: |
mkdir -p dist-final
if [ "$RUNNER_OS" == "Windows" ]; then
mv nuitka-build/main.dist dist-final/${{ env.APP_NAME }}
else
chmod +x dist/${{ env.APP_NAME }}
mv dist/${{ env.APP_NAME }} dist-final/${{ matrix.artifact_name }}
fi
ls -la dist-final/
- name: Create ZIP (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
Compress-Archive -Path "dist-final/${{ env.APP_NAME }}/*" -DestinationPath "dist-final/${{ matrix.artifact_name }}.zip"
- name: Upload artifact (Windows)
if: runner.os == 'Windows'
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.os }}-build
path: dist-final/${{ matrix.artifact_name }}.zip
retention-days: 7
- name: Upload artifact (Linux/macOS)
if: runner.os != 'Windows'
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.os }}-build
path: dist-final/${{ matrix.artifact_name }}
retention-days: 7
-6
View File
@@ -62,12 +62,6 @@ SoftwareManager is a Python-based GUI tool that simplifies searching and downloa
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=KeksPirates/SoftwareManager&type=date&legend=top-left" />
</picture>
</a>
## Contributors
<a href="https://github.com/KeksPirates/SoftwareManager/graphs/contributors">
<img src="https://contrib.rocks/image?repo=KeksPirates/SoftwareManager" />
</a>
---
**Disclaimer:** SoftwareManager is intended for legal and ethical use only. Ensure compliance with applicable laws and regulations when using this tool.
+1 -1
View File
@@ -1,5 +1,5 @@
from core.utils.data.state import state
from core.utils.data.tracker import get_magnet_link
from core.utils.data.state import state
from bs4 import BeautifulSoup
from typing import Dict
import requests
+19 -9
View File
@@ -1,4 +1,4 @@
from core.utils.logging.loghandler import consoleLog
from core.utils.logging.logs import consoleLog
import requests
import re
@@ -8,24 +8,34 @@ def scrape_gofile(url):
filetoken = re.findall(r"(?<=https...gofile.io\/d\/).*", url)[0]
session = requests.Session()
acc = session.post("https://api.gofile.io/accounts")
token = acc.json()["data"]["token"]
headers = {
"Authorization": f"Bearer {token}",
"X-Website-Token": "4fd6sg89d7s6", # Maybe make this dynamic in the future
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Referer": "https://gofile.io/",
"Authorization": f"Bearer lUUtRAccOuRUoZhelNSslDFSlpOgKLDj",
"X-Website-Token": "ffd9ffa831c50b9e68ca5e65cbbbd1a50e9a32e63022e17c7c6748388a1ed73b",
"X-BL": "en-US",
"Origin": "https://gofile.io",
"Sec-GPC": "1",
"Connection": "keep-alive",
"TE": "trailers"
}
r = session.get(
f"https://api.gofile.io/contents/{filetoken}",
headers=headers,
)
try:
temp: dict = r.json()["data"]["children"]
child = [key for key in temp.keys()]
return temp[child[0]]["link"]
except:
consoleLog("gofile didnt auth you, either the api has changed\n or you sent to many requests, please try again later.\n If it still doesnt work please open an issue on Github.")
link = temp[child[0]]["link"]
return link, headers
except Exception:
consoleLog("GoFile Authorization failed, if the Issue persists, please open an Issue on GitHub")
return None
+4 -4
View File
@@ -1,9 +1,9 @@
import requests
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
from core.utils.data.tracker import get_magnet_link
from core.utils.network.jsonhandler import split_data, format_data
from core.utils.data.tracker import get_magnet_link
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from typing import Dict
import requests
def scrape_rutracker(query):
search = requests.get(f"{state.api_url}/search?q={query}", timeout=15)
+8 -9
View File
@@ -6,8 +6,9 @@ from bs4 import BeautifulSoup
from typing import Dict
import webbrowser
import requests
import re
import time
import re
cache = {
"data": [],
@@ -68,10 +69,6 @@ def scrape_steamrip_game_downloads(gamelink):
download_links[0] = "https:" + pure
if pure[2] == "g":
download_links[1] = "https:" + pure
if pure[2] == "v":
download_links[2] = "https:" + pure
if pure[2] == "m":
download_links[3] = "https:" + pure
ret = []
@@ -93,13 +90,15 @@ def get_download_link(post: Dict):
break
if links.index(best) == 0:
return scrape_buzzheavier(best)
link = scrape_buzzheavier(best)
return link
elif links.index(best) == 1:
return scrape_gofile(best)
link, headers = scrape_gofile(best)
return link, headers
else:
consoleLog("Unable to retrieve download link due to captcha, launching browser...")
webbrowser.open(best)
return None
return None, None
def filter_steamrip(query: str):
games = scrape_steamrip_links()
@@ -120,4 +119,4 @@ Metadata = {
}
def init_steamrip():
state.trackers.update({Metadata["name"] : Metadata})
state.trackers.update({Metadata["name"] : Metadata})
+4 -4
View File
@@ -1,10 +1,10 @@
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from core.utils.data.tracker import get_magnet_link
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from core.utils.data.tracker import get_magnet_link
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from typing import Dict
import requests
def scrape_uztracker(query):
+149
View File
@@ -0,0 +1,149 @@
from core.utils.logging.logs import consoleLog, remove_download_log
from PySide6.QtWidgets import QMessageBox
from core.utils.data.state import state
from PySide6.QtCore import Qt, QPoint
from PySide6 import QtWidgets
import subprocess
import platform
import time
import os
class ContextMenu:
def __init__(self, main_window):
self.main_window = main_window
self.context_menu = QtWidgets.QMenu(main_window)
self.context_menu.addAction("Open Containing Folder", self.openFolderAction)
self.context_menu.addAction("Copy Magnet URI", self.copyMagnetURIAction)
self.context_menu.addAction("Remove from list", self.cancelDownloadAction)
self.context_menu.addAction("Delete File", self.deleteFileAction)
main_window.downloadList.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
main_window.downloadList.customContextMenuRequested.connect(self._show_context_menu)
@property
def downloadList(self):
return self.main_window.downloadList
def _show_context_menu(self, pos: QPoint):
index = self.downloadList.indexAt(pos)
if index.isValid():
self._context_menu_row = index.row()
self.context_menu.exec(self.downloadList.viewport().mapToGlobal(pos))
def openFolderAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
download_path = magnetdl.save_path()
if download_path and os.path.exists(download_path):
if platform.system() == "Windows":
os.startfile(os.path.normpath(download_path))
elif platform.system() == "Linux":
subprocess.Popen(["xdg-open", download_path])
elif platform.system() == "Darwin":
subprocess.Popen(["open", download_path])
def copyMagnetURIAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(magnet_link)
def cancelDownloadAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
with state.downloads_lock:
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
# Cache the name BEFORE removing from session
try:
torrent_name = magnetdl.status().name
except RuntimeError:
torrent_name = "Unknown"
confirm = QMessageBox.question(
self.main_window, "Cancel Download",
f"Are you sure you want to cancel the download of '{torrent_name}'?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
)
if confirm == QMessageBox.StandardButton.Yes:
with state.downloads_lock:
state.active_downloads.pop(magnet_link, None)
remove_download_log(magnet_link)
if state.dl_session:
try:
state.dl_session.remove_torrent(magnetdl)
except Exception as e:
consoleLog(f"Exception while removing download from LibTorrent: {e}")
consoleLog(f"Cancelled download: {torrent_name}", True)
def deleteFileAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
with state.downloads_lock:
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
try:
status = magnetdl.status()
save_path = status.save_path
torrent_name = status.name
except RuntimeError:
consoleLog("Error: torrent handle already invalid", True)
with state.downloads_lock:
state.active_downloads.pop(magnet_link, None)
remove_download_log(magnet_link)
return
download_path = os.path.join(save_path, torrent_name)
confirm = QMessageBox.question(
self.main_window, "Delete Files",
f"Are you sure you want to delete the downloaded files of '{torrent_name}'? This action cannot be undone.",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
)
if confirm == QMessageBox.StandardButton.Yes:
with state.downloads_lock:
state.active_downloads.pop(magnet_link, None)
remove_download_log(magnet_link)
if state.dl_session:
try:
state.dl_session.remove_torrent(magnetdl)
time.sleep(0.5)
except Exception as e:
consoleLog(f"Exception while removing download from LibTorrent: {e}")
if download_path and os.path.exists(download_path):
import shutil
last_error = None
for attempt in range(3):
try:
if os.path.isfile(download_path):
os.remove(download_path)
else:
shutil.rmtree(download_path)
consoleLog(f"Deleted files for: {torrent_name}", True)
last_error = None
break
except Exception as e:
last_error = e
if attempt < 2:
time.sleep(0.5)
if last_error:
consoleLog(f"Error deleting files: {last_error}", True)
else:
consoleLog(f"Removed entry (files not found): {torrent_name}", True)
@@ -0,0 +1,89 @@
from core.interface.dialogs.pauseresumedelegate import PauseResumeDelegate
from core.interface.dialogs.hoverrowdelegate import HoverRowDelegate
from core.interface.dialogs.downloadmodel import DownloadModel
from core.interface.dialogs.theme import _table_stylesheet
from PySide6.QtWidgets import QTableView, QHeaderView
from core.utils.logging.logs import consoleLog
from PySide6 import QtWidgets
from PySide6.QtCore import Qt
def _create_download_list(self) -> QTableView:
self.download_model = DownloadModel()
self.downloadList.setModel(self.download_model)
self.downloadList.horizontalHeader().setStretchLastSection(False)
self.downloadList.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
self.downloadList.horizontalHeader().resizeSection(0, 70)
self.downloadList.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
self.downloadList.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setMinimumSectionSize(60)
self.downloadList.verticalHeader().setDefaultSectionSize(40)
self.downloadList.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
self.downloadList.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
self.downloadList.verticalHeader().setVisible(False)
self.downloadList.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
self.downloadList.horizontalHeader().setHighlightSections(False)
self.downloadList.setMouseTracking(True)
self.downloadList.setShowGrid(False)
self.downloadList.setStyleSheet(_table_stylesheet("QTableView"))
self.downloadList.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.downloadList.viewport().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
download_model = self.download_model
def on_pause_resume_clicked(row):
download_model.toggle_pause_resume(row)
self.downloadList.viewport().setMouseTracking(True)
hover_delegate = HoverRowDelegate(self.downloadList)
self.downloadList.setItemDelegate(hover_delegate)
delegate = PauseResumeDelegate(self.downloadList)
self.downloadList.setItemDelegateForColumn(0, delegate)
delegate.clicked.connect(on_pause_resume_clicked)
return self.downloadList
def download_list_update(self):
self._update_speed_label()
if not self.download_model:
return
row_count = self.download_model.rowCount()
col_count = self.download_model.columnCount()
if row_count > 0 and col_count > 0:
top_left = self.download_model.index(0, 0)
bottom_right = self.download_model.index(row_count - 1, col_count - 1)
if top_left.isValid() and bottom_right.isValid():
self.download_model.dataChanged.emit(top_left, bottom_right, [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole])
if row_count != self._last_dl_row_count:
old_count = self._last_dl_row_count
self._last_dl_row_count = row_count
if row_count > 0:
self.download_model.layoutAboutToBeChanged.emit()
self.download_model.layoutChanged.emit()
for row in range(row_count):
idx = self.download_model.index(row, 0)
if idx.isValid():
self.downloadList.closePersistentEditor(idx)
self.downloadList.openPersistentEditor(idx)
elif old_count > 0:
self.download_model.layoutAboutToBeChanged.emit()
self.download_model.layoutChanged.emit()
else:
if row_count > 0:
delegate = self.downloadList.itemDelegateForColumn(0)
for row in range(row_count):
idx = self.download_model.index(row, 0)
if idx.isValid():
editor = self.downloadList.indexWidget(idx)
if editor and delegate:
try:
delegate.setEditorData(editor, idx)
except RuntimeError as e:
consoleLog(f"Exception while updating download list: {e}")
+136
View File
@@ -0,0 +1,136 @@
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
import libtorrent as lt
import subprocess
import platform
import os
class DownloadModel(QAbstractTableModel):
def __init__(self):
super().__init__()
self.headers = ["Action", "Name", "Status", "Progress", "Speed", "Size", "Total Size"]
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
with state.downloads_lock:
return len(state.active_downloads)
def columnCount(self, parent=QModelIndex()):
return len(self.headers)
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
return self.headers[section]
return None
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
with state.downloads_lock:
if index.row() >= len(state.active_downloads) or index.row() < 0:
return None
try:
magnet_link = list(state.active_downloads.keys())[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (IndexError, KeyError, RuntimeError):
return None
if role == Qt.ItemDataRole.DisplayRole:
col = index.column()
if col == 0:
pass
elif col == 1:
return status.name if status.has_metadata else "Fetching metadata..."
elif col == 2:
if status.paused:
is_auto = getattr(status, 'auto_managed', True)
return "Queued" if is_auto else "Paused"
elif status.state == lt.torrent_status.downloading:
return "Downloading"
elif status.state == lt.torrent_status.seeding:
return "Seeding"
else:
return "Queued"
elif col == 3:
return f"{status.progress * 100:.1f}%"
elif col == 4:
down_kb = status.download_rate / 1024
up_kb = status.upload_rate / 1024
down_text = f"{down_kb / 1024:.1f} MB/s" if down_kb > 1024 else f"{down_kb:.1f} kB/s"
up_text = f"{up_kb / 1024:.1f} MB/s" if up_kb > 1024 else f"{up_kb:.1f} kB/s"
return f"{down_text}{up_text}"
elif col == 5:
downloaded_mb = status.total_wanted_done / (1024 * 1024)
if downloaded_mb > 1024:
return f"{downloaded_mb / 1024:.2f} GB"
else:
return f"{downloaded_mb:.1f} MB"
elif col == 6:
total_mb = status.total_wanted / (1024 * 1024)
if total_mb > 1024:
return f"{total_mb / 1024:.2f} GB"
else:
return f"{total_mb:.1f} MB"
elif col == 7:
if status.download_rate > 0:
bytes_left = status.total_wanted - status.total_wanted_done
eta_seconds = bytes_left / status.download_rate
if eta_seconds < 60:
return f"{int(eta_seconds)}s"
elif eta_seconds < 3600:
minutes = int(eta_seconds / 60)
seconds = int(eta_seconds % 60)
return f"{minutes}m {seconds}s"
else:
hours = int(eta_seconds / 3600)
minutes = int((eta_seconds % 3600) / 60)
return f"{hours}h {minutes}m"
else:
return "" if status.paused else "Stalled"
if role == Qt.ItemDataRole.UserRole and index.column() == 0:
return status.paused
return None
def toggle_pause_resume(self, row):
with state.downloads_lock:
if row >= len(state.active_downloads) or row < 0:
return
try:
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (IndexError, KeyError, RuntimeError):
return
if status.state == lt.torrent_status.seeding:
try:
save_path = magnetdl.save_path()
if save_path and os.path.exists(save_path):
if platform.system() == "Windows":
os.startfile(os.path.normpath(save_path))
elif platform.system() == "Linux":
subprocess.Popen(["xdg-open", save_path])
elif platform.system() == "Darwin":
subprocess.Popen(["open", save_path])
except Exception as e:
consoleLog(f"Exception while opening file: {e}")
return
is_paused = status.paused
if is_paused:
if hasattr(magnetdl, 'set_flags'):
magnetdl.set_flags(lt.torrent_flags.auto_managed)
magnetdl.resume()
consoleLog(f"Resumed download: {status.name}", True)
else:
if hasattr(magnetdl, 'unset_flags'):
magnetdl.unset_flags(lt.torrent_flags.auto_managed)
magnetdl.pause()
consoleLog(f"Paused download: {status.name}", True)
idx = self.index(row, 0)
self.dataChanged.emit(idx, idx, [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole])
@@ -0,0 +1,22 @@
from core.interface.dialogs.theme import _theme_colors
from PySide6.QtWidgets import QStyledItemDelegate
from PySide6.QtCore import Qt
class ElidedItemDelegate(QStyledItemDelegate):
def __init__(self, get_hovered_row, parent=None):
super().__init__(parent)
self._get_hovered_row = get_hovered_row
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if option.text:
metrics = option.fontMetrics
text_rect = option.rect.adjusted(14, 0, -14, 0)
option.text = metrics.elidedText(option.text, Qt.TextElideMode.ElideMiddle, text_rect.width())
def paint(self, painter, option, index):
if index.row() == self._get_hovered_row():
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, option, index)
+36
View File
@@ -0,0 +1,36 @@
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from PySide6.QtCore import QEvent
def eventFilter(self, obj, event):
try:
if obj == state.trackertable.viewport():
if event.type() == QEvent.Type.MouseMove:
pos = event.position().toPoint() if hasattr(event, 'position') else event.pos()
idx = state.trackertable.indexAt(pos)
new_row = idx.row() if idx.isValid() else -1
if new_row != self._tracker_hovered_row or state.trackertable is not self._tracker_hovered_table:
self._tracker_hovered_row = new_row
self._tracker_hovered_table = state.trackertable
state.trackertable.viewport().update()
elif event.type() == QEvent.Type.Leave:
self._tracker_hovered_row = -1
self._tracker_hovered_table = None
state.trackertable.viewport().update()
if obj == self.downloadList.viewport():
if event.type() == QEvent.Type.MouseMove:
pos = event.position().toPoint() if hasattr(event, 'position') else event.pos()
idx = self.downloadList.indexAt(pos)
new_row = idx.row() if idx.isValid() else -1
if new_row != self._hovered_row:
old_row = self._hovered_row
self._hovered_row = new_row
self._invalidate_hover_row(old_row)
self._invalidate_hover_row(new_row)
elif event.type() == QEvent.Type.Leave:
old_row = self._hovered_row
self._hovered_row = -1
self._invalidate_hover_row(old_row)
except (RuntimeError, AttributeError) as e:
consoleLog(f"Exception in EventFilter: {e}")
return super(type(self), self).eventFilter(obj, event)
@@ -0,0 +1,19 @@
from core.interface.dialogs.theme import _theme_colors
from PySide6.QtWidgets import QStyledItemDelegate
from PySide6 import QtWidgets
class HoverRowDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
from core.interface.gui import MainWindow
opt = QtWidgets.QStyleOptionViewItem(option)
option.state &= ~QtWidgets.QStyle.StateFlag.State_HasFocus
option.state &= ~QtWidgets.QStyle.StateFlag.State_Selected
hovered_row = MainWindow._instance._hovered_row if MainWindow._instance else -1
if index.row() == hovered_row:
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, opt, index)
+29
View File
@@ -0,0 +1,29 @@
from PySide6.QtGui import QImage, QPixmap
from core.utils.data.state import state
from PySide6.QtWidgets import QLabel
from PySide6.QtCore import Qt
import os
class Image():
def __init__(self, parent):
self.overlay_label = QLabel(parent)
self.overlay_label.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
if state.image_path is not None and os.path.exists(state.image_path):
self.image = QImage(state.image_path)
self.image = self.image.scaledToWidth(300, Qt.TransformationMode.SmoothTransformation)
self.pixmap = QPixmap.fromImage(self.image)
self.overlay_label.setPixmap(self.pixmap)
self.overlay_label.adjustSize()
self.overlay_label.raise_()
x = parent.width() - self.overlay_label.width()
y = parent.height() - self.overlay_label.height()
self.overlay_label.move(x, y)
def update_image_overlay(self, new_image_path):
self.image = QImage(new_image_path)
self.pixmap = QPixmap.fromImage(self.image)
self.overlay_label.setPixmap(self.pixmap)
self.overlay_label.adjustSize()
@@ -0,0 +1,86 @@
from core.interface.dialogs.theme import _theme_colors, SVG_PLAY, SVG_PAUSE, SVG_FOLDER
from PySide6.QtWidgets import QStyledItemDelegate, QWidget, QHBoxLayout
from core.interface.utils.svghelper import svg_icon
from PySide6.QtCore import Qt, QSize, Signal
from core.utils.data.state import state
from PySide6 import QtWidgets
import libtorrent as lt
class PauseResumeDelegate(QStyledItemDelegate):
clicked = Signal(int)
def paint(self, painter, option, index):
from core.interface.gui import MainWindow
opt = QtWidgets.QStyleOptionViewItem(option)
option.state &= ~QtWidgets.QStyle.StateFlag.State_HasFocus
option.state &= ~QtWidgets.QStyle.StateFlag.State_Selected
hovered_row = MainWindow._instance._hovered_row if MainWindow._instance else -1
if index.row() == hovered_row:
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, opt, index)
def setEditorData(self, editor, index):
button = editor.findChild(QtWidgets.QPushButton)
if not button:
return
try:
with state.downloads_lock:
keys = list(state.active_downloads.keys())
if index.row() >= len(keys):
return
magnet_link = keys[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (RuntimeError, IndexError, KeyError):
return
if status.state == lt.torrent_status.seeding:
button.setIcon(svg_icon(SVG_FOLDER, 18))
button.setText("")
else:
is_user_paused = status.paused and not status.auto_managed
button.setIcon(svg_icon(SVG_PLAY if is_user_paused else SVG_PAUSE, 18))
button.setText("")
def createEditor(self, parent, option, index):
try:
with state.downloads_lock:
keys = list(state.active_downloads.keys())
if index.row() >= len(keys):
return QWidget(parent)
magnet_link = keys[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (RuntimeError, IndexError, KeyError):
return QWidget(parent)
widget = QWidget(parent)
widget.setStyleSheet("border: none; background: transparent;")
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
if status.state == lt.torrent_status.seeding:
btnPause = QtWidgets.QPushButton()
btnPause.setIcon(svg_icon(SVG_FOLDER, 18))
else:
btnPause = QtWidgets.QPushButton()
is_user_paused = status.paused and not status.auto_managed
btnPause.setIcon(svg_icon(SVG_PLAY if is_user_paused else SVG_PAUSE, 18))
btnPause.setIconSize(QSize(18, 18))
btnPause.setFixedSize(30, 30)
btnPause.setCursor(Qt.CursorShape.PointingHandCursor)
btnPause.setStyleSheet("QPushButton { border: none; background: transparent; padding: 0px; }")
btnPause.clicked.connect(lambda: self.clicked.emit(index.row()))
layout.addStretch()
layout.addWidget(btnPause)
layout.addStretch()
widget.setLayout(layout)
return widget
def editorEvent(self, event, model, option, index):
return False
+13 -11
View File
@@ -1,12 +1,12 @@
from core.utils.config.settings import save_settings
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
from core.interface.utils.tabhelper import general_tab
from core.interface.utils.tabhelper import paths_tab
from core.interface.utils.tabhelper import network_tab
from core.utils.config.settings import save_settings
from core.interface.utils.tabhelper import paths_tab
from core.interface.utils.svghelper import svg_icon
from PySide6 import QtWidgets
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from PySide6.QtCore import Qt, QSize
from PySide6 import QtWidgets
from PySide6.QtWidgets import (
QLineEdit,
QPushButton,
@@ -21,6 +21,7 @@ from PySide6.QtWidgets import (
QComboBox,
QTabWidget,
)
import platform
SVG_FOLDER = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 6c0-1.1.9-2 2-2h5l2 2h7c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6z" fill="{color}"/></svg>'
@@ -33,7 +34,8 @@ def settings_dialog(self):
dialog.setWindowTitle("Settings")
dialog.setFixedSize(700, 450)
dialog.setLayout(QVBoxLayout())
dialog_layout = QVBoxLayout()
dialog.setLayout(dialog_layout)
if state.window_transparency and platform.system() != "Windows" and dialog:
dialog.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
@@ -92,7 +94,7 @@ def settings_dialog(self):
api_url = QLineEdit()
api_url_layout.addWidget(QLabel("API Server URL:"))
api_url_layout.addWidget(api_url)
api_url_container.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
api_url_container.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Fixed)
api_url_container.setLayout(api_url_layout)
api_url.setText(state.api_url)
@@ -106,7 +108,7 @@ def settings_dialog(self):
download_path = QLineEdit()
download_path_layout.addWidget(QLabel("Download Path:"))
download_path_layout.addWidget(download_path)
download_path_container.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
download_path_container.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Fixed)
download_path_container.setLayout(download_path_layout)
download_path.setText(state.download_path)
@@ -141,7 +143,7 @@ def settings_dialog(self):
image_path = QLineEdit()
image_path_layout.addWidget(QLabel("Image Path (requires restart, experimental):"))
image_path_layout.addWidget(image_path)
image_path_container.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
image_path_container.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Fixed)
image_path_container.setLayout(image_path_layout)
image_path.setText(state.image_path)
@@ -284,7 +286,7 @@ def settings_dialog(self):
self.tab2 = paths_tab("Paths", download_path_container, image_path_container, self.tabs)
self.tab3 = network_tab("Network", interface_container, max_connections_container, max_downloads_container, up_speed_limit_container, down_speed_limit_container, api_url_container, self.tabs)
dialog.layout().addWidget(self.tabs)
dialog.layout().addLayout(layout)
dialog_layout.addWidget(self.tabs)
dialog_layout.addLayout(layout)
dialog.exec()
+79
View File
@@ -0,0 +1,79 @@
from PySide6.QtGui import QColor
import darkdetect
def _is_dark_mode():
return darkdetect.isDark()
def _theme_colors():
dark = _is_dark_mode()
if dark:
return {
"text": "rgba(255, 255, 255, 0.9)",
"border": "rgba(255, 255, 255, 0.06)",
"selected": "rgba(255, 255, 255, 0.04)",
"header_text": "rgba(255, 255, 255, 0.5)",
"header_border": "rgba(255, 255, 255, 0.1)",
"hover": QColor(255, 255, 255, 15),
}
else:
return {
"text": "rgba(0, 0, 0, 0.87)",
"border": "rgba(0, 0, 0, 0.08)",
"selected": "rgba(0, 0, 0, 0.06)",
"header_text": "rgba(0, 0, 0, 0.6)",
"header_border": "rgba(0, 0, 0, 0.12)",
"hover": QColor(0, 0, 0, 15),
}
def _table_stylesheet(view_type="QTableWidget"):
c = _theme_colors()
dark = _is_dark_mode()
color_rule = "" if dark else f"color: {c['text']};"
return f"""
{view_type} {{
border: none;
outline: 0;
font-size: 13px;
{color_rule}
}}
{view_type}::item {{
border-bottom: 1px solid {c["border"]};
padding: 6px 14px;
outline: none;
{color_rule}
}}
{view_type}::item:selected {{
background: {c["selected"]};
outline: none;
border: none;
border-bottom: 1px solid {c["border"]};
}}
{view_type}::item:focus {{
outline: none;
border: none;
border-bottom: 1px solid {c["border"]};
}}
QHeaderView {{
background: transparent;
}}
QHeaderView::section {{
background: transparent;
color: {c["header_text"]};
font-weight: normal;
border: none;
border-bottom: 1px solid {c["header_border"]};
padding: 6px 14px;
}}
QHeaderView::section:checked {{
background: transparent;
color: {c["header_text"]};
font-weight: normal;
}}
"""
SVG_PLAY = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><polygon points="6,3 20,12 6,21" fill="{color}"/></svg>'
SVG_PAUSE = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect x="5" y="3" width="4" height="18" rx="1" fill="{color}"/><rect x="15" y="3" width="4" height="18" rx="1" fill="{color}"/></svg>'
SVG_FOLDER = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 6c0-1.1.9-2 2-2h5l2 2h7c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6z" fill="{color}"/></svg>'
@@ -0,0 +1,14 @@
from core.interface.dialogs.theme import _theme_colors
from PySide6.QtWidgets import QStyledItemDelegate
class TrackerHoverDelegate(QStyledItemDelegate):
def __init__(self, get_hovered_row, parent=None):
super().__init__(parent)
self._get_hovered_row = get_hovered_row
def paint(self, painter, option, index):
if index.row() == self._get_hovered_row():
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, option, index)
@@ -0,0 +1,26 @@
from core.interface.dialogs.theme import _table_stylesheet
from PySide6.QtWidgets import QTableWidget
from PySide6 import QtWidgets
from PySide6.QtCore import Qt
def _create_tracker_table(self):
table = QTableWidget()
table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
table.verticalHeader().setVisible(False)
table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
table.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
table.setShowGrid(False)
table.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
table.viewport().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
table.horizontalHeader().setHighlightSections(False)
table.horizontalHeader().setStretchLastSection(False)
table.setStyleSheet(_table_stylesheet("QTableWidget"))
table.setMouseTracking(True)
table.viewport().setMouseTracking(True)
table.viewport().installEventFilter(self)
table.setItemDelegateForColumn(0, self._tracker_elided_delegate)
self._apply_default_headers(table)
return table
+48
View File
@@ -0,0 +1,48 @@
from core.utils.network.update_checker import get_updates
from core.utils.network.updater import download_update
from PySide6.QtWidgets import QDialog, QMessageBox
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from pathlib import Path
import platform
import json
import os
def _get_build_info_path() -> (Path | None):
current_dir = Path(__file__).resolve().parent
for _ in range(6): # Climb max 6 directories
file = current_dir / "build_info.json"
if file.exists():
return file
# Go up one directory if file isn't found
current_dir = current_dir.parent
return None
def get_version() -> None:
# Get build info filepath
build_info_path = _get_build_info_path()
if os.path.exists(build_info_path):
with open(build_info_path, "r") as f:
build_info = json.load(f)
state.version = build_info.get("version")
else:
consoleLog(f"Could not find build info file (Path: {build_info_path})")
class UpdateDialog(QDialog):
def __init__(self, parent=None):
if state.ignore_updates is False and platform.system() == "Windows":
assets, latest = get_updates()
if assets != None:
msg = QMessageBox()
msg.setIcon(QMessageBox.Icon.Information)
msg.setWindowTitle("Update Available")
msg.setText(f"A new version is available\n({latest})")
msg.setInformativeText("Press Ok to download.")
msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Ignore)
response = msg.exec_()
if response == QMessageBox.StandardButton.Ok:
download_update(assets)
+50 -689
View File
@@ -1,25 +1,31 @@
from core.utils.logging.logs import consoleLog, remove_download_log, flush_log_buffer
from core.utils.general.wrappers import run_thread
from core.utils.data.state import state
from core.utils.network.download import download_selected
from core.utils.network.update_checker import get_updates
from core.interface.utils.tabhelper import create_tab
from core.interface.utils.searchhelper import return_pressed
from core.interface.utils.svghelper import svg_icon
from core.interface.dialogs.settings import settings_dialog
from core.interface.assets.base64_icons import settings_black_base64
from core.interface.dialogs.trackerhoverdelegate import TrackerHoverDelegate
from core.interface.dialogs.elideditemdelegate import ElidedItemDelegate
from core.interface.dialogs.trackertable import _create_tracker_table
from core.interface.dialogs.downloadlist import _create_download_list
from core.interface.assets.base64_icons import settings_white_base64
from core.interface.assets.base64_icons import settings_black_base64
from core.interface.dialogs.downloadlist import download_list_update
from core.interface.dialogs.update import get_version, UpdateDialog
from core.utils.logging.logs import consoleLog, flush_log_buffer
from core.interface.dialogs.downloadmodel import DownloadModel
from core.interface.utils.searchhelper import return_pressed
from core.interface.dialogs.settings import settings_dialog
from core.interface.assets.base64_icons import logo_base64
from core.interface.dialogs.eventfilter import eventFilter
from core.utils.network.download import download_selected
from core.interface.utils.tabhelper import create_tab
from core.utils.general.shutdown import closehelper
from core.utils.general.wrappers import run_thread
from core.interface.dialogs.image import Image
from core.utils.data.state import state
import core.interface.dialogs.contextmenu
from PySide6 import QtWidgets
from PySide6.QtCore import (
Qt,
QTimer,
QModelIndex,
QAbstractTableModel,
Signal,
QEvent,
QSize
)
@@ -28,222 +34,33 @@ from PySide6.QtWidgets import (
QTableView,
QWidget,
QVBoxLayout,
QListWidget,
QLabel,
QHBoxLayout,
QComboBox,
QTabWidget,
QHeaderView,
QMessageBox,
QTableWidget,
QTableWidgetItem,
QTextEdit,
QStyledItemDelegate,
QStatusBar
)
from PySide6.QtGui import (
QIcon,
QCloseEvent,
QImage,
QPixmap,
QContextMenuEvent,
QGuiApplication,
QColor,
)
import darkdetect
import threading
import platform
import requests as r
import os
import subprocess
import libtorrent as lt
import sys
import json
import base64
def _is_dark_mode():
return darkdetect.isDark()
def _theme_colors():
dark = _is_dark_mode()
if dark:
return {
"text": "rgba(255, 255, 255, 0.9)",
"border": "rgba(255, 255, 255, 0.06)",
"selected": "rgba(255, 255, 255, 0.04)",
"header_text": "rgba(255, 255, 255, 0.5)",
"header_border": "rgba(255, 255, 255, 0.1)",
"hover": QColor(255, 255, 255, 15),
}
else:
return {
"text": "rgba(0, 0, 0, 0.87)",
"border": "rgba(0, 0, 0, 0.08)",
"selected": "rgba(0, 0, 0, 0.06)",
"header_text": "rgba(0, 0, 0, 0.6)",
"header_border": "rgba(0, 0, 0, 0.12)",
"hover": QColor(0, 0, 0, 15),
}
def _table_stylesheet(view_type="QTableWidget"):
c = _theme_colors()
dark = _is_dark_mode()
color_rule = "" if dark else f"color: {c['text']};"
return f"""
{view_type} {{
border: none;
outline: 0;
font-size: 13px;
{color_rule}
}}
{view_type}::item {{
border-bottom: 1px solid {c["border"]};
padding: 6px 14px;
outline: none;
{color_rule}
}}
{view_type}::item:selected {{
background: {c["selected"]};
outline: none;
border: none;
border-bottom: 1px solid {c["border"]};
}}
{view_type}::item:focus {{
outline: none;
border: none;
border-bottom: 1px solid {c["border"]};
}}
QHeaderView {{
background: transparent;
}}
QHeaderView::section {{
background: transparent;
color: {c["header_text"]};
font-weight: normal;
border: none;
border-bottom: 1px solid {c["header_border"]};
padding: 6px 14px;
}}
QHeaderView::section:checked {{
background: transparent;
color: {c["header_text"]};
font-weight: normal;
}}
"""
SVG_PLAY = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><polygon points="6,3 20,12 6,21" fill="{color}"/></svg>'
SVG_PAUSE = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect x="5" y="3" width="4" height="18" rx="1" fill="{color}"/><rect x="15" y="3" width="4" height="18" rx="1" fill="{color}"/></svg>'
SVG_FOLDER = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 6c0-1.1.9-2 2-2h5l2 2h7c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6z" fill="{color}"/></svg>'
def _verify_hash(file_path, expected_hash):
import hashlib
sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
return f"sha256:{sha256.hexdigest()}" == expected_hash
def _download_update(assets):
import tempfile
import time
for asset in assets:
if "-windows-setup.exe" in asset["name"]:
filename = asset["name"]
setup_hash = asset["hash"]
url = asset["url"]
break
if not filename:
consoleLog("Error: No Windows installer found in release assets")
return
installer_path = os.path.join(tempfile.gettempdir(), filename)
progress = QtWidgets.QProgressDialog("Downloading installer...", None, 0, 0)
progress.setWindowTitle("Updating")
progress.setWindowModality(Qt.WindowModality.ApplicationModal)
progress.setCancelButton(None)
progress.setMinimumDuration(0)
progress.setAutoClose(False)
progress.setAutoReset(False)
progress.setRange(0, 100)
progress.setValue(0)
progress.show()
QtWidgets.QApplication.processEvents()
response = r.get(url, allow_redirects=True, stream=True)
total = int(response.headers.get("content-length", 0))
downloaded = 0
with open(installer_path, "wb") as f:
for chunk in response.iter_content(chunk_size=65536):
f.write(chunk)
downloaded += len(chunk)
if total > 0:
progress.setValue(int(downloaded * 100 / total))
QtWidgets.QApplication.processEvents()
if not os.path.exists(installer_path):
progress.close()
raise FileNotFoundError("Executable not found")
if setup_hash:
if _verify_hash(installer_path, setup_hash):
consoleLog(f"Sucessfully validated installer hash ({setup_hash})")
else:
consoleLog("Error: Invalid Filehash, file may be corrupted")
sys.exit(0)
else:
consoleLog("Skipping Hash Verification (no hash found for release)")
progress.setLabelText("Installing update...")
progress.setValue(100)
QtWidgets.QApplication.processEvents()
subprocess.Popen([installer_path, "/VERYSILENT", "/SUPPRESSMSGBOXES", "/SP-", "/CLOSEAPPLICATIONS"])
time.sleep(1)
sys.exit(0)
def windowCloseHelper():
QGuiApplication.quit()
class ElidedItemDelegate(QStyledItemDelegate):
def __init__(self, get_hovered_row, parent=None):
super().__init__(parent)
self._get_hovered_row = get_hovered_row
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if option.text:
metrics = option.fontMetrics
text_rect = option.rect.adjusted(14, 0, -14, 0)
option.text = metrics.elidedText(option.text, Qt.TextElideMode.ElideMiddle, text_rect.width())
def paint(self, painter, option, index):
if index.row() == self._get_hovered_row():
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, option, index)
class TrackerHoverDelegate(QStyledItemDelegate):
def __init__(self, get_hovered_row, parent=None):
super().__init__(parent)
self._get_hovered_row = get_hovered_row
def paint(self, painter, option, index):
if index.row() == self._get_hovered_row():
painter.save()
painter.fillRect(option.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, option, index)
class MainWindow(QtWidgets.QMainWindow, QWidget):
eventFilter = eventFilter
log_signal = Signal(str)
search_results_signal = Signal(list)
_instance = None
@@ -259,6 +76,7 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
pixmap.loadFromData(image_data)
self.setWindowIcon(QIcon(pixmap))
# Set AppID on Windows
if platform.system() == "Windows":
try:
import ctypes
@@ -267,54 +85,40 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
except Exception as e:
consoleLog(f"Could not set app ID: {e}")
build_info_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "build_info.json")
if os.path.exists(build_info_path):
with open(build_info_path, "r") as f:
build_info = json.load(f)
state.version = build_info.get("version")
if state.ignore_updates is False and platform.system() == "Windows":
assets = get_updates()
if assets != None:
msg = QMessageBox()
msg.setIcon(QMessageBox.Icon.Information)
msg.setWindowTitle("Update Available")
msg.setText("A new version is available.")
msg.setInformativeText("Press Ok to download the update.")
msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Ignore)
response = msg.exec_()
if response == QMessageBox.StandardButton.Ok:
_download_update(assets)
# Get current version
# core.interface.dialogs.update
get_version()
UpdateDialog()
# Initialize Window
self.setWindowTitle("Software Manager")
self.setGeometry(100, 100, 800, 600)
self.controls = QWidget()
self.controlsLayout = QVBoxLayout()
# Searchbar
self.searchbar = QLineEdit()
self.searchbar.setPlaceholderText("Search for software...")
self.searchbar.setClearButtonEnabled(True)
self.searchbar.setMinimumHeight(30)
self.searchbar.returnPressed.connect(self._start_search)
# Download Button
self.dlbutton = QtWidgets.QPushButton("Download")
self.dlbutton.setCursor(Qt.CursorShape.PointingHandCursor)
self.libraryList = QListWidget()
# Dialog for empty results
self.emptyResults = QLabel("No Results")
self.emptyResults.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.emptyResults.hide()
self.download_model = None
self.downloadList = QTableView()
self.downloadList.setMouseTracking(True)
self._hovered_row = -1
self._tracker_hovered_row = -1
self._tracker_hovered_table = None
self._last_dl_row_count = 0
self.downloadList.viewport().installEventFilter(self)
self.emptyLibrary = QLabel("No items in library.")
self.emptyDownload = QLabel("No items in downloads.")
self.emptyDownload.setAlignment(Qt.AlignmentFlag.AlignCenter)
@@ -326,245 +130,17 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
self._tracker_elided_delegate = ElidedItemDelegate(lambda: self._tracker_hovered_row, self)
self._tracker_hover_delegate = TrackerHoverDelegate(lambda: self._tracker_hovered_row, self)
state.trackertable = self._create_tracker_table()
state.trackertable = _create_tracker_table(self)
container = QWidget()
containerLayout = QVBoxLayout()
containerLayout.addWidget(self.searchbar)
containerLayout.addWidget(state.trackertable)
class DownloadModel(QAbstractTableModel):
def __init__(self):
super().__init__()
self.headers = ["Action", "Name", "Status", "Progress", "Speed", "Size", "Total Size"]
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
with state.downloads_lock:
return len(state.active_downloads)
def columnCount(self, parent=QModelIndex()):
return len(self.headers)
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
return self.headers[section]
return None
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
with state.downloads_lock:
if index.row() >= len(state.active_downloads) or index.row() < 0:
return None
try:
magnet_link = list(state.active_downloads.keys())[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (IndexError, KeyError, RuntimeError):
return None
if role == Qt.ItemDataRole.DisplayRole:
col = index.column()
if col == 0:
pass
elif col == 1:
return status.name if status.has_metadata else "Fetching metadata..."
elif col == 2:
if status.paused:
is_auto = getattr(status, 'auto_managed', True)
return "Queued" if is_auto else "Paused"
elif status.state == lt.torrent_status.downloading:
return "Downloading"
elif status.state == lt.torrent_status.seeding:
return "Seeding"
else:
return "Queued"
elif col == 3:
return f"{status.progress * 100:.1f}%"
elif col == 4:
down_kb = status.download_rate / 1024
up_kb = status.upload_rate / 1024
down_text = f"{down_kb / 1024:.1f} MB/s" if down_kb > 1024 else f"{down_kb:.1f} kB/s"
up_text = f"{up_kb / 1024:.1f} MB/s" if up_kb > 1024 else f"{up_kb:.1f} kB/s"
return f"{down_text}{up_text}"
elif col == 5:
downloaded_mb = status.total_wanted_done / (1024 * 1024)
if downloaded_mb > 1024:
return f"{downloaded_mb / 1024:.2f} GB"
else:
return f"{downloaded_mb:.1f} MB"
elif col == 6:
total_mb = status.total_wanted / (1024 * 1024)
if total_mb > 1024:
return f"{total_mb / 1024:.2f} GB"
else:
return f"{total_mb:.1f} MB"
elif col == 7:
if status.download_rate > 0:
bytes_left = status.total_wanted - status.total_wanted_done
eta_seconds = bytes_left / status.download_rate
if eta_seconds < 60:
return f"{int(eta_seconds)}s"
elif eta_seconds < 3600:
minutes = int(eta_seconds / 60)
seconds = int(eta_seconds % 60)
return f"{minutes}m {seconds}s"
else:
hours = int(eta_seconds / 3600)
minutes = int((eta_seconds % 3600) / 60)
return f"{hours}h {minutes}m"
else:
return "" if status.paused else "Stalled"
if role == Qt.ItemDataRole.UserRole and index.column() == 0:
return status.paused
return None
def toggle_pause_resume(self, row):
with state.downloads_lock:
if row >= len(state.active_downloads) or row < 0:
return
try:
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
except (IndexError, KeyError, RuntimeError):
return
if status.state == lt.torrent_status.seeding:
try:
save_path = magnetdl.save_path()
if save_path and os.path.exists(save_path):
if platform.system() == "Windows":
os.startfile(os.path.normpath(save_path))
elif platform.system() == "Linux":
subprocess.Popen(["xdg-open", save_path])
elif platform.system() == "Darwin":
subprocess.Popen(["open", save_path])
except Exception:
pass
return
is_paused = status.paused
if is_paused:
if hasattr(magnetdl, 'set_flags'):
magnetdl.set_flags(lt.torrent_flags.auto_managed)
magnetdl.resume()
consoleLog(f"Resumed download: {status.name}", True)
else:
if hasattr(magnetdl, 'unset_flags'):
magnetdl.unset_flags(lt.torrent_flags.auto_managed)
magnetdl.pause()
consoleLog(f"Paused download: {status.name}", True)
idx = self.index(row, 0)
self.dataChanged.emit(idx, idx, [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole])
class HoverRowDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
opt = QtWidgets.QStyleOptionViewItem(option)
opt.state &= ~QtWidgets.QStyle.StateFlag.State_HasFocus
opt.state &= ~QtWidgets.QStyle.StateFlag.State_Selected
if index.row() == MainWindow._instance._hovered_row:
painter.save()
painter.fillRect(opt.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, opt, index)
class PauseResumeDelegate(QStyledItemDelegate):
clicked = Signal(int)
def paint(self, painter, option, index):
opt = QtWidgets.QStyleOptionViewItem(option)
opt.state &= ~QtWidgets.QStyle.StateFlag.State_HasFocus
opt.state &= ~QtWidgets.QStyle.StateFlag.State_Selected
if index.row() == MainWindow._instance._hovered_row:
painter.save()
painter.fillRect(opt.rect, _theme_colors()["hover"])
painter.restore()
super().paint(painter, opt, index)
def setEditorData(self, editor, index):
button = editor.findChild(QtWidgets.QPushButton)
magnet_link = list(state.active_downloads.keys())[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
if button:
if status.state == lt.torrent_status.seeding:
button.setIcon(svg_icon(SVG_FOLDER, 18))
button.setText("")
else:
is_user_paused = status.paused and not status.auto_managed
button.setIcon(svg_icon(SVG_PLAY if is_user_paused else SVG_PAUSE, 18))
button.setText("")
def createEditor(self, parent, option, index):
magnet_link = list(state.active_downloads.keys())[index.row()]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
widget = QWidget(parent)
widget.setStyleSheet("border: none; background: transparent;")
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
if status.state == lt.torrent_status.seeding:
btnPause = QtWidgets.QPushButton()
btnPause.setIcon(svg_icon(SVG_FOLDER, 18))
else:
btnPause = QtWidgets.QPushButton()
is_user_paused = status.paused and not status.auto_managed
btnPause.setIcon(svg_icon(SVG_PLAY if is_user_paused else SVG_PAUSE, 18))
btnPause.setIconSize(QSize(18, 18))
btnPause.setFixedSize(30, 30)
btnPause.setCursor(Qt.CursorShape.PointingHandCursor)
btnPause.setStyleSheet("QPushButton { border: none; background: transparent; padding: 0px; }")
btnPause.clicked.connect(lambda: self.clicked.emit(index.row()))
layout.addStretch()
layout.addWidget(btnPause)
layout.addStretch()
widget.setLayout(layout)
return widget
def editorEvent(self, event, model, option, index):
return False
# core.interface.dialogs.hoverrowdelegate
self.download_model = DownloadModel()
self.downloadList.setModel(self.download_model)
self.downloadList.horizontalHeader().setStretchLastSection(False)
self.downloadList.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
self.downloadList.horizontalHeader().resizeSection(0, 70)
self.downloadList.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
self.downloadList.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
self.downloadList.horizontalHeader().setMinimumSectionSize(60)
self.downloadList.verticalHeader().setDefaultSectionSize(40)
self.downloadList.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
self.downloadList.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
self.downloadList.verticalHeader().setVisible(False)
self.downloadList.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
self.downloadList.horizontalHeader().setHighlightSections(False)
self.downloadList.setMouseTracking(True)
self.downloadList.setShowGrid(False)
self.downloadList.setStyleSheet(_table_stylesheet("QTableView"))
self.downloadList.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.downloadList.viewport().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
download_model = self.download_model
def on_pause_resume_clicked(row):
download_model.toggle_pause_resume(row)
self.downloadList.viewport().setMouseTracking(True)
hover_delegate = HoverRowDelegate(self.downloadList)
self.downloadList.setItemDelegate(hover_delegate)
delegate = PauseResumeDelegate(self.downloadList)
self.downloadList.setItemDelegateForColumn(0, delegate)
delegate.clicked.connect(on_pause_resume_clicked)
self.downloadList = _create_download_list(self)
self.downloadList.viewport().installEventFilter(self)
self.dlbutton.clicked.connect(lambda: run_thread(threading.Thread(target=download_selected, args=(state.trackertable.selectedItems(),))))
@@ -587,35 +163,32 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
self.horizontal_layout.addWidget(self.emptyResults, stretch=3)
self.horizontal_layout.addWidget(state.trackertable)
# Tabs
self.tab1 = create_tab("Search", self.searchbar, state.trackertable, self.tabs, self.dlbutton, self.horizontal_layout)
self.tab3 = create_tab("Downloads", self.emptyDownload, self.downloadList, self.tabs, None, None)
if state.image_path is not None and os.path.exists(state.image_path):
self.image = QImage(state.image_path)
self.image = self.image.scaledToWidth(300, Qt.TransformationMode.SmoothTransformation)
self.pixmap = QPixmap.fromImage(self.image)
self.overlay_label = QLabel(self)
self.overlay_label.setPixmap(self.pixmap)
self.overlay_label.adjustSize()
self.overlay_label.raise_()
x = self.width() - self.overlay_label.width()
y = self.height() - self.overlay_label.height()
self.overlay_label.move(x, y)
self.tab2 = create_tab("Downloads", self.emptyDownload, self.downloadList, self.tabs, None, None)
# Corner Widget (Settings Button, Tracker list, Tab button container)
self.corner_widget = QWidget()
self.corner_layout = QHBoxLayout(self.corner_widget)
self.corner_layout.setContentsMargins(0, 0, 0, 0)
# Tracker list
self.tracker_list = QComboBox()
self.tracker_list.addItems(list(state.trackers.keys()))
self.tracker_list.setCursor(Qt.CursorShape.PointingHandCursor)
self.tracker_list.activated.connect(self.set_tracker)
self.corner_layout.addWidget(self.tracker_list)
# Settings button
self.settings_btn = QtWidgets.QToolButton()
self.settings_btn.setIconSize(QSize(21, 21))
self.settings_btn.setStyleSheet("background: transparent;")
self.settings_btn.setToolTip("Settings")
self.settings_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self.settings_btn.clicked.connect(lambda: settings_dialog(self))
self.corner_layout.addWidget(self.settings_btn)
# Adjust theme based on system preferences
if darkdetect.isDark():
settings_white_pixmap = QPixmap()
settings_white = base64.b64decode(settings_white_base64)
@@ -627,11 +200,6 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
settings_black_pixmap.loadFromData(settings_black)
self.settings_btn.setIcon(QIcon(settings_black_pixmap))
self.settings_btn.setToolTip("Settings")
self.settings_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self.settings_btn.clicked.connect(lambda: settings_dialog(self))
self.corner_layout.addWidget(self.settings_btn)
self.tab_wrapper = QWidget()
self.tab_layout = QVBoxLayout()
self.tab_layout.setContentsMargins(0, 0, 0, 0)
@@ -663,6 +231,7 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
self.version = QLabel(f"Version: {state.version}")
self.statusbar.addPermanentWidget(self.version, Qt.AlignmentFlag.AlignLeft)
# (\u2193) Arrow down, (\u2191) Arrow up
self.speed_label = QLabel("\u2193 0.0 kB/s \u2191 0.0 kB/s")
self.speed_label.setStyleSheet("padding-right: 6px;")
self.statusbar.addPermanentWidget(self.speed_label)
@@ -670,40 +239,15 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
self.setStatusBar(self.statusbar)
self.download_timer = QTimer()
self.download_timer.timeout.connect(self.download_list_update)
self.download_timer.timeout.connect(lambda: download_list_update(self))
self.download_timer.start(500)
self.active_timer = QTimer()
self.active_timer.timeout.connect(self.show_empty_downloads)
self.active_timer.start(500)
self.context_menu = QtWidgets.QMenu(self)
self.context_menu.addAction("Open Containing Folder", self.openFolderAction)
self.context_menu.addAction("Copy Magnet URI", self.copyMagnetURIAction)
self.context_menu.addAction("Remove from list", self.cancelDownloadAction)
self.context_menu.addAction("Delete File", self.deleteFileAction)
def _create_tracker_table(self):
table = QTableWidget()
table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
table.verticalHeader().setVisible(False)
table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
table.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
table.setShowGrid(False)
table.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
table.viewport().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
table.horizontalHeader().setHighlightSections(False)
table.horizontalHeader().setStretchLastSection(False)
table.setStyleSheet(_table_stylesheet("QTableWidget"))
table.setMouseTracking(True)
table.viewport().setMouseTracking(True)
table.viewport().installEventFilter(self)
table.setItemDelegateForColumn(0, self._tracker_elided_delegate)
self._apply_default_headers(table)
return table
self._context_menu = core.interface.dialogs.contextmenu.ContextMenu(self)
self.image_overlay = Image(self)
def _apply_default_headers(self, table):
tracker_name = state.currenttracker if hasattr(state, 'currenttracker') and state.currenttracker else None
@@ -804,52 +348,9 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
self.searchbar.setEnabled(True)
self.searchbar.setFocus()
def update_image_overlay(self, new_image_path):
self.image = QImage(new_image_path)
self.pixmap = QPixmap.fromImage(self.image)
self.overlay_label.setPixmap(self.pixmap)
self.overlay_label.adjustSize()
def download_list_update(self):
if not self.download_model:
self._update_speed_label()
return
row_count = self.download_model.rowCount()
col_count = self.download_model.columnCount()
if row_count > 0 and col_count > 0:
top_left = self.download_model.index(0, 0)
bottom_right = self.download_model.index(row_count - 1, col_count - 1)
if top_left.isValid() and bottom_right.isValid():
self.download_model.dataChanged.emit(top_left, bottom_right, [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole])
if row_count != self._last_dl_row_count:
old_count = self._last_dl_row_count
self._last_dl_row_count = row_count
if row_count > 0:
self.download_model.layoutAboutToBeChanged.emit()
self.download_model.layoutChanged.emit()
for row in range(row_count):
idx = self.download_model.index(row, 0)
if idx.isValid():
self.downloadList.closePersistentEditor(idx)
self.downloadList.openPersistentEditor(idx)
elif old_count > 0:
self.download_model.layoutAboutToBeChanged.emit()
self.download_model.layoutChanged.emit()
else:
if row_count > 0:
delegate = self.downloadList.itemDelegateForColumn(0)
for row in range(row_count):
idx = self.download_model.index(row, 0)
if idx.isValid():
editor = self.downloadList.indexWidget(idx)
if editor and delegate:
delegate.setEditorData(editor, idx)
self._update_speed_label()
def _update_speed_label(self):
total_down = 0
total_up = 0
@@ -861,8 +362,8 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
s = handle.status()
total_down += s.download_rate
total_up += s.upload_rate
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while updating speed label: {e}")
down_kb = total_down / 1024
up_kb = total_up / 1024
down_text = f"{down_kb / 1024:.1f} MB/s" if down_kb > 1024 else f"{down_kb:.1f} kB/s"
@@ -886,43 +387,6 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
from core.utils.general.shutdown import force_exit
force_exit()
def eventFilter(self, obj, event):
try:
if hasattr(self, 'speed_label') and obj == self.speed_label:
if event.type() == QEvent.Type.MouseButtonRelease:
settings_dialog(self)
return True
if obj == state.trackertable.viewport():
if event.type() == QEvent.Type.MouseMove:
pos = event.position().toPoint() if hasattr(event, 'position') else event.pos()
idx = state.trackertable.indexAt(pos)
new_row = idx.row() if idx.isValid() else -1
if new_row != self._tracker_hovered_row or state.trackertable is not self._tracker_hovered_table:
self._tracker_hovered_row = new_row
self._tracker_hovered_table = state.trackertable
state.trackertable.viewport().update()
elif event.type() == QEvent.Type.Leave:
self._tracker_hovered_row = -1
self._tracker_hovered_table = None
state.trackertable.viewport().update()
if obj == self.downloadList.viewport():
if event.type() == QEvent.Type.MouseMove:
pos = event.position().toPoint() if hasattr(event, 'position') else event.pos()
idx = self.downloadList.indexAt(pos)
new_row = idx.row() if idx.isValid() else -1
if new_row != self._hovered_row:
old_row = self._hovered_row
self._hovered_row = new_row
self._invalidate_hover_row(old_row)
self._invalidate_hover_row(new_row)
elif event.type() == QEvent.Type.Leave:
old_row = self._hovered_row
self._hovered_row = -1
self._invalidate_hover_row(old_row)
except (RuntimeError, AttributeError):
pass
return super().eventFilter(obj, event)
def _invalidate_hover_row(self, row):
if row >= 0 and self.download_model:
self.downloadList.viewport().update()
@@ -948,106 +412,3 @@ class MainWindow(QtWidgets.QMainWindow, QWidget):
else:
self.emptyDownload.show()
self.downloadList.hide()
def contextMenuEvent(self, event: QContextMenuEvent):
if self.downloadList.underMouse():
pos = self.downloadList.viewport().mapFromGlobal(event.globalPos())
index = self.downloadList.indexAt(pos)
if index.isValid():
row = index.row()
self._context_menu_row = row
self.context_menu.exec(event.globalPos())
else:
super().contextMenuEvent(event)
def openFolderAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
download_path = magnetdl.save_path()
if download_path and os.path.exists(download_path):
if platform.system() == "Windows":
os.startfile(os.path.normpath(download_path))
elif platform.system() == "Linux":
subprocess.Popen(["xdg-open", download_path])
elif platform.system() == "Darwin":
subprocess.Popen(["open", download_path])
def copyMagnetURIAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(magnet_link)
def cancelDownloadAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
confirm = QMessageBox.question(self, "Cancel Download", f"Are you sure you want to cancel the download of '{magnetdl.status().name}'?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
if confirm == QMessageBox.StandardButton.Yes:
if hasattr(magnetdl, 'stop'):
magnetdl.stop()
elif state.dl_session:
try:
state.dl_session.remove_torrent(magnetdl)
except Exception:
pass
del state.active_downloads[magnet_link]
remove_download_log(magnet_link)
try:
consoleLog(f"Cancelled download: {magnetdl.status().name}", True)
except RuntimeError:
consoleLog(f"Cancelled download")
def deleteFileAction(self):
if not hasattr(self, '_context_menu_row'):
return
row = self._context_menu_row
if row < 0 or row >= len(state.active_downloads):
return
magnet_link = list(state.active_downloads.keys())[row]
magnetdl = state.active_downloads[magnet_link]
status = magnetdl.status()
save_path = status.save_path
torrent_name = status.name
download_path = os.path.join(save_path, torrent_name)
confirm = QMessageBox.question(self, "Delete Files", f"Are you sure you want to delete the downloaded files of '{magnetdl.status().name}'? This action cannot be undone.", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
if confirm == QMessageBox.StandardButton.Yes:
if hasattr(magnetdl, 'stop'):
magnetdl.stop()
elif state.dl_session:
try:
state.dl_session.remove_torrent(magnetdl)
except Exception:
pass
if download_path and os.path.exists(download_path):
try:
if os.path.isfile(download_path):
remove_download_log(magnet_link)
os.remove(download_path)
del state.active_downloads[magnet_link]
consoleLog(f"Deleted files for: {magnetdl.status().name}", True)
else:
import shutil
remove_download_log(magnet_link)
shutil.rmtree(download_path)
del state.active_downloads[magnet_link]
consoleLog(f"Deleted files for: {magnetdl.status().name}", True)
except Exception as e:
consoleLog(f"Error deleting files: {e}", True)
else:
del state.active_downloads[magnet_link]
remove_download_log(magnet_link)
consoleLog(f"Removed entry (files not found): {magnetdl.status().name}", True)
+2 -3
View File
@@ -1,9 +1,8 @@
from PySide6.QtWidgets import QTableWidgetItem, QHeaderView
from core.utils.logging.logs import consoleLog
from core.data.scrapers.rutracker import init_rutracker
from core.data.scrapers.uztracker import init_uztracker
from core.data.scrapers.monkrus import init_m0nkrus
from core.data.scrapers.steamrip import init_steamrip
from core.data.scrapers.monkrus import init_m0nkrus
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
init_rutracker()
+2 -2
View File
@@ -9,7 +9,7 @@ from .utils import (
detect_filename_from_headers,
)
def add_direct_download(url: str, title: str, dl_path: Optional[str] = None):
def add_direct_download(url: str, title: str, dl_path: Optional[str] = None, headers: Optional[dict] = None, single_threaded: bool = False):
if dl_path is None:
dl_path = state.download_path
@@ -24,7 +24,7 @@ def add_direct_download(url: str, title: str, dl_path: Optional[str] = None):
or sanitize_filename(title) + ".zip"
)
handle = DirectDownloadHandle(url, filename, dl_path)
handle = DirectDownloadHandle(url, filename, dl_path, headers, single_threaded)
state.active_downloads[url] = handle
add_download_log(title, url, "", False)
handle.start()
+21 -17
View File
@@ -1,17 +1,17 @@
import os
import threading
import requests
import json
import hashlib
import time
from core.utils.logging.logs import consoleLog, update_download_completed
from concurrent.futures import ThreadPoolExecutor, as_completed
from .status import DirectDownloadStatus, ChunkSpec
from core.utils.data.state import state
from .utils import format_size
from typing import Optional
import libtorrent as lt
import threading
import requests
import hashlib
import json
import time
import os
from core.utils.logging.logs import consoleLog, update_download_completed
from core.utils.data.state import state
from .status import DirectDownloadStatus, ChunkSpec
from .utils import format_size
class SimpleThrottler:
def __init__(self):
@@ -58,7 +58,7 @@ class DirectDownloadHandle:
"Chrome/125.0.0.0 Safari/537.36"
)
def __init__(self, url: str, name: str, save_path: str):
def __init__(self, url: str, name: str, save_path: str, headers: Optional[dict] = None, single_threaded: bool = False):
self.url = url
self._name = name
self._save_path = save_path
@@ -69,6 +69,8 @@ class DirectDownloadHandle:
self._thread: Optional[threading.Thread] = None
self._session: Optional[requests.Session] = None
self._supports_range = False
self._custom_headers = headers
self._single_threaded = single_threaded
state_dir = os.path.join(state.settings_path, "direct_downloads")
os.makedirs(state_dir, exist_ok=True)
@@ -132,14 +134,14 @@ class DirectDownloadHandle:
"chunks": chunks_done
}, f)
except Exception as e:
pass
consoleLog(f"Exception while saving download state: {e}")
def _clear_state(self):
if os.path.exists(self._state_file):
try:
os.remove(self._state_file)
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while removing download state file: {e}")
def start(self):
@@ -151,6 +153,8 @@ class DirectDownloadHandle:
def _build_session(self) -> requests.Session:
session = requests.Session()
session.headers.update({"User-Agent": self.USER_AGENT})
if self._custom_headers is not None:
session.headers.update(self._custom_headers)
adapter = requests.adapters.HTTPAdapter(
max_retries=0,
pool_connections=self.NUM_THREADS,
@@ -194,6 +198,7 @@ class DirectDownloadHandle:
use_multithreaded = (
self._supports_range
and total_size > self.MIN_CHUNK_SIZE * 2
and not self._single_threaded
)
if use_multithreaded:
@@ -204,7 +209,7 @@ class DirectDownloadHandle:
self._preallocate_file(total_size)
self._multithreaded_download(total_size)
else:
reason = "no range support" if not self._supports_range else "file too small"
reason = "no range support" if not self._supports_range else "file too small or single-threaded mode"
consoleLog(f"Single-threaded download ({reason}): {self._name}")
self._single_threaded_download()
@@ -439,5 +444,4 @@ class DirectDownloadHandle:
raise RuntimeError(
f"Size mismatch: expected {format_size(expected_size)}, "
f"got {format_size(actual_size)}"
)
)
+2 -2
View File
@@ -1,8 +1,8 @@
import threading
import time
from dataclasses import dataclass
from typing import Optional
import libtorrent as lt
import threading
import time
@dataclass
+6 -5
View File
@@ -1,7 +1,8 @@
import os
import requests
from typing import Optional
from core.utils.logging.logs import consoleLog
from urllib.parse import urlparse, unquote
from typing import Optional
import requests
import os
def sanitize_filename(name: str) -> str:
# Remove or replace dangerous characters
@@ -36,8 +37,8 @@ def detect_filename_from_headers(url: str, user_agent: str) -> Optional[str]:
fname = parts[-1].strip().strip('"').strip("'")
if fname:
return fname
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while retrieving filename from headers: {e}")
return None
def format_size(size_bytes: int) -> str:
+2
View File
@@ -29,6 +29,7 @@ def get_active_interfaces():
def list_interfaces() -> None:
consoleLog("Fetching Network Interfaces...")
addrs = psutil.net_if_addrs()
stats = psutil.net_if_stats()
@@ -45,6 +46,7 @@ def list_interfaces() -> None:
consoleLog(f"Found Interface: {interface} [{status}]")
def init_interfaces():
consoleLog("Initializing Interface variables...")
addrs = psutil.net_if_addrs()
state.interfaces = list(addrs.keys())
state.active_interfaces = get_active_interfaces()
+8 -10
View File
@@ -1,16 +1,15 @@
import time
import os
from core.network.interface import get_interface_ip
from core.utils.general.wrappers import run_thread
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
import libtorrent as lt
import threading
import platform
import ctypes
from core.utils.general.wrappers import run_thread
from core.network.interface import get_interface_ip
import threading
import libtorrent as lt
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
import time
import os
global loop_running
loop_running = False
def get_free_space_mb(dirname):
@@ -103,7 +102,6 @@ def add_download(magnet_uri):
magnetdl.save_path = state.download_path
download = state.dl_session.add_torrent(magnetdl)
else:
download = None
state.dl_session.remove_torrent(handle)
consoleLog("Not enough free space to download this item.")
return False
+8 -8
View File
@@ -1,10 +1,10 @@
from core.utils.data.state import state
from core.utils.logging.logs import update_download_completed_by_hash
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from plyer import notification
import libtorrent as lt
import os
import time
import os
def cleanup_session():
@@ -37,8 +37,8 @@ def send_notification(shutdown_event):
timeout=4
)
notified.add(magnet_uri)
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while sending notification: {e}")
time.sleep(5)
def update_log(shutdown_event):
@@ -59,8 +59,8 @@ def update_log(shutdown_event):
info_hash = str(status.info_hash)
update_download_completed_by_hash(info_hash, True)
updated.add(magnet_uri)
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while updating log file: {e}")
time.sleep(5)
def check_deleted_files(shutdown_event):
@@ -79,6 +79,6 @@ def check_deleted_files(shutdown_event):
consoleLog(f"Registered File Deletion: {status.name}")
state.dl_session.remove_torrent(magnetdl)
del state.active_downloads[magnet_uri]
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while checking for file deletions: {e}")
time.sleep(5)
+2 -1
View File
@@ -1,5 +1,6 @@
from core.utils.logging.logs import consoleLog
from core.network.libtorrent_int import add_download
from core.utils.logging.logs import consoleLog
def add_magnet(uri):
if uri is not None and uri.startswith("magnet:?"):
+1 -1
View File
@@ -1,6 +1,6 @@
from core.network.libtorrent_int import update_settings
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from .config import create_config
+1 -1
View File
@@ -1,8 +1,8 @@
import threading
from PySide6.QtCore import QObject, Signal
from PySide6.QtWidgets import QTableWidget
from typing import Any, List, Dict
from pathlib import Path
import threading
class AppState(QObject):
image_changed = Signal(str)
+3 -2
View File
@@ -1,6 +1,6 @@
import requests
from bs4 import BeautifulSoup
from core.utils.logging.logs import consoleLog
from bs4 import BeautifulSoup
import requests
def get_magnet_link(post_url):
@@ -15,6 +15,7 @@ def get_magnet_link(post_url):
return magnet_link['href']
else:
consoleLog("Magnet Link not Found!")
return None
except requests.RequestException as e:
consoleLog(f"Failed to fetch {post_url}: {e}")
return None
+4 -3
View File
@@ -1,13 +1,14 @@
from core.network.libtorrent_misc import cleanup_session
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
import os
def closehelper():
state.shutdown_event.set()
try:
from core.network.libtorrent_misc import cleanup_session
cleanup_session()
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while cleaning up LibTorrent Session: {e}")
def force_exit():
os._exit(0)
+8 -1
View File
@@ -1,2 +1,9 @@
from core.utils.logging.logs import consoleLog
def run_thread(thread):
thread.start()
target_name = thread._target.__name__
try:
thread.start()
consoleLog(f"Started Thread: {target_name}")
except Exception as e:
consoleLog(f"Exception while starting thread {target_name}: {e}")
+3 -4
View File
@@ -1,5 +1,5 @@
from core.utils.logging.logs import consoleLog, remove_download_log
from core.utils.network.download import run_download_direct, seed_magnet
from core.utils.logging.logs import consoleLog, remove_download_log
import os
def split_data(data):
@@ -14,13 +14,12 @@ def check_completed(downloads, resume):
if download.completed == False:
consoleLog(f"Found unfinished download: {download.title}")
if resume == True:
dl_dir = os.path.dirname(download.path)
if download.magnet_uri:
run_download_direct(download.magnet_uri, dl_dir, download.title)
run_download_direct(download.magnet_uri, download.title)
consoleLog(f"Resuming Magnet: {download.title}")
elif download.url:
from core.network.direct_download import add_direct_download
add_direct_download(download.url, download.title, dl_dir)
add_direct_download(download.url, download.title)
consoleLog(f"Resuming Direct Download: {download.title}")
def check_downloads(downloads):
+4 -4
View File
@@ -3,10 +3,10 @@ from core.utils.data.state import state
from dataclasses import asdict
from datetime import datetime
import json
import time
import os
import re
import time
import threading
def add_download_log(title, url, magnet_uri, completed) -> DownloadList:
# wait for metadata outside the lock to avoid blocking other threads
@@ -247,8 +247,8 @@ def flush_log_buffer(): # credits to claude
for log_entry in state.log_buffer:
MainWindow.add_log(log_entry)
state.log_buffer = []
except Exception:
pass
except Exception as e:
consoleLog(f"Exception while flushing log buffer: {e}")
def consoleLog(text, printAnyways = False):
now = datetime.now()
+16 -13
View File
@@ -1,17 +1,17 @@
from PySide6.QtWidgets import QTableWidgetItem
from PySide6.QtCore import Qt
from core.utils.logging.logs import consoleLog
from core.network.libtorrent_wrapper import add_magnet
from core.utils.general.wrappers import run_thread
from core.utils.logging.logs import add_download_log
from core.network.libtorrent_int import add_seed
from core.utils.data.state import state
from core.network.direct_download import add_direct_download
from core.network.libtorrent_wrapper import add_magnet
from core.utils.logging.logs import add_download_log
from core.utils.general.wrappers import run_thread
from core.network.libtorrent_int import add_seed
from PySide6.QtWidgets import QTableWidgetItem
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from PySide6.QtCore import Qt
from typing import Optional
import threading
def download_selected(items: list[QTableWidgetItem]):
if not items:
consoleLog("No item selected for download.")
@@ -30,18 +30,21 @@ def download_selected(items: list[QTableWidgetItem]):
consoleLog(f"Downloading {post.get('title', 'Unknown')}")
run_thread(threading.Thread(target=run_download, args=(post,)))
def run_download(post):
def run_download(post, headers: Optional[dict] = None):
linkfunc = state.trackers[state.currenttracker]["linkFunc"]
ismagnet = state.trackers[state.currenttracker]["isMagnet"]
link = linkfunc(post)
result = linkfunc(post)
if ismagnet:
link = result
add_magnet(link)
add_download_log(post.get("title", "Unknown"), "", link, False)
else:
add_direct_download(link, post.get("title", "Unknown"))
link, link_headers = result if isinstance(result, tuple) else (result, None)
final_headers = headers or link_headers
add_direct_download(link, post.get("title", "Unknown"), headers=final_headers, single_threaded=final_headers is not None)
def run_download_direct(magnet_uri, dl_path=None, title="Direct Download"):
def run_download_direct(magnet_uri, title="Direct Download"):
consoleLog(f"Magnet: {title}")
add_magnet(magnet_uri)
add_download_log(title, "", magnet_uri, False)
+9 -8
View File
@@ -1,19 +1,20 @@
import requests
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
import requests
def get_updates():
url = f"https://api.github.com/repos/KeksPirates/SoftwareManager/releases/latest"
try:
response = requests.get(url, timeout=15)
except requests.RequestException as e:
consoleLog(f"Failed to fetch releases: {e}")
return None
return None, None
if response.status_code != 200:
consoleLog(f"Failed to fetch releases: {response.status_code}")
return None
return None, None
release = response.json()
@@ -33,9 +34,9 @@ def get_updates():
url=asset['browser_download_url'],
hash=asset.get('digest')
))
return release_assets
return release_assets, latest_version
else:
return None
return None, None
else:
consoleLog("Already up-to-date.")
return None
return None, None
+96
View File
@@ -0,0 +1,96 @@
from core.network.direct_download.handle import DirectDownloadHandle
from core.utils.logging.logs import consoleLog
from core.utils.data.state import state
from PySide6.QtCore import Qt
from PySide6 import QtWidgets
import libtorrent as lt
import subprocess
import tempfile
import hashlib
import time
import sys
import os
def _verify_hash(file_path: str, expected_hash: str) -> bool:
sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
return f"sha256:{sha256.hexdigest()}" == expected_hash
def download_update(assets: list):
filename = None
setup_hash = None
url = None
for asset in assets:
if "-windows-setup.exe" in asset["name"]:
filename = asset["name"]
setup_hash = asset["hash"]
url = asset["url"]
break
if not filename:
consoleLog("Error: No Windows installer found in release assets")
return
installer_path = os.path.join(tempfile.gettempdir(), filename)
progress = QtWidgets.QProgressDialog("Downloading update... (0.0 MB/s)", None, 0, 100)
progress.setWindowTitle("Updating")
progress.setWindowModality(Qt.WindowModality.ApplicationModal)
progress.setCancelButton(None)
progress.setMinimumDuration(0)
progress.setAutoClose(False)
progress.setAutoReset(False)
progress.setValue(0)
progress.show()
QtWidgets.QApplication.processEvents()
original_limit = state.down_speed_limit
state.down_speed_limit = 0
handle = DirectDownloadHandle(url, filename, tempfile.gettempdir())
handle.start()
while True:
QtWidgets.QApplication.processEvents()
status = handle.status()
if status.error:
state.down_speed_limit = original_limit
progress.close()
consoleLog(f"Update download failed: {status.error}")
return
if status.total_wanted > 0:
pct = int(status.total_wanted_done * 100 / status.total_wanted)
speed_mb = status.download_rate / (1024 * 1024)
progress.setValue(pct)
progress.setLabelText(f"Downloading update... ({speed_mb:.1f} MB/s)")
if status.state == lt.torrent_status.seeding:
break
time.sleep(0.1)
state.down_speed_limit = original_limit
if setup_hash:
if _verify_hash(installer_path, setup_hash):
consoleLog(f"Successfully validated installer hash ({setup_hash})")
else:
progress.close()
consoleLog("Error: Invalid file hash, file may be corrupted")
sys.exit(0)
else:
consoleLog("Skipping hash verification (no hash found for release)")
progress.setLabelText("Installing update...")
progress.setValue(100)
QtWidgets.QApplication.processEvents()
subprocess.Popen([installer_path, "/VERYSILENT", "/SUPPRESSMSGBOXES", "/SP-", "/CLOSEAPPLICATIONS"])
time.sleep(1)
sys.exit(0)
+20 -17
View File
@@ -1,65 +1,68 @@
from core.interface.gui import MainWindow
from core.utils.data.state import state
from core.utils.logging.logs import consoleLog
from core.network.libtorrent_misc import send_notification, update_log, check_deleted_files
from core.utils.logging.logs import get_download_logs
from core.utils.general.shutdown import closehelper
from core.utils.general.wrappers import run_thread
from core.utils.logging.loghandler import split_data, check_completed, check_downloads
from core.network.interface import list_interfaces, init_interfaces
from core.utils.logging.logs import get_download_logs
from core.utils.logging.logs import set_main_window
from core.utils.general.shutdown import closehelper
from core.utils.general.wrappers import run_thread
from core.utils.general.shutdown import force_exit
from core.utils.config.config import read_config
from core.utils.logging.logs import consoleLog
from core.interface.gui import MainWindow
from core.utils.data.state import state
from PySide6 import QtWidgets
from PySide6.QtCore import Qt
import qdarktheme
import threading
import platform
import signal
import sys
import time
import sys
def run_gui():
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication(sys.argv)
qdarktheme.setup_theme("auto")
widget = MainWindow()
# Check OS for window transparency compatibility and apply
if state.window_transparency and platform.system() != "Windows":
widget.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
qdarktheme.setup_theme("auto", custom_colors={"background": "#00000000"})
from core.utils.logging.logs import set_main_window
set_main_window(widget)
widget.show()
sys.exit(app.exec())
def keyboardinterrupthandler(signum, frame):
closehelper()
from core.utils.general.shutdown import force_exit
force_exit()
def main():
# Begin counting startup time
start_time = time.perf_counter()
# Parse saved files
read_config()
logs = get_download_logs()
_, downloads = split_data(logs)
# Initialize Keyboardinterrupt signal
signal.signal(signal.SIGINT, keyboardinterrupthandler)
consoleLog("Starting SoftwareManager...")
consoleLog("Fetching Network Interfaces...")
# Get network interface info
list_interfaces()
consoleLog("Initializing Interface variables...")
init_interfaces()
consoleLog(f"Current Bound: {state.bound_interface}")
# Start background daemon threads
run_thread(threading.Thread(target=send_notification, args=(state.shutdown_event,), daemon=True))
consoleLog("Started Thread: send_notification")
run_thread(threading.Thread(target=update_log, args=(state.shutdown_event,), daemon=True))
consoleLog("Started Thread: update_log")
run_thread(threading.Thread(target=check_completed, args=(downloads, state.autoresume)))
consoleLog("Started Thread: check_completed")
run_thread(threading.Thread(target=check_deleted_files, args=(state.shutdown_event,), daemon=True))
consoleLog("Started Thread: check_deleted_files")
# Start background non-daemon threads
run_thread(threading.Thread(target=check_completed, args=(downloads, state.autoresume)))
run_thread(threading.Thread(target=check_downloads, args=(downloads,)))
consoleLog("Started Thread: check_downloads")
# Finish counting startup time
elapsed = time.perf_counter() - start_time
consoleLog(f"Initialization completed in {elapsed:.2f}s. Launching GUI")
# Launch GUI
run_gui()
if __name__ == "__main__":