From 968d0079544261a165efb1f8d416790521f25ba9 Mon Sep 17 00:00:00 2001 From: Lucas Vivo Date: Mon, 9 Nov 2026 20:01:23 +0100 Subject: [PATCH] feat(wallpaper-changer.py): add modular Python port Introduce a Python CLI for selecting, processing, and setting wallpapers, including encrypted image and naming-table workflows, monitor-aware image composition, search and exclusion filters, and migration and usage notes. Module guide: - main.py: validates command combinations and coordinates configuration, encryption commands, image processing, monitor detection, wallpaper composition, and GNOME wallpaper setting. - wallpaper_changer/__init__.py: marks the application package. - wallpaper_changer/argument_parser.py: defines CLI options and merges command-line arguments with arguments loaded from the config file. - wallpaper_changer/config.py: loads host-specific image, wallpaper, and private-key settings. - wallpaper_changer/encryption_manager.py: reads and writes legacy OpenSSL encrypted files and loads, stores, encrypts, or decrypts naming tables. - wallpaper_changer/image_repository.py: scans and converts images, manages encrypted images and naming-table entries, and handles image decoding and sequential filename correction. - wallpaper_changer/logging_utils.py: configures and retrieves the project's custom logger. - wallpaper_changer/monitor_manager.py: discovers monitor layouts from DRM data or host configuration files. - wallpaper_changer/naming_table.py: loads legacy plaintext naming-table entries. - wallpaper_changer/wallpaper_builder.py: filters and selects images, decrypts as needed, and composes a labeled multi-monitor wallpaper. - wallpaper_changer/wallpaper_setter.py: sets GNOME background settings using gsettings. --- wallpaper_changer/.vscode/launch.json | 19 + wallpaper_changer/.vscode/settings.json | 13 + wallpaper_changer/README.md | 12 + wallpaper_changer/docs/MIGRATION_NOTES.md | 1 + wallpaper_changer/main.py | 124 ++++++ .../wallpaper_changer/__init__.py | 0 .../wallpaper_changer/argument_parser.py | 132 ++++++ wallpaper_changer/wallpaper_changer/config.py | 44 ++ wallpaper_changer/wallpaper_changer/daemon.py | 8 + .../wallpaper_changer/encryption_manager.py | 179 ++++++++ .../wallpaper_changer/image_repository.py | 391 ++++++++++++++++++ .../wallpaper_changer/logging_utils.py | 12 + .../wallpaper_changer/monitor_manager.py | 195 +++++++++ .../wallpaper_changer/naming_table.py | 10 + .../wallpaper_changer/wallpaper_builder.py | 166 ++++++++ .../wallpaper_changer/wallpaper_setter.py | 33 ++ 16 files changed, 1339 insertions(+) create mode 100644 wallpaper_changer/.vscode/launch.json create mode 100644 wallpaper_changer/.vscode/settings.json create mode 100644 wallpaper_changer/README.md create mode 100644 wallpaper_changer/docs/MIGRATION_NOTES.md create mode 100755 wallpaper_changer/main.py create mode 100644 wallpaper_changer/wallpaper_changer/__init__.py create mode 100644 wallpaper_changer/wallpaper_changer/argument_parser.py create mode 100644 wallpaper_changer/wallpaper_changer/config.py create mode 100644 wallpaper_changer/wallpaper_changer/daemon.py create mode 100644 wallpaper_changer/wallpaper_changer/encryption_manager.py create mode 100644 wallpaper_changer/wallpaper_changer/image_repository.py create mode 100644 wallpaper_changer/wallpaper_changer/logging_utils.py create mode 100644 wallpaper_changer/wallpaper_changer/monitor_manager.py create mode 100644 wallpaper_changer/wallpaper_changer/naming_table.py create mode 100644 wallpaper_changer/wallpaper_changer/wallpaper_builder.py create mode 100644 wallpaper_changer/wallpaper_changer/wallpaper_setter.py diff --git a/wallpaper_changer/.vscode/launch.json b/wallpaper_changer/.vscode/launch.json new file mode 100644 index 0000000..bd36467 --- /dev/null +++ b/wallpaper_changer/.vscode/launch.json @@ -0,0 +1,19 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "wallpaper_changer: main.py", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/main.py", + "args": [ + "--log-level", + "TRACE", + "-x","--disable-encryption" + ], + "console": "integratedTerminal", + "cwd": "${workspaceFolder}", + "justMyCode": false + } + ] +} diff --git a/wallpaper_changer/.vscode/settings.json b/wallpaper_changer/.vscode/settings.json new file mode 100644 index 0000000..fbd8c57 --- /dev/null +++ b/wallpaper_changer/.vscode/settings.json @@ -0,0 +1,13 @@ +{ + "python.defaultInterpreterPath": "/home/lucas/scripts/.venv/bin/python", + "python-envs.pythonProjects": [ + { + "path": "main.py", + "envManager": "ms-python.python:venv", + "packageManager": "ms-python.python:pip" + } + ], + "editor.tabSize": 4, + "editor.insertSpaces": true, + "editor.detectIndentation": false +} \ No newline at end of file diff --git a/wallpaper_changer/README.md b/wallpaper_changer/README.md new file mode 100644 index 0000000..66f7429 --- /dev/null +++ b/wallpaper_changer/README.md @@ -0,0 +1,12 @@ +Generated migration starter from WallpaperChanger.sh. Implements monitor detection, image scanning, openssl wrapper, naming table loader, wallpaper builder and GNOME setter. + +Use `--disable-encryption` to build a wallpaper from a folder without encrypting files or decrypting images or the naming table. Encrypted image payloads are skipped; `.jpg_enc` files are included only when they contain plain JPEG data. + +Encrypt or decrypt the fixed naming-table files in the selected image folder: + +```sh +wallpaperchanger --encryptNT +wallpaperchanger --decryptNT +``` + +`--encryptNT` reads `naming_table.dec` and writes `naming_table_enc.txt`; `--decryptNT` reads `naming_table_enc.txt` and writes `naming_table.dec`. \ No newline at end of file diff --git a/wallpaper_changer/docs/MIGRATION_NOTES.md b/wallpaper_changer/docs/MIGRATION_NOTES.md new file mode 100644 index 0000000..ca1ddee --- /dev/null +++ b/wallpaper_changer/docs/MIGRATION_NOTES.md @@ -0,0 +1 @@ +Generated from WallpaperChanger.sh modules: change_image, get_screensize, encryption, naming-table, daemon, gsettings, Nextcloud sync. \ No newline at end of file diff --git a/wallpaper_changer/main.py b/wallpaper_changer/main.py new file mode 100755 index 0000000..d8514aa --- /dev/null +++ b/wallpaper_changer/main.py @@ -0,0 +1,124 @@ +#!/home/lucas/scripts/.venv/bin/python3 +from pathlib import Path +import sys + +from wallpaper_changer.logging_utils import get_logger +from serverlibrary import setup_logging + +from wallpaper_changer.config import Config +from wallpaper_changer.argument_parser import parse_args +from wallpaper_changer.image_repository import ImageRepository +from wallpaper_changer.monitor_manager import MonitorManager +from wallpaper_changer.encryption_manager import EncryptionManager +from wallpaper_changer.wallpaper_builder import WallpaperBuilder +from wallpaper_changer.wallpaper_setter import WallpaperSetter + +logger = get_logger(__name__) + +args = parse_args() + +if args.disable_encryption and ( + args.check_encryption + or args.decode_all + or args.decode_argument + or args.printNT + or args.encryptNT + or args.decryptNT +): + raise ValueError( + "--disable-encryption cannot be used with encryption check, decode, or naming-table commands" + ) + +if ( + args.check_encryption or args.decode_all or args.decode_argument or args.printNT +) and args.folder == "default": + args.folder = "x" +setup_logging(args.log_level, "wallpaper_changer") + +if args.clear: + args.folder = "default" + args.search = None + +cfg = Config.load(args) + +if args.printNT: + naming_table = EncryptionManager().load_naming_table( + cfg.img_dir / "naming_table.enc", cfg.private_key + ) + for original_name, encrypted_name in naming_table: + if args.grep_nt and args.grep_nt not in original_name: + continue + print(f"{original_name} -> {encrypted_name}") + sys.exit(0) + +image_repository = ImageRepository(cfg.img_dir) + +if args.encryptNT: + EncryptionManager().encrypt_naming_table_file( + cfg.img_dir / "naming_table.dec", + cfg.img_dir / "naming_table.enc", + cfg.private_key, + ) + sys.exit(0) + +if args.decryptNT: + EncryptionManager().decrypt_naming_table_file( + cfg.img_dir / "naming_table.enc", + cfg.img_dir / "naming_table.dec", + cfg.private_key, + ) + sys.exit(0) + +if not args.disable_encryption and (args.check_encryption or args.folder != "default"): + new_images_folder = Path("~").expanduser() / "Wallpaper" / "New" + image_repository.check_encryption( + new_images_folder, cfg.private_key, replace=args.replace + ) + image_repository.check_encryption( + cfg.img_dir, cfg.private_key, replace=args.replace + ) + +if args.decode_all: + image_repository.decode_all(cfg.private_key) + sys.exit(0) + + +if args.decode_argument: + image_repository.decode_images( + pattern=args.decode_argument, + private_key=cfg.private_key, + remove=args.rm, + ) + sys.exit(0) + +image_repository.convert_to_jpg() +image_repository.check_consecutive_filenames(correct=True) +imgs = image_repository.scan( + cfg.private_key, + disable_encryption=args.disable_encryption, +) + +monitor_image_dir = cfg.img_dir.parent if cfg.host == "serverhost" else cfg.img_dir +monitors = MonitorManager().get_screensize( + cfg.host, + monitor_image_dir, + args.monitor_config, +) + +if args.times < 1: + raise ValueError("--times must be at least 1") + +wallpaper_builder = WallpaperBuilder() +wallpaper_setter = WallpaperSetter() +for _ in range(args.times): + wallpaper_path = wallpaper_builder.build( + imgs, + monitors, + private_key=cfg.private_key, + search_terms=args.search, + exclude=args.exclude, + decode_and_leave=args.decode_and_leave, + disable_encryption=args.disable_encryption, + ) + wallpaper_setter.set_ubuntu(wallpaper_path) + print(wallpaper_path) diff --git a/wallpaper_changer/wallpaper_changer/__init__.py b/wallpaper_changer/wallpaper_changer/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/wallpaper_changer/wallpaper_changer/argument_parser.py b/wallpaper_changer/wallpaper_changer/argument_parser.py new file mode 100644 index 0000000..5586a88 --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/argument_parser.py @@ -0,0 +1,132 @@ +import shlex +import sys +from argparse import ArgumentParser, Namespace +from collections.abc import Sequence + +from serverlibrary import parser_add_loglevel + +from wallpaper_changer.config import Config + + +def build_parser() -> ArgumentParser: + parser = ArgumentParser( + prog="wallpaperchanger", + description="Wallpaper changer and encrypted wallpaper vault manager", + ) + + parser.add_argument( + "-t", + "--daemon", + type=int, + metavar="MINUTES", + help="Run in daemon mode and change wallpaper every N minutes", + ) + parser.add_argument("-s", "--search", nargs="+", help="Search parameters") + parser.add_argument( + "-ex", + "--exclude", + nargs="+", + default=["elements"], + help="Exclude terms", + ) + parser.add_argument( + "-c", "--config", action="store_true", help="Load configuration file" + ) + parser.add_argument("-l", "--log", action="store_true", help="Enable logging") + + parser.add_argument( + "-clear", + "--clear", + action="store_true", + help="Clear configuration and wallpapers", + ) + parser.add_argument("-times", type=int, default=1, help="Change wallpaper N times") + parser.add_argument( + "-mon", "--monitor-config", type=int, default=0, help="Use monitors.cfg" + ) + parser.add_argument("-screen", help="Override screen size") + + folder_group = parser.add_mutually_exclusive_group() + folder_group.add_argument( + "-f", + "--folder", + type=str.lower, + choices=("x", "insta", "default"), + metavar="FOLDER", + default="default", + help="Select the image folder: x or insta", + ) + folder_group.add_argument( + "-x", + dest="folder", + action="store_const", + const="x", + help="Alias for --folder x", + ) + folder_group.add_argument( + "-i", + dest="folder", + action="store_const", + const="insta", + help="Alias for --folder insta", + ) + + parser.add_argument( + "--decode-and-leave","-dec-leave", action="store_true", help="Leave decrypted files on disk" + ) + parser.add_argument( + "--disable-encryption", + action="store_true", + help="Skip encryption and decryption when building a wallpaper", + ) + parser.add_argument("-replace", action="store_true", help="Replace encrypted image") + parser.add_argument( + "-ch-enc", + "--check-encryption", + action="store_true", + help="Encrypt/decrypt consistency check", + ) + parser.add_argument( + "-dec-all", "--decode-all", action="store_true", help="Decrypt all images" + ) + parser.add_argument( + "-dec-arg", + "--decode-argument", + metavar="PATTERN", + help="Decrypt images matching pattern", + ) + parser.add_argument( + "-rm", action="store_true", help="Delete encrypted source after processing" + ) + parser.add_argument("--printNT", action="store_true", help="Print naming table") + parser.add_argument( + "-g", "--grep-nt", metavar="PATTERN", help="Search naming table" + ) + naming_table_group = parser.add_mutually_exclusive_group() + naming_table_group.add_argument( + "--encryptNT", + action="store_true", + help="Encrypt naming_table.dec to naming_table.enc in the selected image folder", + ) + naming_table_group.add_argument( + "--decryptNT", + action="store_true", + help="Decrypt naming_table.enc to naming_table.dec in the selected image folder", + ) + parser_add_loglevel(parser) + return parser + + +def parse_args(argv: Sequence[str] | None = None) -> Namespace: + command_line = list(sys.argv[1:] if argv is None else argv) + parser = build_parser() + initial_args, _ = parser.parse_known_args(command_line) + if not initial_args.config: + return parser.parse_args(command_line) + + config_tokens = shlex.split( + Config.argument_config_file().read_text(), + comments=True, + ) + config_args = parser.parse_args(config_tokens) + return parser.parse_args(command_line, namespace=config_args) diff --git a/wallpaper_changer/wallpaper_changer/config.py b/wallpaper_changer/wallpaper_changer/config.py new file mode 100644 index 0000000..7c682f7 --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/config.py @@ -0,0 +1,44 @@ +from dataclasses import dataclass +from pathlib import Path +import socket + +from wallpaper_changer.logging_utils import get_logger + +logger = get_logger(__name__) + +@dataclass +class Config: + host: str + img_dir: Path + img_folder: str + wallpaper_dir: Path + private_key: str + + @staticmethod + def argument_config_file(hostname: str | None = None) -> Path: + config_file = Path.home() / "Wallpaper" / "wp.conf" + if not config_file.exists(): + config_file.parent.mkdir(parents=True, exist_ok=True) + config_file.write_text( + f"# Wallpaper Changer Configuration File\n" + ) + return config_file + + @classmethod + def load(cls, args): + hostname = socket.gethostname() + if hostname == "vivohost": + wallpaper_dir = Path("/tmp/wallpaper") + img_folder = "Desktop1920x1080/" + + if args.folder == "x": + img_folder = "corrupt" + elif args.folder == "insta": + img_folder = "insta" + + img_dir = Path("/home/lucas/Nextcloud/Stuff/Wallpaper/") / img_folder + + private_key = Path( + "file:/home/lucas/Nextcloud/Dokumente/Projekte/Server/quiethost/IMG_privateKey.pem" + ) + return cls(hostname, img_dir, img_folder, wallpaper_dir, private_key) diff --git a/wallpaper_changer/wallpaper_changer/daemon.py b/wallpaper_changer/wallpaper_changer/daemon.py new file mode 100644 index 0000000..ba3948c --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/daemon.py @@ -0,0 +1,8 @@ +import time + + +class DaemonRunner: + def run(self, fn, minutes): + while True: + fn() + time.sleep(minutes * 60) diff --git a/wallpaper_changer/wallpaper_changer/encryption_manager.py b/wallpaper_changer/wallpaper_changer/encryption_manager.py new file mode 100644 index 0000000..a4ea74e --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/encryption_manager.py @@ -0,0 +1,179 @@ +import os +from pathlib import Path +from os import PathLike +from typing import overload + +from cryptography.hazmat.primitives import hashes, padding +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC + +from wallpaper_changer.logging_utils import get_logger + +logger = get_logger(__name__) + + +class EncryptionManager: + """Encrypt and decrypt files using the legacy OpenSSL enc file format.""" + + _MAGIC = b"Salted__" + _SALT_SIZE = 8 + _KEY_SIZE = 32 + _IV_SIZE = 16 + _ITERATIONS = 10_000 + _BLOCK_SIZE = algorithms.AES.block_size + + def encrypt( + self, + src: str | PathLike[str], + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: + self.encrypt_data(Path(src).read_bytes(), dst, key) + + def encrypt_naming_table_file( + self, + src: str | PathLike[str], + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: + source_path = Path(src) + destination_path = Path(dst) + if not source_path.exists(): + raise FileNotFoundError(f"Naming-table source file does not exist: {source_path}") + if source_path.resolve() == destination_path.resolve(): + raise ValueError("Naming-table source and destination must be different") + self.encrypt(source_path, destination_path, key) + source_path.unlink(missing_ok=True) + + def decrypt_naming_table_file( + self, + src: str | PathLike[str], + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: + source_path = Path(src) + destination_path = Path(dst) + if not source_path.exists(): + raise FileNotFoundError(f"Naming-table source file does not exist: {source_path}") + if source_path.resolve() == destination_path.resolve(): + raise ValueError("Naming-table source and destination must be different") + self.decrypt(source_path, destination_path, key) + source_path.unlink(missing_ok=True) + + def encrypt_data( + self, + plaintext: bytes, + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: + salt = os.urandom(self._SALT_SIZE) + aes_key, iv = self._derive_key_and_iv(key, salt) + + padder = padding.PKCS7(self._BLOCK_SIZE).padder() + padded_plaintext = padder.update(plaintext) + padder.finalize() + encryptor = Cipher(algorithms.AES(aes_key), modes.CBC(iv)).encryptor() + ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize() + + Path(dst).write_bytes(self._MAGIC + salt + ciphertext) + + def load_naming_table( + self, src: str | PathLike[str], key: str | bytes | PathLike[str] + ) -> list[tuple[str, str]]: + encrypted_path = Path(src) + if not encrypted_path.exists(): + return [] + + content = self.decrypt(encrypted_path, None, key) + if content is None: + raise ValueError(f"Failed to read the naming table: {encrypted_path}") + + naming_table = [] + for line in content.decode("utf-8").splitlines(): + if line.strip() and ";" in line: + original_name, encrypted_name = line.split(";", 1) + naming_table.append((original_name, encrypted_name)) + return naming_table + + def store_naming_table( + self, + naming_table: list[tuple[str, str]], + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: + content = "".join( + f"{original_name};{encrypted_name}\n" + for original_name, encrypted_name in naming_table + ).encode("utf-8") + self.encrypt_data(content, dst, key) + + @overload + def decrypt( + self, + src: str | PathLike[str], + dst: None, + key: str | bytes | PathLike[str], + ) -> bytes: ... + + @overload + def decrypt( + self, + src: str | PathLike[str], + dst: str | PathLike[str], + key: str | bytes | PathLike[str], + ) -> None: ... + + def decrypt( + self, + src: str | PathLike[str], + dst: str | PathLike[str] | None, + key: str | bytes | PathLike[str], + ) -> bytes | None: + encrypted = Path(src).read_bytes() + header_size = len(self._MAGIC) + self._SALT_SIZE + ciphertext = encrypted[header_size:] + if ( + not encrypted.startswith(self._MAGIC) + or len(ciphertext) < self._BLOCK_SIZE // 8 + or len(ciphertext) % (self._BLOCK_SIZE // 8) != 0 + ): + raise ValueError("Invalid or truncated encrypted file") + + salt = encrypted[len(self._MAGIC) : header_size] + aes_key, iv = self._derive_key_and_iv(key, salt) + decryptor = Cipher(algorithms.AES(aes_key), modes.CBC(iv)).decryptor() + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + unpadder = padding.PKCS7(self._BLOCK_SIZE).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + if dst is None: + return plaintext + Path(dst).write_bytes(plaintext) + return None + + @classmethod + def _derive_key_and_iv( + cls, password: str | bytes | PathLike[str], salt: bytes + ) -> tuple[bytes, bytes]: + passphrase = cls._read_passphrase(password) + key_material = PBKDF2HMAC( + algorithm=hashes.SHA256(), + length=cls._KEY_SIZE + cls._IV_SIZE, + salt=salt, + iterations=cls._ITERATIONS, + ).derive(passphrase) + return key_material[: cls._KEY_SIZE], key_material[cls._KEY_SIZE :] + + @staticmethod + def _read_passphrase(password: str | bytes | PathLike[str]) -> bytes: + if isinstance(password, bytes): + return password + + value = os.fspath(password) + if value.startswith("file:"): + passphrase_file = Path(value.removeprefix("file:")) + return passphrase_file.read_bytes().partition(b"\n")[0].removesuffix(b"\r") + if isinstance(password, PathLike): + return Path(value).read_bytes().partition(b"\n")[0].removesuffix(b"\r") + if value.startswith("pass:"): + value = value.removeprefix("pass:") + return value.encode("utf-8") diff --git a/wallpaper_changer/wallpaper_changer/image_repository.py b/wallpaper_changer/wallpaper_changer/image_repository.py new file mode 100644 index 0000000..7e09d41 --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/image_repository.py @@ -0,0 +1,391 @@ +import logging +import re +import shutil +from dataclasses import dataclass +from pathlib import Path + +from PIL import Image, ImageOps + +from wallpaper_changer.encryption_manager import EncryptionManager +from wallpaper_changer.logging_utils import get_logger + +IMAGE_EXTENSIONS = frozenset(Image.registered_extensions()) + + +@dataclass +class WallpaperImage: + path: Path + width: int + height: int + aspect: float + + +class ImageRepository: + def __init__(self, root: str | Path): + self.img_folder_path = Path(root) + self.logger = get_logger(__name__) + self.image_list = [] + + def scan(self, private_key: str | Path, disable_encryption: bool = False): + out = [] + result: dict[str, str] = {} + if not disable_encryption: + encryption_manager = EncryptionManager() + result = { + encrypted_name: original_name + for original_name, encrypted_name in encryption_manager.load_naming_table( + self.img_folder_path / "naming_table.enc", private_key + ) + } + for file in self.img_folder_path.rglob("*"): + if not file.is_file(): + continue + if file.suffix.lower() not in IMAGE_EXTENSIONS | {".jpg_enc"}: + continue + if ( + disable_encryption + and file.suffix.lower() == ".jpg_enc" + and not self._is_jpg(file) + ): + continue + + self.logger.trace(f"Found image {file}") + out.append( + { + "file": file, + "name": result.get(file.name, file.name), + } + ) + self.image_list = out + return out + + def convert_to_jpg(self, image_folder: str | Path | None = None) -> list[Path]: + folder = ( + Path(image_folder) if image_folder is not None else self.img_folder_path + ) + converted_paths = [] + for image_path in sorted(folder.rglob("*")): + converted_path = self._convert_to_jpg(image_path) + if converted_path is not None: + converted_paths.append(converted_path) + return converted_paths + + def check_encryption( + self, new_images_folder: Path, private_key: str | Path, replace: bool = False + ) -> list[Path]: + if not new_images_folder.is_dir(): + self.logger.warning(f"New folder does not exist: {new_images_folder}") + return [] + new_images = list(new_images_folder.glob("*")) + if not new_images: + self.logger.trace(f"No new images found in {new_images_folder}") + return [] + self.convert_to_jpg(new_images_folder) + + for image_path in sorted(new_images_folder.rglob("*.jpg")): + if not image_path.is_file(): + continue + if image_path.parent == self.img_folder_path: + continue + destination = self._available_path(self.img_folder_path / image_path.name) + shutil.move(str(image_path), destination) + + encryption_manager = EncryptionManager() + naming_table_path = self.img_folder_path / "naming_table.enc" + naming_table = encryption_manager.load_naming_table( + naming_table_path, private_key + ) + encrypted_numbers = [ + int(match.group(1)) + for path in self.img_folder_path.rglob("*.jpg_enc") + if (match := re.fullmatch(r"(\d+)\.jpg_enc", path.name)) + ] + next_number = max(encrypted_numbers, default=0) + 1 + encrypted_images = [] + plaintext_images = [] + + for image_path in sorted(self.img_folder_path.rglob("*")): + if ( + not image_path.is_file() + or image_path.suffix.lower() not in IMAGE_EXTENSIONS + ): + continue + + existing_entry = next( + (entry for entry in naming_table if entry[0] == image_path.name), + None, + ) + if existing_entry and replace: + image_name = existing_entry[1] + identifier = image_path.name + else: + identifier = image_path.name + if existing_entry: + identifier = self._unique_identifier(identifier, naming_table) + + image_name = f"{next_number:05}.jpg_enc" + next_number += 1 + image_name = self._available_path( + self.img_folder_path / image_name + ).name + + encrypted_path = self.img_folder_path / image_name + self.logger.trace(f"Encrypting {image_path} to {encrypted_path}") + encryption_manager.encrypt(image_path, encrypted_path, private_key) + encrypted_images.append(encrypted_path) + plaintext_images.append(image_path) + + if not existing_entry or not replace: + naming_table.append((identifier, image_name)) + + encryption_manager.store_naming_table( + naming_table, naming_table_path, private_key + ) + for image_path in plaintext_images: + image_path.unlink() + self.logger.info("Check encryption done") + return encrypted_images + + def check_consecutive_filenames( + self, correct: bool = False + ) -> bool: + """Check JPG number suffixes per folder and prefix, optionally fixing gaps.""" + numbered_images: dict[tuple[Path, str], list[tuple[int, str, Path]]] = {} + for path in self.img_folder_path.rglob("*"): + if not path.is_file(): + continue + match = re.fullmatch(r"(.*?)(\d+)\.jpg", path.name, re.IGNORECASE) + if not match: + continue + + prefix, number_text = match.groups() + numbered_images.setdefault((path.parent, prefix), []).append( + (int(number_text), number_text, path) + ) + + renamed_files = [] + is_consecutive = True + for (folder, prefix), images in numbered_images.items(): + images.sort(key=lambda image: (image[0], image[2].name)) + numbers = [number for number, _, _ in images] + expected_numbers = list( + range(numbers[0], numbers[0] + len(numbers)) + ) + if numbers == expected_numbers: + continue + + is_consecutive = False + self.logger.debug( + f"Non-consecutive JPG filenames in {folder} for prefix " + f"{prefix!r}: found {numbers}" + ) + if not correct: + continue + + width = max(len(number_text) for _, number_text, _ in images) + for index, (_, _, path) in enumerate(images): + new_number = numbers[0] + index + new_name = f"{prefix}{new_number:0{width}d}{path.suffix}" + renamed_files.append((path, path.with_name(new_name))) + + if not correct or is_consecutive: + self.logger.debug( + f"Numbered JPG images are consecutive: {is_consecutive}" + ) + return is_consecutive + + staged_files = [] + for old_path, new_path in renamed_files: + self.logger.debug(f"Renaming {old_path} to {new_path}") + temporary_path = self._available_path( + old_path.with_name(f".{old_path.name}.renumbering.jpg") + ) + old_path.rename(temporary_path) + staged_files.append((temporary_path, new_path)) + + for temporary_path, new_path in staged_files: + temporary_path.rename(new_path) + + self.logger.info("Corrected gaps in JPG filename sequences") + return True + + def decode_all(self, private_key: str | Path) -> list[Path]: + naming_table_path = self.img_folder_path / "naming_table.enc" + encryption_manager = EncryptionManager() + naming_table = encryption_manager.load_naming_table( + naming_table_path, private_key + ) + encrypted_images = sorted(self.img_folder_path.rglob("*.jpg_enc")) + decoded_paths = [] + sources_to_remove = [] + + for encrypted_path in encrypted_images: + if self._is_jpg(encrypted_path): + continue + + image_name = next( + ( + original_name + for original_name, encrypted_name in naming_table + if encrypted_name == encrypted_path.name + ), + None, + ) + if image_name is None: + image_name = self._find_name_in_legacy_tables(encrypted_path.name) + self.logger.warning( + f"Could not find original name for {encrypted_path.name} in naming table, checking legacy tables: {image_name}" + ) + if image_name is None: + image_name = f"Sexy_MISSING_{len(decoded_paths) + 1}.jpg" + self.logger.warning( + f"Could not find original name for {encrypted_path.name}, using {image_name}" + ) + + decoded_path = self._available_path( + self.img_folder_path / Path(image_name).name + ) + self.logger.trace(f"Decoding {encrypted_path} to {decoded_path}") + encryption_manager.decrypt(encrypted_path, decoded_path, private_key) + decoded_paths.append(decoded_path) + sources_to_remove.append(encrypted_path) + + for source_path in sources_to_remove: + source_path.unlink() + + encrypted_table = self.img_folder_path / "naming_table.enc" + encrypted_table.unlink(missing_ok=True) + self.logger.info("Decoded all encrypted images") + return decoded_paths + + def decode_images( + self, pattern: str, private_key: str | Path, remove: bool = False + ) -> list[Path]: + matcher = re.compile(pattern) + naming_table_path = self.img_folder_path / "naming_table.enc" + encryption_manager = EncryptionManager() + naming_table = encryption_manager.load_naming_table( + naming_table_path, private_key + ) + selected_entries = [ + entry for entry in naming_table if matcher.search(f"{entry[0]};{entry[1]}") + ] + + decoded_paths = [] + sources_to_remove = [] + decoded_entries = [] + new_folder = Path("~").expanduser() / "Wallpaper" / "New" + new_folder.mkdir(parents=True, exist_ok=True) + + for original_name, encrypted_name in selected_entries: + encrypted_path = self.img_folder_path / Path(encrypted_name).name + if not encrypted_path.exists(): + matches = list(self.img_folder_path.rglob(Path(encrypted_name).name)) + if len(matches) != 1: + raise FileNotFoundError( + f"Could not uniquely locate encrypted image: {encrypted_name}" + ) + encrypted_path = matches[0] + if self._is_jpg(encrypted_path): + continue + + decoded_path = self._available_path(new_folder / Path(original_name).name) + self.logger.trace(f"Decoding {encrypted_path} to {decoded_path}") + encryption_manager.decrypt(encrypted_path, decoded_path, private_key) + decoded_paths.append(decoded_path) + sources_to_remove.append(encrypted_path) + decoded_entries.append((original_name, encrypted_name)) + + if remove: + entries_to_keep = list(naming_table) + for entry in decoded_entries: + entries_to_keep.remove(entry) + encryption_manager.store_naming_table( + entries_to_keep, naming_table_path, private_key + ) + for source_path in sources_to_remove: + source_path.unlink() + else: + encryption_manager.store_naming_table( + naming_table, naming_table_path, private_key + ) + + return decoded_paths + + def _find_name_in_legacy_tables(self, encrypted_name: str) -> str | None: + legacy_folder = self.img_folder_path / "NT" + if not legacy_folder.is_dir(): + return None + + for table_path in sorted(legacy_folder.iterdir()): + if not table_path.is_file(): + continue + for line in table_path.read_text(encoding="utf-8").splitlines(): + if ";" not in line: + continue + original_name, stored_name = line.split(";", 1) + if stored_name == encrypted_name: + return original_name + return None + + @staticmethod + def _is_jpg(path: Path) -> bool: + with path.open("rb") as image_file: + return image_file.read(3) == b"\xff\xd8\xff" + + @staticmethod + def _available_path(path: Path) -> Path: + if not path.exists(): + return path + counter = 1 + while True: + candidate = path.with_name(f"{path.stem}_DOUBLE_{counter}{path.suffix}") + if not candidate.exists(): + return candidate + counter += 1 + + @staticmethod + def _unique_identifier(identifier: str, naming_table: list[tuple[str, str]]) -> str: + existing_names = {original_name for original_name, _ in naming_table} + path = Path(identifier) + counter = 1 + while True: + candidate = f"{path.stem}_enc_DOUBLE_{counter}{path.suffix}" + if candidate not in existing_names: + return candidate + counter += 1 + + def _convert_to_jpg(self, image_path: Path) -> Path | None: + if ( + not image_path.is_file() + or image_path.suffix.lower() not in IMAGE_EXTENSIONS + or image_path.suffix.lower() in {".jpg", "jpeg"} + ): + return None + + jpg_path = self._available_path(image_path.with_suffix(".jpg")) + pil_logger = logging.getLogger("PIL") + previous_log_level = pil_logger.level + pil_logger.setLevel(logging.INFO) + try: + with Image.open(image_path) as image: + if image.format == "JPEG": + if image_path.suffix.lower() == ".jpg": + return image_path + image_path.rename(jpg_path) + return jpg_path + + image = ImageOps.exif_transpose(image) + if image.mode in {"RGBA", "LA"} or "transparency" in image.info: + rgba = image.convert("RGBA") + converted = Image.new("RGB", rgba.size, "white") + converted.paste(rgba, mask=rgba.getchannel("A")) + else: + converted = image.convert("RGB") + self.logger.trace(f"Converting {image_path} to {jpg_path}") + converted.save(jpg_path, format="JPEG", quality=95) + finally: + pil_logger.setLevel(previous_log_level) + + image_path.unlink() + return jpg_path diff --git a/wallpaper_changer/wallpaper_changer/logging_utils.py b/wallpaper_changer/wallpaper_changer/logging_utils.py new file mode 100644 index 0000000..a653c9e --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/logging_utils.py @@ -0,0 +1,12 @@ +import logging + +from serverlibrary import CustomLogger + +logging.setLoggerClass(CustomLogger) + + +def get_logger(name: str) -> CustomLogger: + logger = logging.getLogger(name) + if not isinstance(logger, CustomLogger): + raise TypeError(f"Logger {name!r} is not a CustomLogger") + return logger diff --git a/wallpaper_changer/wallpaper_changer/monitor_manager.py b/wallpaper_changer/wallpaper_changer/monitor_manager.py new file mode 100644 index 0000000..4e5c63d --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/monitor_manager.py @@ -0,0 +1,195 @@ +from dataclasses import dataclass +from pathlib import Path +import re +import xml.etree.ElementTree as ET + + +@dataclass(frozen=True) +class Monitor: + width: int + height: int + x: int = 0 + + @property + def aspect_ratio(self) -> float: + return self.height / self.width + + +@dataclass(frozen=True) +class ScreenLayout: + monitors: tuple[Monitor, ...] + + @property + def monitor_count(self) -> int: + return len(self.monitors) + + @property + def screen_aspect_ratio(self) -> float: + return self.monitors[0].height / sum(monitor.width for monitor in self.monitors) + + +class MonitorManager: + def connected(self) -> list[Path]: + monitors = [] + for path in Path("/sys/class/drm").glob("card*-*"): + if (path / "status").read_text().strip() == "connected": + monitors.append(path) + return monitors + + def get_screensize( + self, + host: str, + image_dir: Path, + monitor_config: int = 0, + drm_root: Path = Path("/sys/class/drm"), + monitor_file: Path = Path.home() / ".config/monitors.xml", + lid_state: Path = Path("/proc/acpi/button/lid/LID0/state"), + ) -> ScreenLayout: + if host == "serverhost": + return self._read_server_layout(image_dir, monitor_config) + if host not in {"quiethost", "vivohost"}: + raise ValueError(f"Unsupported monitor host: {host}") + + connectors = self._connected_connectors(host, drm_root, lid_state) + if len(connectors) == 1: + width, height = self._read_virtual_size(connectors[0]) + return ScreenLayout((Monitor(width, height),)) + if not connectors: + raise RuntimeError(f"No enabled monitors found for host {host}") + + active_connectors = { + connector.name.split("-", 1)[1]: connector for connector in connectors + } + active_sizes = { + name: self._read_virtual_size(connector) + for name, connector in active_connectors.items() + } + selected: ScreenLayout | None = None + for configuration in ( + ET.parse(monitor_file).getroot().findall(".//configuration") + ): + logical_monitors = configuration.findall("logicalmonitor") + if len(logical_monitors) != len(connectors): + continue + + layout_monitors = [] + configured_connectors = set() + configuration_matches = True + for logical_monitor in logical_monitors: + connector_names = { + connector.text + for connector in logical_monitor.findall(".//monitorspec/connector") + if connector.text + } + configured_connectors.update(connector_names) + mode = logical_monitor.find("mode") + width = self._xml_integer(mode, "width") + height = self._xml_integer(mode, "height") + x = self._xml_integer(logical_monitor, "x") + if not connector_names or any( + active_sizes.get(name) != (width, height) + for name in connector_names + ): + configuration_matches = False + layout_monitors.append(Monitor(width, height, x)) + + if ( + configuration_matches + and configured_connectors == active_connectors.keys() + ): + selected = ScreenLayout(tuple(layout_monitors)) + + if selected is None: + raise RuntimeError( + f"No matching monitor configuration found in {monitor_file}" + ) + return selected + + @staticmethod + def _connected_connectors( + host: str, + drm_root: Path, + lid_state: Path, + ) -> list[Path]: + cards = sorted( + path + for path in drm_root.glob("card[0-9]*") + if re.fullmatch(r"card\d+", path.name) + ) + + connectors = [] + for card in cards: + for connector in sorted(drm_root.glob(f"{card.name}-*")): + if (connector / "status").read_text().strip() != "connected": + continue + if (connector / "enabled").read_text().strip() != "enabled": + continue + if host == "quiethost" and connector.name.split("-", 1)[-1].startswith( + "eDP" + ): + try: + lid_open = "open" in lid_state.read_text() + except FileNotFoundError: + lid_open = False + if not lid_open: + continue + connectors.append(connector) + return connectors + + @staticmethod + def _read_virtual_size(connector: Path) -> tuple[int, int]: + size_file = connector / "device/device/graphics/fb0/virtual_size" + size = size_file.read_text().strip().split(",") + if len(size) != 2: + raise ValueError(f"Invalid virtual monitor size in {size_file}") + width, height = (int(value) for value in size) + if width <= 0 or height <= 0: + raise ValueError(f"Invalid virtual monitor size in {size_file}") + return width, height + + @staticmethod + def _xml_integer(element: ET.Element | None, child: str) -> int: + value = element.findtext(child) if element is not None else None + if value is None: + raise ValueError(f"Missing <{child}> in monitor configuration") + return int(value) + + @staticmethod + def _read_server_layout(image_dir: Path, monitor_config: int) -> ScreenLayout: + filename = ( + f"monitors{monitor_config}.cfg" if monitor_config > 0 else "monitors.cfg" + ) + config_file = image_dir / ".LOG" / filename + lines = config_file.read_text().splitlines() + + monitor_line = next( + (line for line in lines if line.strip().startswith("Mon")), None + ) + if monitor_line is None: + raise ValueError(f"Missing monitor count in {config_file}") + monitor_count = int(monitor_line.split(":")[-1].strip()) + + def read_axis(axis: str) -> list[int]: + line = next((line for line in lines if line.strip().startswith(axis)), None) + if line is None: + raise ValueError(f"Missing {axis} dimensions in {config_file}") + values = [ + value for value in re.split(r"[:,\s]+", line.strip()[1:]) if value + ] + return [int(value) for value in values] + + widths = read_axis("X") + heights = read_axis("Y") + if ( + monitor_count <= 0 + or len(widths) != monitor_count + or len(heights) != monitor_count + ): + raise ValueError(f"Invalid monitor dimensions in {config_file}") + if any(width <= 0 for width in widths) or any( + height <= 0 for height in heights + ): + raise ValueError(f"Invalid monitor dimensions in {config_file}") + return ScreenLayout( + tuple(Monitor(width, height) for width, height in zip(widths, heights)) + ) diff --git a/wallpaper_changer/wallpaper_changer/naming_table.py b/wallpaper_changer/wallpaper_changer/naming_table.py new file mode 100644 index 0000000..7801d28 --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/naming_table.py @@ -0,0 +1,10 @@ +class NamingTable: + def load(self, path): + d = {} + try: + for l in open(path): + a, b = l.strip().split(";", 1) + d[a] = b + except: + pass + return d diff --git a/wallpaper_changer/wallpaper_changer/wallpaper_builder.py b/wallpaper_changer/wallpaper_changer/wallpaper_builder.py new file mode 100644 index 0000000..df9370b --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/wallpaper_builder.py @@ -0,0 +1,166 @@ +import random +import re +from collections.abc import Mapping, Sequence +from io import BytesIO +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont, ImageOps + +from wallpaper_changer.encryption_manager import EncryptionManager +from wallpaper_changer.logging_utils import get_logger +from wallpaper_changer.monitor_manager import ScreenLayout + +logger = get_logger(__name__) + +class WallpaperBuilder: + + def build( + self, + images: Sequence[Mapping[str, Path | str]], + layout: ScreenLayout, + private_key: str | Path, + search_terms: Sequence[str] | None = None, + exclude: Sequence[str] = (), + output_path: str | Path | None = None, + decode_and_leave: bool = False, + disable_encryption: bool = False, + ) -> Path: + if not images: + raise ValueError("No images are available to build a wallpaper") + if not layout.monitors: + raise ValueError("Cannot build a wallpaper without monitor dimensions") + + selected_images: list[Mapping[str, Path | str]] = [] + for index, monitor in enumerate(layout.monitors): + term = None + if search_terms: + term = ( + search_terms[0] + if len(search_terms) == 1 + else search_terms[index % len(search_terms)] + ) + candidates = self.find_candidates(images, term, exclude) + if not candidates: + raise ValueError(f"No images match search term {term!r}") + + unused_candidates = [ + candidate + for candidate in candidates + if candidate not in selected_images + ] + logger.trace(f"Selected candidates for monitor {index}: {len(candidates)}") + selected_images.append(random.choice(unused_candidates or candidates)) + + left = min(monitor.x for monitor in layout.monitors) + right = max(monitor.x + monitor.width for monitor in layout.monitors) + height = max(monitor.height for monitor in layout.monitors) + canvas = Image.new("RGB", (right - left, height), "black") + draw = ImageDraw.Draw(canvas) + encryption_manager = ( + None if disable_encryption else EncryptionManager() + ) + + for monitor, image_record in zip(layout.monitors, selected_images): + source = self._open_image( + image_record, + private_key, + encryption_manager, + disable_encryption=disable_encryption, + ) + if decode_and_leave: + source.save(Path(image_record["file"]).with_name(image_record["name"])) + logger.debug(f"Leaving decrypted image on disk: {image_record['file']}") + + centering_panorama = [(0,0),(1,0)] + fitted = ImageOps.fit( + source, + (monitor.width, monitor.height), + method=Image.Resampling.LANCZOS, + centering = centering_panorama[random.randint(0,1)] + ) + + monitor_left = monitor.x - left + canvas.paste(fitted, (monitor_left, 0)) + font_size = max(12, monitor.height // 120) + margin_top = 55 + margin_left = 10 + draw.text( + (monitor_left + monitor.width - margin_left, margin_top), + Path(str(image_record["name"])).stem, + font=ImageFont.load_default(size=font_size), + fill="white", + anchor="rb", + stroke_width=1, + stroke_fill="black", + ) + + destination = ( + Path(output_path) + if output_path + else (Path.home() / "Wallpaper" / "current" / "wallpaper.jpg") + ) + destination.parent.mkdir(parents=True, exist_ok=True) + canvas.save(destination, format="JPEG", quality=95) + return destination + + @staticmethod + def find_candidates( + images: Sequence[Mapping[str, Path | str]], + search_term: str | None, + exclude: Sequence[str], + ) -> list[Mapping[str, Path | str]]: + excluded_terms = [term for term in (*exclude, "_decrypted") if term] + + candidates = [ + image + for image in images + if not any( + term.casefold() in str(image["name"]).casefold() + for term in excluded_terms + ) + ] + if search_term: + pattern = WallpaperBuilder._search_pattern(search_term) + matches = [ + image + for image in candidates + if re.search(pattern, str(image["name"]), re.IGNORECASE) + ] + if matches: + candidates = matches + return candidates + + @staticmethod + def _search_pattern(search_term: str) -> str: + number = re.search(r"\d{2}", search_term) + text = re.sub(r"\d", "", search_term) + if number and text: + return f"{re.escape(text)}.*{re.escape(number.group())}" + return re.escape(search_term) + + @staticmethod + def _open_image( + image_record: Mapping[str, Path | str], + private_key: str | Path, + encryption_manager: EncryptionManager | None, + disable_encryption: bool = False, + ) -> Image.Image: + image_path = Path(image_record["file"]) + if image_path.suffix.lower() == ".jpg_enc": + image_data = image_path.read_bytes() + if not image_data.startswith(b"\xff\xd8\xff"): + if disable_encryption: + raise ValueError( + f"Cannot open encrypted image while encryption is disabled: {image_path}" + ) + if encryption_manager is None: + raise RuntimeError("Encryption manager is required to decrypt images") + decrypted = encryption_manager.decrypt(image_path, None, private_key) + if decrypted is None: + raise ValueError(f"Could not decrypt image: {image_path}") + image_data = decrypted + with Image.open(BytesIO(image_data)) as image: + return image.convert("RGB") + + with Image.open(image_path) as image: + return image.convert("RGB") diff --git a/wallpaper_changer/wallpaper_changer/wallpaper_setter.py b/wallpaper_changer/wallpaper_changer/wallpaper_setter.py new file mode 100644 index 0000000..ffdac63 --- /dev/null +++ b/wallpaper_changer/wallpaper_changer/wallpaper_setter.py @@ -0,0 +1,33 @@ +from pathlib import Path +import subprocess + +from wallpaper_changer.logging_utils import get_logger + +logger = get_logger(__name__) + +class WallpaperSetter: + def set_ubuntu(self, path: str | Path) -> None: + wallpaper = path.expanduser().resolve() + if not wallpaper.is_file(): + raise FileNotFoundError(f"Wallpaper does not exist: {wallpaper}") + + uri = wallpaper.as_uri() + for setting, value in ( + ("picture-uri", uri), + ("picture-uri-dark", uri), + ("picture-options", "spanned"), + ): + logger.trace(f"Setting {setting} to {value}") + subprocess.run( + [ + "gsettings", + "set", + "org.gnome.desktop.background", + setting, + value, + ], + check=True, + ) + + def set_gnome(self, path: str | Path) -> None: + self.set_ubuntu(path)