from __future__ import annotations import os import shutil import sys from pathlib import Path APP_NAME = "SakuraDownloader" LEGACY_APP_NAME = "PixivDownloader" def is_frozen() -> bool: return bool(getattr(sys, "frozen", False)) def resource_root() -> Path: if is_frozen(): return Path(getattr(sys, "_MEIPASS")).resolve() return Path(__file__).resolve().parents[2] def executable_dir() -> Path: if is_frozen(): return Path(sys.executable).resolve().parent return resource_root() def data_root() -> Path: override = os.environ.get("SAKURA_APP_DATA_DIR") or os.environ.get("PIXIV_APP_DATA_DIR") if override: root = Path(override) elif is_frozen(): local_appdata = os.environ.get("LOCALAPPDATA") root = Path(local_appdata) / APP_NAME if local_appdata else executable_dir() / "data" legacy_root = Path(local_appdata) / LEGACY_APP_NAME if local_appdata else None if legacy_root and legacy_root.exists() and not root.exists(): root.mkdir(parents=True, exist_ok=True) for name in ("pixiv_app_session.json", "runtime", "profiles", "plugins"): src = legacy_root / name dst = root / name if src.exists() and not dst.exists(): if src.is_dir(): import shutil shutil.copytree(src, dst) else: dst.write_bytes(src.read_bytes()) else: root = resource_root() root.mkdir(parents=True, exist_ok=True) return root def runtime_path(*parts: str) -> Path: path = data_root() / "runtime" path.mkdir(parents=True, exist_ok=True) return path.joinpath(*parts) def profiles_root() -> Path: path = data_root() / "profiles" path.mkdir(parents=True, exist_ok=True) return path def plugins_root() -> Path: return resource_root() / "plugins" def external_plugins_root() -> Path: """Plugins shipped beside the executable, outside the PyInstaller bundle.""" return executable_dir() / "plugins" def user_plugins_root() -> Path: path = data_root() / "plugins" path.mkdir(parents=True, exist_ok=True) return path def plugin_roots() -> list[Path]: roots = [plugins_root(), external_plugins_root(), user_plugins_root()] result: list[Path] = [] for root in roots: if root not in result: result.append(root) return result def webui_root() -> Path: return resource_root() / "pixiv_app" / "webui" def app_session_file() -> Path: return data_root() / "pixiv_app_session.json" def app_library_file() -> Path: """Persistent local library DB, writable even when the EXE directory is read-only.""" target = data_root() / "pixiv_app_library.db" if is_frozen() and not target.exists(): legacy = executable_dir() / "pixiv_app_library.db" if legacy.is_file(): target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(legacy, target) return target def downloads_root() -> Path: path = executable_dir() / "Sakura_Downloads" path.mkdir(parents=True, exist_ok=True) return path