v4.9.0 - Refactor (#41)
* fix imports
remove unused imports
use full import path
sort import (1. Standard Library, 2. Third-Party, 3. Local) in alphabetic.
* - remove: Method 3 from src.core.ytsage_downlader:cleanup_subtitle_file
- it could delete the subtitle file of other movies if it present in same directory as it scane recursively.
- refactor: migrate from os.path to pathlib.Path for path handling
- Replaced os.path methods with pathlib.Path to improve readability,
- avoid repeatation.
- cross-platform compatibility, and maintain cleaner code.
- improve: enhance code readability
- Standardized string literals to use double quotes for consistency
- Removed unnecessary spaces to maintain cleaner formatting
- Applied code formatting for better readability and maintainability
* - add: ytsage_constants.py file for one place to store all constants.
- imporve: return type hint for function.
- remove: src/gui/ytsage_gui_dialogs.py file to avoid repetation
- src/gui/dialogs is renamed to src/gui/ytsage_gui_dialogs for same naming convection. (future import will remains same)
- use of src/gui/ytsage_gui_dialogs/__init__.py to import the dilogs modules.
- change: variable self.parent to self._parent so it does not overwrite the parent()
- add type hint checking.
* - refactor: QMetaObject.invokeMethod to Signal
- I encounter error with incokeMethod. Could not solve it.
- So, Changed it to Signal to match app code language.
- implement: the ytsage_constants.py to code
- remove: unnecessary logic
- remove: repetitive code logic.
- update: yt-dlp logic for src\gui\ytsage_gui_dialogs\ytsage_dialogs_update:_update_binary
- yt-dlp update logic will use `yt-dlp -U`
* refactor: remove unused imports and streamline code formatting across multiple files
* - **refactor: drop `pygame` in favor of built-in `PySide6` sound**
- Removed `pygame` dependency (too heavy just for notifications).
- Replaced with `QSoundEffect`, which is lightweight and built into `PySide6`.
- Dropped `pygame.mixer` + threading → Qt handles async playback.
- Implemented sound playback with `QUrl.fromLocalFile()` and `.play()`.
- Added `setVolume(0.9)` as a configurable example.
- Converted notification sound from `.mp3` to `.wav` (only format supported).
* **refactor(utils): simplify logger module**
- Moved `logger` to `src.utils`
- Removed unnecessary import checks (logger is always available)
- Replaced `raise` statements with error logging to prevent crashes
- Use `logger.exception()` in `except` blocks to capture traceback (logged as error)
**style: remove redundant str() in f-strings**
- Dropped explicit `str()` calls inside f-strings
- f-strings already call `str()` under the hood
**chore: add type hints for GUI mixins**
- Added type hints for `FormatTableMixin` (`src.gui.ytsage_gui_format_table`)
- Added type hints for `VideoInfoMixin` (`src.gui.ytsage_gui_video_info`)
- Improves autocomplete and type safety in IDEs
* - **introduce the `ytsage_config_manager.py` module to manage app setting.**
- Loads settings from a JSON config file (`APP_CONFIG_FILE`).
- Creates the config file with default values if missing or corrupt.
- Retrieves, sets, and deletes settings using simple dot-separated keys.
- Provides safe error handling with logging instead of raising exceptions.
- Persists updates back to disk automatically.
- **Usage**
```python
from src.utils.ytsage_config_manager import ConfigManager
download_path = ConfigManager.get("download_path")
ConfigManager.set("download_path", "D:/Downloads")
last_check = ConfigManager.get("cached_versions.ytdlp.last_check")
ConfigManager.delete("cached_versions.ffmpeg.path")
```
* **Refactore: pkg_resources with importlib.metadata.version**
- UserWarning: pkg_resources is deprecated as an API.
- See https://setuptools.pypa.io/en/latest/pkg_resources.html.
- The pkg_resources package is slated for removal as early as 2025-11-30.
* **refactore: notification sound**
- `QSoundEffect` is chnaged back to `pyglet` as per mainter `@oop7` choise.
- simplify the logic.
* remove: import check, it should always work.
* **fix: runtime error**
- yt_dlp moved from `--excludes` to `--packages` in `build-windows.yml`
- In frozen build, logger will not log to consol. insted will log to file.
- In frozen build, `app_dir` is next to `.exe` file.
* chang back to checking import for ytdlp
* Bump version to 4.8.1
Update version references from 4.8.0b to 4.8.1 in __init__.py, main app, and About dialog to reflect the new release.
* Update asset paths in build workflows
Changed asset inclusion and screenshot removal paths from 'assets' to 'lib/assets' in Linux, macOS, and Windows build workflows to reflect new directory structure and ensure screenshots are excluded from packaged builds.
* Bump version to 4.8.2
Update version references from 4.8.1 to 4.8.2 in source files and documentation to prepare for a new patch release.
* Fix asset include path in Windows build workflow
Corrects the syntax for including asset files in the build-windows.yml workflow by changing 'assets,lib/assets' to 'assets=lib/assets'. This ensures assets are properly mapped during the build process.
* Update release tag examples in CI/CD README
Changed the example git tag commands from v4.8.0 and v4.8.2 to v4.8.1 for consistency in the CI/CD documentation.
* Fix include-files mapping in Windows build workflow
Changed the cx_Freeze --include-files argument from '=' to ':' for source:destination mapping in build-windows.yml. This resolves an issue where '=' was treated as a literal path, ensuring assets are correctly copied to the destination directory.
* Remove redundant comments in build-windows workflow
Deleted comments explaining the colon usage for source:destination mapping in the cx_Freeze CLI, as the mapping is already clear from the context.
* Refactor Windows build to use cx_Freeze setup script
Replaces direct cx_Freeze CLI calls with dynamically generated setup scripts for both standard and FFmpeg builds. This improves maintainability and flexibility of build configuration in the GitHub Actions workflow.
* Bump version to 4.8.3
Updated version references from 4.8.2 to 4.8.3 in __init__.py, main app, and About dialog to reflect the new release.
* revert(build): move yt_dlp from --packages to --excludes in build-windows.yml
---------
Co-authored-by: Your Name <mohamed.mohamed112@ai.mnu.edu.eg>
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
Config Manager Module
|
||||
=====================
|
||||
|
||||
This module provides **thread-safe** centralized management for application
|
||||
configuration in YTSage. It handles reading, writing, and managing settings
|
||||
stored in a JSON file, with support for nested keys via dot notation.
|
||||
|
||||
Thread safety is ensured using a reentrant lock (`RLock`), so multiple threads
|
||||
can safely access or modify settings concurrently.
|
||||
|
||||
Features
|
||||
--------
|
||||
- Thread-safe operations for getting, setting, and deleting configuration values.
|
||||
- Loads settings from a JSON config file (`APP_CONFIG_FILE`).
|
||||
- Creates the config file with default values if missing or corrupt.
|
||||
- Retrieves, sets, and deletes settings using dot-separated keys.
|
||||
- Provides safe error handling with logging instead of raising exceptions.
|
||||
- Persists updates back to disk automatically.
|
||||
|
||||
Usage
|
||||
-----
|
||||
from src.utils.ytsage_config_manager import ConfigManager
|
||||
|
||||
# Load settings (auto-loads if not already loaded)
|
||||
download_path = ConfigManager.get("download_path")
|
||||
|
||||
# Update a value
|
||||
ConfigManager.set("download_path", "D:/Downloads")
|
||||
|
||||
# Retrieve nested value
|
||||
last_check = ConfigManager.get("cached_versions.ytdlp.last_check")
|
||||
|
||||
# Delete a key
|
||||
ConfigManager.delete("cached_versions.ffmpeg.path")
|
||||
|
||||
Design Notes
|
||||
------------
|
||||
- Settings are stored in `ConfigManager.settings` (a dict).
|
||||
- Default values are defined in `ConfigManager.default_config`.
|
||||
- All modifications trigger a save (`_save`) to keep JSON in sync.
|
||||
- Logs actions and errors using the app's central logger.
|
||||
- Uses `RLock` to allow safe concurrent access from multiple threads.
|
||||
|
||||
Exceptions
|
||||
----------
|
||||
- Any issues during file I/O (permissions, disk errors, JSON corruption)
|
||||
are caught and logged. The application continues running with defaults
|
||||
when possible.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from src.utils.ytsage_constants import APP_CONFIG_FILE, USER_HOME_DIR
|
||||
from src.utils.ytsage_logger import logger
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
"""
|
||||
Thread-safe configuration manager for YTSage.
|
||||
|
||||
Provides methods to load, save, get, set, and delete settings stored in a JSON file.
|
||||
Supports nested keys via dot notation and automatically persists changes.
|
||||
"""
|
||||
|
||||
_lock = threading.RLock()
|
||||
_config_file = APP_CONFIG_FILE
|
||||
_settings: dict[str, Any] = {}
|
||||
_default_config = {
|
||||
"download_path": str(USER_HOME_DIR / "Downloads"),
|
||||
"speed_limit_value": None,
|
||||
"speed_limit_unit_index": 0,
|
||||
"cookie_file_path": None,
|
||||
"last_used_cookie_file": None,
|
||||
"auto_update_ytdlp": True,
|
||||
"auto_update_frequency": "daily",
|
||||
"last_update_check": 0,
|
||||
"cached_versions": {
|
||||
"ytdlp": {"version": None, "path": None, "last_check": 0, "path_mtime": 0},
|
||||
"ffmpeg": {"version": None, "path": None, "last_check": 0, "path_mtime": 0},
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _load(cls) -> None:
|
||||
"""
|
||||
Loads configuration settings from a JSON file if it exists and is valid.
|
||||
If the file is missing or corrupt, loads default settings and creates or overwrites the config file as needed.
|
||||
Logs actions and errors during the process.
|
||||
"""
|
||||
with cls._lock:
|
||||
if cls._config_file.exists():
|
||||
try:
|
||||
with open(cls._config_file, "r", encoding="utf-8") as f:
|
||||
cls._settings = json.load(f)
|
||||
logger.info("Config loaded from file.")
|
||||
except json.JSONDecodeError:
|
||||
cls._settings = cls._default_config.copy()
|
||||
logger.warning("Config file corrupt, loaded defaults.")
|
||||
else:
|
||||
cls._settings = cls._default_config.copy()
|
||||
cls._save()
|
||||
logger.info("Config file not found, created default config.")
|
||||
|
||||
@classmethod
|
||||
def _save(cls) -> None:
|
||||
"""
|
||||
Save current settings to JSON file.
|
||||
|
||||
Note:
|
||||
May raise exceptions if the file cannot be written due to permission issues,
|
||||
disk errors, or other I/O problems.
|
||||
"""
|
||||
with cls._lock:
|
||||
try:
|
||||
with open(cls._config_file, "w", encoding="utf-8") as f:
|
||||
json.dump(cls._settings, f, indent=4)
|
||||
logger.debug("Config saved to file.")
|
||||
except (OSError, PermissionError) as e:
|
||||
logger.exception(f"Failed to save config: {e}")
|
||||
except Exception as e:
|
||||
logger.exception(f"Unexpected error while saving config: {e}")
|
||||
|
||||
@classmethod
|
||||
def get(cls, key: str) -> Any:
|
||||
"""
|
||||
Retrieve a configuration value using a dotted key notation.
|
||||
Args:
|
||||
key (str): The dotted key string representing the path to the desired setting (e.g., "database.host").
|
||||
Any: The value associated with the given key, or None if the key does not exist.
|
||||
Notes:
|
||||
- If the configuration settings are not loaded, this method will load them before attempting retrieval.
|
||||
- If any part of the dotted key path is missing, None is returned and a debug message is logged.
|
||||
"""
|
||||
with cls._lock:
|
||||
if not cls._settings:
|
||||
cls._load()
|
||||
parts = key.split(".")
|
||||
value = cls._settings
|
||||
for part in parts:
|
||||
if isinstance(value, dict) and part in value:
|
||||
value = value[part]
|
||||
else:
|
||||
logger.debug(f"Config key '{key}' not found.")
|
||||
return None
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def set(cls, key: str, value: Any) -> None:
|
||||
"""
|
||||
Sets a configuration value for a given key.
|
||||
If the configuration settings are not loaded, loads them first.
|
||||
Supports nested keys using dot notation (e.g., "database.host").
|
||||
Updates the configuration dictionary with the provided value,
|
||||
saves the updated settings, and logs the change.
|
||||
Args:
|
||||
key (str): The configuration key, possibly nested using dots.
|
||||
value (Any): The value to set for the specified key.
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
with cls._lock:
|
||||
if not cls._settings:
|
||||
cls._load()
|
||||
parts = key.split(".")
|
||||
d = cls._settings
|
||||
for part in parts[:-1]:
|
||||
d = d.setdefault(part, {})
|
||||
d[parts[-1]] = value
|
||||
cls._save()
|
||||
logger.info(f"Config key '{key}' set to '{value}'.")
|
||||
|
||||
@classmethod
|
||||
def delete(cls, key: str) -> None:
|
||||
"""
|
||||
Deletes a configuration key from the settings.
|
||||
If the key is nested (dot-separated), traverses the settings dictionary accordingly.
|
||||
If the key exists, removes it and saves the updated settings.
|
||||
Logs the deletion or if the key was not found.
|
||||
Args:
|
||||
key (str): The dot-separated configuration key to delete.
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
with cls._lock:
|
||||
if not cls._settings:
|
||||
cls._load()
|
||||
parts = key.split(".")
|
||||
d = cls._settings
|
||||
for part in parts[:-1]:
|
||||
if part not in d:
|
||||
logger.debug(f"Config key '{key}' not found for deletion.")
|
||||
return
|
||||
d = d[part]
|
||||
if parts[-1] in d:
|
||||
d.pop(parts[-1], None)
|
||||
cls._save()
|
||||
logger.info(f"Config key '{key}' deleted.")
|
||||
else:
|
||||
logger.debug(f"Config key '{key}' not found for deletion.")
|
||||
@@ -59,14 +59,18 @@ SOUND_PATH: Path = get_asset_path("assets/sound/notification.mp3")
|
||||
|
||||
OS_NAME: str = platform.system() # Windows ; Darwin ; Linux
|
||||
|
||||
IS_FROZEN = getattr(sys, "frozen", False)
|
||||
USER_HOME_DIR: Path = Path.home()
|
||||
|
||||
# OS Specific Constants
|
||||
if OS_NAME == "Windows":
|
||||
OS_FULL_NAME: str = f"{OS_NAME} {platform.release()}"
|
||||
|
||||
# APP_PATH will be from system environment path or fallback to Path.home()
|
||||
APP_DIR: Path = Path(os.environ.get("LOCALAPPDATA", USER_HOME_DIR / "AppData" / "Local")) / "YTSage"
|
||||
if IS_FROZEN:
|
||||
APP_DIR: Path = Path(sys.executable).parent
|
||||
else:
|
||||
# APP_PATH will be from system environment path or fallback to Path.home()
|
||||
APP_DIR: Path = Path(os.environ.get("LOCALAPPDATA", USER_HOME_DIR / "AppData" / "Local")) / "YTSage"
|
||||
APP_BIN_DIR: Path = APP_DIR / "bin"
|
||||
APP_DATA_DIR: Path = APP_DIR / "data"
|
||||
APP_LOG_DIR: Path = APP_DIR / "logs"
|
||||
@@ -74,9 +78,6 @@ if OS_NAME == "Windows":
|
||||
|
||||
YTDLP_DOWNLOAD_URL: str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"
|
||||
YTDLP_APP_BIN_PATH: Path = APP_BIN_DIR / "yt-dlp.exe"
|
||||
|
||||
# Documentation URLs
|
||||
YTDLP_DOCS_URL: str = "https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#usage-and-options"
|
||||
|
||||
SUBPROCESS_CREATIONFLAGS: int = subprocess.CREATE_NO_WINDOW
|
||||
|
||||
@@ -84,7 +85,10 @@ elif OS_NAME == "Darwin": # macOS
|
||||
_mac_version = platform.mac_ver()[0]
|
||||
OS_FULL_NAME: str = f"macOS {_mac_version}" if _mac_version else "macOS"
|
||||
|
||||
APP_DIR: Path = USER_HOME_DIR / "Library" / "Application Support" / "YTSage"
|
||||
if IS_FROZEN:
|
||||
APP_DIR: Path = Path(sys.executable).parent
|
||||
else:
|
||||
APP_DIR: Path = USER_HOME_DIR / "Library" / "Application Support" / "YTSage"
|
||||
APP_BIN_DIR: Path = APP_DIR / "bin"
|
||||
APP_DATA_DIR: Path = APP_DIR / "data"
|
||||
APP_LOG_DIR: Path = APP_DIR / "logs"
|
||||
@@ -92,9 +96,6 @@ elif OS_NAME == "Darwin": # macOS
|
||||
|
||||
YTDLP_DOWNLOAD_URL: str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"
|
||||
YTDLP_APP_BIN_PATH: Path = APP_BIN_DIR / "yt-dlp"
|
||||
|
||||
# Documentation URLs
|
||||
YTDLP_DOCS_URL: str = "https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#usage-and-options"
|
||||
|
||||
SUBPROCESS_CREATIONFLAGS: int = 0
|
||||
|
||||
@@ -102,7 +103,10 @@ elif OS_NAME == "Darwin": # macOS
|
||||
else: # Linux and other UNIX-like
|
||||
OS_FULL_NAME: str = f"{OS_NAME} {platform.release()}"
|
||||
|
||||
APP_DIR: Path = USER_HOME_DIR / ".local" / "share" / "YTSage"
|
||||
if IS_FROZEN:
|
||||
APP_DIR: Path = Path(sys.executable).parent
|
||||
else:
|
||||
APP_DIR: Path = USER_HOME_DIR / ".local" / "share" / "YTSage"
|
||||
APP_BIN_DIR: Path = APP_DIR / "bin"
|
||||
APP_DATA_DIR: Path = APP_DIR / "data"
|
||||
APP_LOG_DIR: Path = APP_DIR / "logs"
|
||||
@@ -110,12 +114,11 @@ else: # Linux and other UNIX-like
|
||||
|
||||
YTDLP_DOWNLOAD_URL: str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp"
|
||||
YTDLP_APP_BIN_PATH: Path = APP_BIN_DIR / "yt-dlp"
|
||||
|
||||
# Documentation URLs
|
||||
YTDLP_DOCS_URL: str = "https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#usage-and-options"
|
||||
|
||||
SUBPROCESS_CREATIONFLAGS: int = 0
|
||||
|
||||
# Documentation URLs
|
||||
YTDLP_DOCS_URL: str = "https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#usage-and-options"
|
||||
|
||||
# ffmpeg download links
|
||||
FFMPEG_7Z_DOWNLOAD_URL = "https://github.com/GyanD/codexffmpeg/releases/download/7.1.1/ffmpeg-7.1.1-full_build.7z"
|
||||
@@ -124,6 +127,7 @@ FFMPEG_ZIP_DOWNLOAD_URL = "https://github.com/GyanD/codexffmpeg/releases/downloa
|
||||
|
||||
if __name__ == "__main__":
|
||||
# If this file is run directly, print directory information; if imported, create the necessary directories for the application.
|
||||
# for debug, to check os specific variable which can be different based on os.
|
||||
info = {
|
||||
"OS_NAME": OS_NAME,
|
||||
"OS_FULL_NAME": OS_FULL_NAME,
|
||||
@@ -135,7 +139,6 @@ if __name__ == "__main__":
|
||||
"APP_CONFIG_FILE": str(APP_CONFIG_FILE),
|
||||
"YTDLP_DOWNLOAD_URL": YTDLP_DOWNLOAD_URL,
|
||||
"YTDLP_APP_BIN_PATH": YTDLP_APP_BIN_PATH,
|
||||
"YTDLP_DOCS_URL": YTDLP_DOCS_URL,
|
||||
"SUBPROCESS_CREATIONFLAGS": SUBPROCESS_CREATIONFLAGS,
|
||||
}
|
||||
for key, value in info.items():
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
YTSage centralized logging with loguru.
|
||||
|
||||
- This module provides centralized logging configuration for the entire YTSage application.
|
||||
- Two log files: ytsage.log (all logs) & ytsage_error.log (errors only).
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from src.utils.ytsage_constants import APP_LOG_DIR, IS_FROZEN
|
||||
|
||||
# Separate configs for each handler
|
||||
CONSOLE_CONFIG = {
|
||||
"sink": sys.stdout if sys.stdout else sys.stderr,
|
||||
"level": "INFO",
|
||||
"colorize": True,
|
||||
"enqueue": True,
|
||||
}
|
||||
|
||||
ALL_LOGS_CONFIG = {
|
||||
"sink": APP_LOG_DIR / "ytsage.log",
|
||||
"level": "DEBUG",
|
||||
"rotation": "10 MB",
|
||||
"retention": "14 days",
|
||||
"compression": "zip",
|
||||
"enqueue": True,
|
||||
}
|
||||
|
||||
ERROR_LOGS_CONFIG = {
|
||||
"sink": APP_LOG_DIR / "ytsage_error.log",
|
||||
"level": "ERROR",
|
||||
"rotation": "5 MB",
|
||||
"retention": "30 days",
|
||||
"compression": "zip",
|
||||
"enqueue": True,
|
||||
}
|
||||
|
||||
|
||||
# Logger initialization
|
||||
def init_logger() -> None:
|
||||
"""Configure loguru logger using separate configs for each handler."""
|
||||
logger.remove() # Remove default loguru handler
|
||||
|
||||
if not IS_FROZEN:
|
||||
logger.add(**CONSOLE_CONFIG)
|
||||
logger.add(**ALL_LOGS_CONFIG)
|
||||
logger.add(**ERROR_LOGS_CONFIG)
|
||||
|
||||
logger.info("YTSage logger initialized")
|
||||
|
||||
|
||||
init_logger()
|
||||
|
||||
__all__ = ["logger"]
|
||||
Reference in New Issue
Block a user