From 4a3f71db1805c315ba2ae6bbed3786ac9049ec12 Mon Sep 17 00:00:00 2001 From: Javierinsitu Date: Thu, 15 Oct 2026 17:41:36 -0300 Subject: [PATCH] feat: add Linux support --- .github/workflows/ci.yml | 3 +- .github/workflows/linux-release.yml | 81 +++++++++++++++++++++ CHANGELOG.md | 18 ++++- README.md | 72 +++++++++++++----- app/acestream/install.py | 49 ++++++++++--- app/config.py | 21 ++++-- app/launcher.py | 2 +- app/services/player.py | 20 +++-- app/web/engine_routes.py | 2 +- app/web/routes.py | 2 +- docs/packaging-linux.md | 34 +++++++++ linux/acelist.spec | 40 ++++++++++ linux/build.py | 64 ++++++++++++++++ linux/entry.py | 6 ++ linux/smoke_test.py | 109 ++++++++++++++++++++++++++++ plan.md | 4 +- pyproject.toml | 2 +- start.sh | 32 ++++++++ tests/test_config.py | 24 +++++- tests/test_linux_packaging.py | 40 ++++++++++ tests/test_player.py | 8 ++ tests/test_settings.py | 20 ++++- tests/test_web_engine_start.py | 14 +++- 23 files changed, 612 insertions(+), 55 deletions(-) create mode 100644 .github/workflows/linux-release.yml create mode 100644 docs/packaging-linux.md create mode 100644 linux/acelist.spec create mode 100644 linux/build.py create mode 100644 linux/entry.py create mode 100644 linux/smoke_test.py create mode 100755 start.sh create mode 100644 tests/test_linux_packaging.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fd90f8..eaf74ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,10 +10,11 @@ permissions: jobs: test: - runs-on: windows-latest + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: + os: [ubuntu-latest, windows-latest] python-version: ["3.11", "3.12"] steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml new file mode 100644 index 0000000..c39ca2e --- /dev/null +++ b/.github/workflows/linux-release.yml @@ -0,0 +1,81 @@ +name: Linux executable + +on: + pull_request: + paths: + - "app/**" + - "migrations/**" + - "linux/**" + - "LICENSE" + - "alembic.ini" + - "pyproject.toml" + - ".github/workflows/linux-release.yml" + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-22.04 + permissions: + contents: write + id-token: write + attestations: write + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install dependencies + run: python -m pip install -e ".[build]" + + - name: Read the version + id: version + shell: bash + run: | + version="$(python -c 'import app; print(app.__version__)')" + echo "version=$version" >> "$GITHUB_OUTPUT" + if [[ "${{ github.event_name }}" == release ]]; then + tag="${{ github.event.release.tag_name }}" + if [[ "$tag" != "v$version" ]]; then + echo "Release tag $tag does not match app.__version__ $version" >&2 + exit 1 + fi + fi + + - name: Build + run: python linux/build.py + + - name: Smoke test + run: python linux/smoke_test.py --expect-version "${{ steps.version.outputs.version }}" + + - uses: actions/upload-artifact@v4 + with: + name: AceList-${{ steps.version.outputs.version }}-linux-x86_64 + path: | + dist/AceList-*-linux-x86_64.tar.gz + dist/AceList-*-linux-x86_64.tar.gz.sha256 + if-no-files-found: error + + - name: Attest provenance + if: github.event_name == 'release' && !github.event.repository.private + uses: actions/attest-build-provenance@v2 + with: + subject-path: dist/AceList-*-linux-x86_64.tar.gz + + - name: Attach to the release + if: github.event_name == 'release' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release upload "${{ github.event.release.tag_name }}" \ + dist/AceList-*-linux-x86_64.tar.gz \ + dist/AceList-*-linux-x86_64.tar.gz.sha256 \ + --clobber diff --git a/CHANGELOG.md b/CHANGELOG.md index a25c511..2f3c140 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,23 @@ Todos los cambios relevantes del proyecto se registran aquí. Formato basado en ## [Sin publicar] ### Agregado -- MIT license (`LICENSE`), declared in `pyproject.toml` and shipped as `LICENSE.txt` next to `AceList.exe` in the Windows zip. +- MIT license (`LICENSE`), declared in `pyproject.toml` and shipped as `LICENSE.txt` in the + Windows and Linux packages. +- Paquete Linux x86-64 en modo carpeta con PyInstaller, tarball versionado, suma SHA-256 y smoke + test del binario contra las páginas principales y una base de datos descartable. +- Workflow de GitHub Actions que construye y prueba el paquete en Ubuntu 22.04, publica el + artefacto en cada cambio pertinente y lo adjunta a las releases con attestación de procedencia. +- `start.sh` crea el entorno virtual, instala o actualiza dependencias cuando cambia + `pyproject.toml` y usa el mismo launcher que el ejecutable. +- Autodetección del engine Linux como `acestreamengine` en `PATH` y en ubicaciones habituales bajo + `/usr` y `/opt`; al iniciarlo usa el modo `--client-console`. +- La matriz de CI ejecuta lint y tests tanto en Ubuntu como en Windows. + +### Cambiado +- El ejecutable guarda sus datos según la plataforma: `%LOCALAPPDATA%\AceList` en Windows y + `$XDG_DATA_HOME/AceList` (o `~/.local/share/AceList`) en Linux. +- Los textos de errores y la documentación ya no suponen que VLC, ffmpeg y Ace Stream terminan en + `.exe`. ## [1.5.0] - 2026-10-11 diff --git a/README.md b/README.md index 85e1bb4..2fabbed 100644 --- a/README.md +++ b/README.md @@ -22,16 +22,48 @@ Catálogo local de enlaces Acestream. Valida el Content ID, comprueba si hay pee ## Requisitos -- Windows 10 u 11 de 64 bits. -- [Ace Stream Media](https://www.acestream.org/) instalado (su engine responde en `http://127.0.0.1:6878`). AceList puede abrirlo con el botón **Iniciar** de la barra superior. +- Linux x86-64 o Windows 10/11 de 64 bits. +- [Ace Stream](https://www.acestream.org/) instalado (su engine debe responder en `http://127.0.0.1:6878`). AceList puede abrirlo con el botón **Iniciar** de la barra superior. - [VLC](https://www.videolan.org/vlc/) para reproducir. - [ffmpeg](https://ffmpeg.org/download.html) para las capturas (opcional: sin ffmpeg los canales se verifican igual, sin imagen). No hace falta instalar Python: el ejecutable lo lleva dentro. -## Instalación +## Instalación en Linux -1. En la página de [releases](https://github.com/fabiomb/AceList/releases/latest), descarga **`AceList--win64.zip`**. +1. En la página de [releases](https://github.com/fabiomb/AceList/releases/latest), descarga **`AceList--linux-x86_64.tar.gz`**. +2. Descomprímelo y ejecuta AceList: + + ```bash + tar -xzf AceList-X.Y.Z-linux-x86_64.tar.gz + cd AceList + ./AceList + ``` + +Se abre el navegador en `http://127.0.0.1:8000/`. Deja la terminal abierta mientras lo uses; +`Ctrl+C` lo detiene. Los datos se guardan en `~/.local/share/AceList` o en +`$XDG_DATA_HOME/AceList`, nunca dentro de la carpeta descomprimida. + +AceList detecta `vlc`, `ffmpeg` y `acestreamengine` en `PATH`. Para el engine también revisa +`/usr/bin`, `/usr/local/bin` y `/opt/acestream`. Si tu instalación usa otra ruta o URL, indícala +en **Ajustes**. El engine también puede quedar iniciado por separado. + +Opciones: + +```bash +./AceList --port 8080 +./AceList --no-browser +``` + +Para verificar la descarga: + +```bash +sha256sum -c AceList-X.Y.Z-linux-x86_64.tar.gz.sha256 +``` + +## Instalación en Windows + +1. En la página de releases, descarga **`AceList--win64.zip`**. 2. Descomprímelo donde quieras, por ejemplo en `Documentos\AceList`. 3. Haz doble clic en **`AceList.exe`**. @@ -47,14 +79,14 @@ AceList todavía no está firmado digitalmente, así que la primera vez Windows Para comprobar que el zip es el original, compara su huella con la del archivo `.sha256` publicado junto a él: ```powershell -Get-FileHash .\AceList-1.3.0-win64.zip -Algorithm SHA256 +Get-FileHash .\AceList-1.5.0-win64.zip -Algorithm SHA256 ``` -### Tus datos +### Tus datos en Windows La base de datos y las capturas se guardan en **`%LOCALAPPDATA%\AceList`** (escribe esa ruta en la barra del Explorador para abrirla), no en la carpeta del programa. Para hacer una copia de seguridad, copia esa carpeta o usa **Exportar** en el listado. -### Actualizar +### Actualizar en Windows Cierra AceList, borra la carpeta del programa y descomprime la versión nueva en su lugar. Tus canales siguen en `%LOCALAPPDATA%\AceList` y la versión nueva actualiza la base de datos sola al arrancar. @@ -65,7 +97,7 @@ Esa versión guarda los datos en la carpeta `data\` del código. Para llevarlos - **Exportar e importar:** en la versión vieja, **Exportar** en el listado; en el ejecutable, sube el archivo en **Importar**. Se pasan los canales con todos sus datos, pero no el historial ni las capturas. - **Copiar la carpeta:** con las dos versiones cerradas, copia el contenido de `data\` (`acelist.db` y `screenshots\`) a `%LOCALAPPDATA%\AceList`. Se pasa todo, incluido el historial. -### Opciones +### Opciones en Windows ```powershell .\AceList.exe --port 8080 # usar ese puerto @@ -74,16 +106,17 @@ Esa versión guarda los datos en la carpeta `data\` del código. Para llevarlos ### Desinstalar -Borra la carpeta del programa. Si tampoco quieres conservar tus canales, borra `%LOCALAPPDATA%\AceList`. +Borra la carpeta del programa. Si tampoco quieres conservar tus canales, borra +`~/.local/share/AceList` en Linux o `%LOCALAPPDATA%\AceList` en Windows. ## Desde el código Si prefieres ejecutarlo desde el código fuente (necesita [Python](https://www.python.org/downloads/) 3.11 o superior): 1. Descarga o clona el repositorio. -2. Haz doble clic en **`start.bat`**. +2. En Linux ejecuta `./start.sh`; en Windows haz doble clic en **`start.bat`**. -La primera vez crea el entorno virtual e instala las dependencias (tarda un minuto). Después aplica las migraciones, arranca el servidor y abre el navegador. Los datos quedan en la carpeta `data\` del repositorio. Desde PowerShell, `.\start.ps1 -Port 8080` usa otro puerto y `.\start.ps1 -NoBrowser` no abre el navegador. +La primera vez crea el entorno virtual e instala las dependencias (tarda un minuto). Después aplica las migraciones, arranca el servidor y abre el navegador. Los datos quedan en la carpeta `data/` del repositorio. En Linux, `./start.sh --port 8080 --no-browser` pasa las opciones al launcher; en PowerShell se usan `-Port 8080` y `-NoBrowser`. ## Uso @@ -113,12 +146,12 @@ Los valores de *Ajustes* se guardan en la base de datos y tienen prioridad. Las | Variable | Por defecto | Uso | |----------|-------------|-----| -| `ACELIST_DATA_DIR` | `%LOCALAPPDATA%\AceList` (ejecutable) o `data` (código) | Carpeta de la base de datos (`acelist.db`) y las capturas (`screenshots/`). | -| `ACELIST_PORT` | `8000` | Puerto local con `start.bat`; el ejecutable usa `--port`. | +| `ACELIST_DATA_DIR` | datos de usuario (ejecutable) o `data` (código) | Carpeta de la base de datos (`acelist.db`) y las capturas (`screenshots/`). En Linux respeta `XDG_DATA_HOME`; en Windows usa `LOCALAPPDATA`. | +| `ACELIST_PORT` | `8000` | Puerto local; el ejecutable y `start.sh` aceptan `--port`. | | `ACELIST_ENGINE_URL` | `http://127.0.0.1:6878` | URL del engine de Ace Stream. | | `ACELIST_ENGINE_TIMEOUT` | `15` | Segundos de espera de cada petición al engine. | -| `ACELIST_VLC_PATH` | autodetección | Ruta de `vlc.exe`. | -| `ACELIST_FFMPEG_PATH` | `PATH` | Ruta de `ffmpeg.exe`. | +| `ACELIST_VLC_PATH` | autodetección | Ruta del ejecutable de VLC. | +| `ACELIST_FFMPEG_PATH` | `PATH` | Ruta del ejecutable de ffmpeg. | | `ACELIST_SCREENSHOT_TIMEOUT` | `30` | Segundos máximos para sacar una captura. | | `ACELIST_CHECK_CONCURRENCY` | `2` | Verificaciones simultáneas en segundo plano. | @@ -138,10 +171,10 @@ No hay usuarios ni contraseñas: no lo expongas a la red. | Síntoma | Qué revisar | |---------|-------------| -| "Ace Stream apagado" en la barra superior | Pulsa **Iniciar**, o abre Ace Stream a mano. Si no hay botón, indica la ruta de `ace_engine.exe` en *Ajustes*. | +| "Ace Stream apagado" en la barra superior | Pulsa **Iniciar**, o abre Ace Stream a mano. Si no hay botón, indica la ruta de su ejecutable en *Ajustes*. | | El indicador está en verde pero todo sale en "Error" | En *Ajustes*, revisa la URL del engine con **Probar conexión**. | -| "No se encontró VLC" | Instala VLC o indica la ruta de `vlc.exe` en *Ajustes*. | -| Canales activos sin captura | ffmpeg no está instalado o no se encuentra: **Autodetectar rutas** en *Ajustes* o indica la ruta de `ffmpeg.exe`. | +| "No se encontró VLC" | Instala VLC o indica la ruta de su ejecutable en *Ajustes*. | +| Canales activos sin captura | ffmpeg no está instalado o no se encuentra: **Autodetectar rutas** en *Ajustes* o indica su ruta. | | "Windows protegió su PC" al abrir `AceList.exe` | Es SmartScreen con un programa sin firma: **Más información → Ejecutar de todos modos** (ver [Aviso de Windows la primera vez](#aviso-de-windows-la-primera-vez)). | | El antivirus bloquea `AceList.exe` | Algunos antivirus desconfían de los programas hechos con PyInstaller (falso positivo). Comprueba el SHA-256 del zip y añade una excepción para la carpeta de AceList. | | La consola se cierra con un mensaje de error | Léelo antes de pulsar Enter: suele ser que no hay puertos libres o que la carpeta de datos no se puede escribir. | @@ -162,7 +195,7 @@ python -m venv .venv Los tests no necesitan el engine ni ffmpeg: el engine se simula con `respx` y nunca se contacta uno real. -Para compilar el ejecutable: `pip install -e ".[build]"` y `python windows\build.py` (ver [docs/packaging.md](docs/packaging.md)). Al publicar una release en GitHub, el CI lo compila, lo prueba y adjunta el zip. +Para compilar los ejecutables: `pip install -e ".[build]"` y `python linux/build.py` en Linux o `python windows/build.py` en Windows. Ver [empaquetado para Linux](docs/packaging-linux.md) y [para Windows](docs/packaging.md). Al publicar una release, el CI compila y prueba ambos artefactos. Stack: Python, FastAPI, SQLite + SQLAlchemy (Alembic), Jinja2 + HTMX, httpx, ffmpeg. Detalle y justificación en [plan.md](plan.md). @@ -185,6 +218,7 @@ El seguimiento se hace con [issues de GitHub](https://github.com/fabiomb/AceList - [idea.md](idea.md): idea original. - [plan.md](plan.md): alcance, arquitectura, modelo de datos y fases. - [docs/engine-api.md](docs/engine-api.md): API del engine de Acestream observada en la práctica. +- [docs/packaging-linux.md](docs/packaging-linux.md): cómo se empaqueta el ejecutable para Linux. - [docs/packaging.md](docs/packaging.md): cómo se empaqueta el ejecutable para Windows. - [CHANGELOG.md](CHANGELOG.md): registro de cambios. diff --git a/app/acestream/install.py b/app/acestream/install.py index 77f2d10..dd24d72 100644 --- a/app/acestream/install.py +++ b/app/acestream/install.py @@ -1,11 +1,20 @@ import os +import shutil import subprocess +import sys from collections.abc import Callable, Iterable from pathlib import Path -def engine_candidates() -> list[Path]: - """Where Ace Stream Media puts its engine on Windows (per user, or for everyone).""" +def engine_candidates(platform: str = sys.platform) -> list[Path]: + """Usual Ace Stream engine locations for the current operating system.""" + if platform != "win32": + return [ + Path("/usr/bin/acestreamengine"), + Path("/usr/local/bin/acestreamengine"), + Path("/opt/acestream/start-engine"), + Path("/opt/acestream/acestreamengine"), + ] found = [] for name in ("APPDATA", "LOCALAPPDATA"): if root := os.environ.get(name): @@ -16,11 +25,15 @@ def engine_candidates() -> list[Path]: return found -def find_engine_executable(candidates: Iterable[Path] | None = None) -> str | None: +def find_engine_executable( + candidates: Iterable[Path] | None = None, *, platform: str = sys.platform +) -> str | None: """Path of the installed engine executable, if Ace Stream is installed.""" - for candidate in engine_candidates() if candidates is None else candidates: + for candidate in engine_candidates(platform) if candidates is None else candidates: if candidate.is_file(): return str(candidate) + if candidates is None and platform != "win32": + return shutil.which("acestreamengine") or shutil.which("start-engine") return None @@ -29,7 +42,10 @@ class EngineStartError(Exception): def start_engine( - path: str, *, launcher: Callable[..., subprocess.Popen] = subprocess.Popen + path: str, + *, + launcher: Callable[..., subprocess.Popen] = subprocess.Popen, + platform: str = sys.platform, ) -> None: """Launches the installed engine and returns at once; it takes a few seconds to answer.""" executable = Path(path) @@ -37,14 +53,25 @@ def start_engine( raise EngineStartError(f"engine executable not found: {path}") try: # An argument list and no shell; detached so it outlives AceList, like VLC. + # The official Linux engine needs an explicit client mode. Windows' GUI + # executable selects it itself. + command = [str(executable)] + if platform != "win32": + command.append("--client-console") + options = { + "stdin": subprocess.DEVNULL, + "stdout": subprocess.DEVNULL, + "stderr": subprocess.DEVNULL, + "close_fds": True, + } + if platform == "win32": + options["creationflags"] = getattr(subprocess, "DETACHED_PROCESS", 0) + else: + options["start_new_session"] = True launcher( - [str(executable)], + command, cwd=str(executable.parent), - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - close_fds=True, - creationflags=getattr(subprocess, "DETACHED_PROCESS", 0), + **options, ) except OSError as exc: raise EngineStartError(f"could not start the engine: {exc}") from exc diff --git a/app/config.py b/app/config.py index ec401d7..feea4bf 100644 --- a/app/config.py +++ b/app/config.py @@ -1,11 +1,11 @@ import os import sys from collections.abc import Mapping -from pathlib import Path +from pathlib import Path, PurePosixPath ROOT_DIR = Path(__file__).resolve().parent.parent -# True inside the Windows executable built with PyInstaller (see docs/packaging.md). +# True inside an executable built with PyInstaller (see docs/packaging.md). FROZEN = bool(getattr(sys, "frozen", False)) @@ -17,7 +17,11 @@ def resource_dir(frozen: bool = FROZEN) -> Path: return Path(getattr(sys, "_MEIPASS", ROOT_DIR)) if frozen else ROOT_DIR -def default_data_dir(frozen: bool = FROZEN, environ: Mapping[str, str] = os.environ) -> Path: +def default_data_dir( + frozen: bool = FROZEN, + environ: Mapping[str, str] = os.environ, + platform: str = sys.platform, +) -> Path: """Where the database and screenshots go unless `ACELIST_DATA_DIR` says otherwise. The executable keeps them in the user's profile, so replacing the program folder on @@ -25,8 +29,15 @@ def default_data_dir(frozen: bool = FROZEN, environ: Mapping[str, str] = os.envi """ if not frozen: return ROOT_DIR / "data" - local = environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local") - return Path(local) / "AceList" + if platform == "win32": + local = environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local") + return Path(local) / "AceList" + # Follow the XDG base-directory convention used by Linux desktops. An absolute + # XDG_DATA_HOME is required by the specification; ignore a malformed relative one. + xdg_value = environ.get("XDG_DATA_HOME") + xdg = Path(xdg_value) if xdg_value and PurePosixPath(xdg_value).is_absolute() else None + base = xdg if xdg else Path.home() / ".local" / "share" + return base / "AceList" RESOURCE_DIR = resource_dir() diff --git a/app/launcher.py b/app/launcher.py index 7f906d9..3049728 100644 --- a/app/launcher.py +++ b/app/launcher.py @@ -1,4 +1,4 @@ -"""AceList.exe: prepares the database, starts the local server and opens the browser. +"""AceList launcher: prepares the database, starts the local server and opens the browser. Also runs from source with `python -m app.launcher`. Messages are for the person who double-clicked the program, so they are in Spanish. diff --git a/app/services/player.py b/app/services/player.py index 475f7f7..5633296 100644 --- a/app/services/player.py +++ b/app/services/player.py @@ -1,6 +1,7 @@ import os import shutil import subprocess +import sys from collections.abc import Callable, Iterable from pathlib import Path from urllib.parse import urlsplit @@ -56,7 +57,7 @@ def open_in_player( content_id = parse_content_id(content_id) vlc = vlc_path or find_vlc() if not vlc: - raise VlcNotFoundError("VLC not found: install it or set ACELIST_VLC_PATH to vlc.exe") + raise VlcNotFoundError("VLC not found: install it or set ACELIST_VLC_PATH") stream = client.start_stream(content_id, kind) if urlsplit(stream.playback_url).scheme not in ("http", "https"): @@ -70,14 +71,19 @@ def open_in_player( command.append(f"--meta-title={title}") command.append(stream.playback_url) try: + options = { + "stdin": subprocess.DEVNULL, + "stdout": subprocess.DEVNULL, + "stderr": subprocess.DEVNULL, + "close_fds": True, + } + if sys.platform == "win32": + options["creationflags"] = getattr(subprocess, "DETACHED_PROCESS", 0) + else: + options["start_new_session"] = True launcher( command, - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - close_fds=True, - # On Windows VLC must outlive the app's console; elsewhere the flag is 0. - creationflags=getattr(subprocess, "DETACHED_PROCESS", 0), + **options, ) except OSError as exc: _stop_quietly(client, stream) diff --git a/app/web/engine_routes.py b/app/web/engine_routes.py index 55b923e..259f63a 100644 --- a/app/web/engine_routes.py +++ b/app/web/engine_routes.py @@ -68,7 +68,7 @@ def engine_start(request: Request, probe: EngineProbeDep, settings: SettingsDep) return _indicator(request, settings, version) # already running executable = engine_executable(settings) if executable is None: - error = "No se encontró ace_engine.exe: indica su ruta en Ajustes." + error = "No se encontró el ejecutable de Ace Stream: indica su ruta en Ajustes." return _indicator(request, settings, None, error=error) try: install.start_engine(executable) diff --git a/app/web/routes.py b/app/web/routes.py index 6eee6b4..655599f 100644 --- a/app/web/routes.py +++ b/app/web/routes.py @@ -390,7 +390,7 @@ def play( client, content_id, kind=kind, title=title, vlc_path=settings.vlc_path ) except player.VlcNotFoundError: - error = "No se encontró VLC. Instálalo o indica la ruta de vlc.exe en Ajustes." + error = "No se encontró VLC. Instálalo o indica la ruta del ejecutable en Ajustes." except ContentNotFoundError: error = "El engine no pudo cargar este Content ID: puede que el enlace haya muerto." except EngineError: diff --git a/docs/packaging-linux.md b/docs/packaging-linux.md new file mode 100644 index 0000000..872d786 --- /dev/null +++ b/docs/packaging-linux.md @@ -0,0 +1,34 @@ +# Empaquetado para Linux + +AceList se distribuye para Linux x86-64 en modo carpeta de PyInstaller. El tarball contiene +`AceList/AceList`, `AceList/_internal/` y `AceList/LICENSE.txt`, incluyendo Python, dependencias, +plantillas, estáticos y migraciones. VLC, ffmpeg y Ace Stream Engine siguen siendo programas +externos. + +## Compilar + +En una distribución Linux x86-64 con Python 3.11 o posterior: + +```bash +python3 -m venv .venv +.venv/bin/python -m pip install -e '.[build]' +.venv/bin/python linux/build.py +.venv/bin/python linux/smoke_test.py --expect-version 1.5.0 +``` + +El resultado queda en `dist/AceList--linux-x86_64.tar.gz`, acompañado por su SHA-256. +El binario debe construirse en Linux: PyInstaller no genera binarios de otra plataforma. + +Los datos del ejecutable no se escriben en el paquete. Se guardan en +`$XDG_DATA_HOME/AceList` o, si esa variable no existe, en `~/.local/share/AceList`. + +## Compatibilidad + +El artefacto de release se construye y prueba en Ubuntu. PyInstaller incorpora el intérprete de +Python, pero no glibc; por eso un binario construido en una distribución reciente puede no correr +en otra mucho más antigua. `start.sh` es la alternativa portable para cualquier distribución con +Python 3.11 o posterior. + +AceList busca el engine en `PATH` con el nombre `acestreamengine`, y también en `/usr/bin`, +`/usr/local/bin` y `/opt/acestream`. Al iniciarlo añade `--client-console`. También se puede dejar +el engine ejecutándose por separado o indicar otra ruta y URL en Ajustes. diff --git a/linux/acelist.spec b/linux/acelist.spec new file mode 100644 index 0000000..e3cf497 --- /dev/null +++ b/linux/acelist.spec @@ -0,0 +1,40 @@ +# PyInstaller spec for the Linux executable, in folder mode. Build with `python linux/build.py`. +from pathlib import Path + +ROOT = Path(SPECPATH).parent # noqa: F821 - SPECPATH is provided by PyInstaller + +datas = [ + (str(ROOT / "app" / "web" / "templates"), "app/web/templates"), + (str(ROOT / "app" / "web" / "static"), "app/web/static"), + (str(ROOT / "migrations"), "migrations"), + (str(ROOT / "alembic.ini"), "."), +] + +a = Analysis( # noqa: F821 + [str(ROOT / "linux" / "entry.py")], + pathex=[str(ROOT)], + datas=datas, + excludes=["tkinter", "pytest", "respx", "PIL"], +) + + +def _keep(entry) -> bool: + parts = Path(entry[0]).parts + if "__pycache__" in parts: + return False + return not ("pycountry" in parts and "locales" in parts) + + +a.datas = [entry for entry in a.datas if _keep(entry)] + +pyz = PYZ(a.pure) # noqa: F821 +exe = EXE( # noqa: F821 + pyz, + a.scripts, + [], + exclude_binaries=True, + name="AceList", + console=True, + upx=False, +) +coll = COLLECT(exe, a.binaries, a.datas, name="AceList", upx=False) # noqa: F821 diff --git a/linux/build.py b/linux/build.py new file mode 100644 index 0000000..45cb1ce --- /dev/null +++ b/linux/build.py @@ -0,0 +1,64 @@ +"""Builds AceList for 64-bit Linux and packs it as a tar.gz archive. + +Leaves in ``dist/``: +- ``AceList/`` with ``AceList``, ``_internal/`` and ``LICENSE.txt``; +- the versioned tarball and its SHA-256 checksum. +""" + +import hashlib +import re +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +DIST = ROOT / "dist" +WORK = ROOT / "build" +SPEC = ROOT / "linux" / "acelist.spec" + + +def version() -> str: + text = (ROOT / "app" / "__init__.py").read_text(encoding="utf-8") + return re.search(r'__version__ = "([^"]+)"', text).group(1) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as file: + for chunk in iter(lambda: file.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def main() -> Path: + subprocess.run( + [ + sys.executable, + "-m", + "PyInstaller", + "--noconfirm", + "--clean", + "--distpath", + str(DIST), + "--workpath", + str(WORK), + str(SPEC), + ], + check=True, + cwd=ROOT, + ) + shutil.copyfile(ROOT / "LICENSE", DIST / "AceList" / "LICENSE.txt") + name = f"AceList-{version()}-linux-x86_64" + archive = Path( + shutil.make_archive(str(DIST / name), "gztar", root_dir=DIST, base_dir="AceList") + ) + checksum = archive.with_name(archive.name + ".sha256") + checksum.write_text(f"{sha256(archive)} {archive.name}\n", encoding="utf-8") + size = archive.stat().st_size / (1024 * 1024) + print(f"\n{archive} ({size:.1f} MB)\n{checksum.read_text(encoding='utf-8').strip()}") + return archive + + +if __name__ == "__main__": + main() diff --git a/linux/entry.py b/linux/entry.py new file mode 100644 index 0000000..3569072 --- /dev/null +++ b/linux/entry.py @@ -0,0 +1,6 @@ +"""Entry point of the Linux AceList executable (see acelist.spec).""" + +from app.launcher import run + +if __name__ == "__main__": + run() diff --git a/linux/smoke_test.py b/linux/smoke_test.py new file mode 100644 index 0000000..041ebb3 --- /dev/null +++ b/linux/smoke_test.py @@ -0,0 +1,109 @@ +"""Starts the built Linux executable with throwaway data and checks its web UI.""" + +import argparse +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +STARTUP_TIMEOUT = 90.0 + + +def free_port() -> int: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def get(url: str) -> tuple[int, bytes]: + with urllib.request.urlopen(url, timeout=5) as response: # noqa: S310 - loopback only + return response.status, response.read() + + +def wait_for_health(base: str, process: subprocess.Popen) -> dict: + deadline = time.monotonic() + STARTUP_TIMEOUT + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError(f"AceList exited with code {process.returncode}") + try: + status, body = get(f"{base}/health") + if status == 200: + return json.loads(body) + except OSError: + pass + time.sleep(0.5) + raise RuntimeError(f"no answer from {base}/health in {STARTUP_TIMEOUT:g} s") + + +def check(executable: Path, expected_version: str | None) -> None: + data = Path(tempfile.mkdtemp(prefix="acelist-smoke-")) + port = free_port() + base = f"http://127.0.0.1:{port}" + env = { + **os.environ, + "ACELIST_DATA_DIR": str(data), + "ACELIST_ENGINE_URL": "http://127.0.0.1:1", + } + process = subprocess.Popen( + [str(executable), "--no-browser", "--port", str(port)], + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + try: + health = wait_for_health(base, process) + print(f"health: {health}") + if health.get("app") != "AceList": + raise RuntimeError(f"not AceList answering: {health}") + if expected_version and health.get("version") != expected_version: + raise RuntimeError(f"version {health.get('version')}, expected {expected_version}") + for path in ( + "/", + "/gallery", + "/import", + "/explore", + "/explore/sources", + "/settings", + "/static/style.css", + ): + status, _ = get(base + path) + print(f"{path}: {status}") + if status != 200: + raise RuntimeError(f"{path} answered {status}") + if not (data / "acelist.db").is_file(): + raise RuntimeError("the database was not created") + finally: + process.kill() + try: + output, _ = process.communicate(timeout=30) + print("--- AceList output ---") + print(output.decode("utf-8", errors="replace")) + finally: + shutil.rmtree(data, ignore_errors=True) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--exe", type=Path, default=ROOT / "dist" / "AceList" / "AceList") + parser.add_argument("--expect-version") + args = parser.parse_args(argv) + sys.stdout.reconfigure(errors="backslashreplace") + try: + check(args.exe, args.expect_version) + except Exception as exc: # noqa: BLE001 - report any failure and fail the job + print(f"SMOKE TEST FAILED: {exc}") + return 1 + print("smoke test passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plan.md b/plan.md index 1c8e46b..15a98e0 100644 --- a/plan.md +++ b/plan.md @@ -12,12 +12,12 @@ Aplicación local para catalogar enlaces Acestream (Content ID), verificar si si - Listado, edición, borrado, orden y filtros. - Categoría, idioma y país por canal. - Botón para abrir el canal en un reproductor externo (VLC). -- Funcionamiento en Windows con Ace Stream Media Center instalado. +- Funcionamiento en Windows y Linux con Ace Stream Engine instalado. **Fuera de alcance (por ahora)** - Acceso remoto, multiusuario, autenticación. -- Empaquetado para macOS/Linux (se evita código específico de Windows donde sea posible). +- Empaquetado para macOS. - Descubrimiento automático de canales. ## 2. Decisiones de arquitectura diff --git a/pyproject.toml b/pyproject.toml index 4dd6947..31a5574 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dev = [ "respx>=0.21", "ruff>=0.6", ] -# To build the Windows executable (windows/build.py) and redraw its icon. +# To build the Windows or Linux executable and redraw the Windows icon. build = [ "pyinstaller==6.22.3", "pillow>=10", diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..f16a33a --- /dev/null +++ b/start.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" + +if [[ ! -x .venv/bin/python ]]; then + python_command="" + for candidate in python3 python; do + if command -v "$candidate" >/dev/null 2>&1 \ + && "$candidate" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))'; then + python_command="$candidate" + break + fi + done + if [[ -z "$python_command" ]]; then + echo "Hace falta Python 3.11 o superior." >&2 + exit 1 + fi + echo "==> Creando el entorno virtual (.venv)" + "$python_command" -m venv .venv +fi + +marker=.venv/acelist-installed.txt +wanted="$(sha256sum pyproject.toml | cut -d ' ' -f 1)" +installed="$(test -f "$marker" && sed -n '1p' "$marker" || true)" +if [[ "$installed" != "$wanted" ]]; then + echo "==> Instalando AceList y sus dependencias" + .venv/bin/python -m pip install --disable-pip-version-check --quiet --editable . + printf '%s\n' "$wanted" > "$marker" +fi + +exec .venv/bin/python -m app.launcher "$@" diff --git a/tests/test_config.py b/tests/test_config.py index 070d0b5..d54f670 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -10,18 +10,38 @@ def test_from_source_the_data_stays_in_the_repository(): def test_the_executable_keeps_data_in_the_user_profile(): data_dir = config.default_data_dir( - frozen=True, environ={"LOCALAPPDATA": r"C:\Users\u\AppData\Local"} + frozen=True, environ={"LOCALAPPDATA": r"C:\Users\u\AppData\Local"}, platform="win32" ) assert data_dir == Path(r"C:\Users\u\AppData\Local") / "AceList" def test_without_localappdata_the_profile_is_found_anyway(): - data_dir = config.default_data_dir(frozen=True, environ={}) + data_dir = config.default_data_dir(frozen=True, environ={}, platform="win32") assert data_dir == Path.home() / "AppData" / "Local" / "AceList" +def test_linux_executable_uses_xdg_data_home(): + data_dir = config.default_data_dir( + frozen=True, environ={"XDG_DATA_HOME": "/home/u/.data"}, platform="linux" + ) + + assert data_dir == Path("/home/u/.data/AceList") + + +def test_linux_executable_falls_back_to_the_standard_user_data_folder(): + assert config.default_data_dir(frozen=True, environ={}, platform="linux") == ( + Path.home() / ".local" / "share" / "AceList" + ) + + +def test_linux_ignores_a_relative_xdg_data_home(): + assert config.default_data_dir( + frozen=True, environ={"XDG_DATA_HOME": "relative"}, platform="linux" + ) == (Path.home() / ".local" / "share" / "AceList") + + def test_resources_come_from_the_repository_when_running_from_source(): assert config.resource_dir(frozen=False) == config.ROOT_DIR assert (config.resource_dir(frozen=False) / "migrations" / "env.py").is_file() diff --git a/tests/test_linux_packaging.py b/tests/test_linux_packaging.py new file mode 100644 index 0000000..43e28c2 --- /dev/null +++ b/tests/test_linux_packaging.py @@ -0,0 +1,40 @@ +"""Static checks for the Linux package; CI also builds and runs the artifact.""" + +import importlib.util +import re +from pathlib import Path + +from app import __version__ + +ROOT = Path(__file__).resolve().parent.parent +LINUX = ROOT / "linux" +SPEC = (LINUX / "acelist.spec").read_text(encoding="utf-8") + + +def load_build_script(): + spec = importlib.util.spec_from_file_location("acelist_linux_build", LINUX / "build.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_every_file_the_linux_spec_bundles_exists(): + sources = re.findall(r"\(str\((ROOT / [^)]+)\),", SPEC) + paths = [ROOT.joinpath(*re.findall(r'"([^"]+)"', source)) for source in sources] + + assert len(paths) == 4 + assert all(path.exists() for path in paths), paths + + +def test_the_linux_build_reads_the_app_version(): + assert load_build_script().version() == __version__ + + +def test_the_linux_build_ships_the_license(): + assert 'shutil.copyfile(ROOT / "LICENSE", DIST / "AceList" / "LICENSE.txt")' in ( + LINUX / "build.py" + ).read_text(encoding="utf-8") + + +def test_linux_source_launcher_is_executable(): + assert (ROOT / "start.sh").stat().st_mode & 0o111 diff --git a/tests/test_player.py b/tests/test_player.py index 95daeaa..d62b82d 100644 --- a/tests/test_player.py +++ b/tests/test_player.py @@ -1,3 +1,5 @@ +import sys + import httpx import pytest @@ -114,6 +116,12 @@ def test_opens_the_playback_url_in_vlc_without_a_shell(client, engine, vlc): [(command, kwargs)] = launcher.calls assert command == [vlc, "--meta-title=Canal", PLAYBACK] assert "shell" not in kwargs + if sys.platform == "win32": + assert "creationflags" in kwargs + assert "start_new_session" not in kwargs + else: + assert kwargs["start_new_session"] is True + assert "creationflags" not in kwargs assert stream.content_id == HASH assert engine.getstream.calls.last.request.url.params["id"] == HASH # VLC is now reading the session: it must not be stopped. diff --git a/tests/test_settings.py b/tests/test_settings.py index 0a65e8d..0fe5a0b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,3 +1,5 @@ +from pathlib import Path + from app.acestream.install import engine_candidates, find_engine_executable from app.db.models import Setting from app.services.settings import AppSettings, load_settings, save_settings @@ -63,7 +65,7 @@ def test_engine_candidates_cover_appdata_and_program_files(monkeypatch): monkeypatch.setenv("ProgramFiles", "C:/PF") monkeypatch.delenv("ProgramFiles(x86)", raising=False) - found = [path.as_posix() for path in engine_candidates()] + found = [path.as_posix() for path in engine_candidates("win32")] assert found == [ "C:/Users/u/AppData/Roaming/ACEStream/engine/ace_engine.exe", @@ -72,6 +74,22 @@ def test_engine_candidates_cover_appdata_and_program_files(monkeypatch): ] +def test_linux_engine_candidates_cover_system_and_opt_locations(): + assert engine_candidates("linux") == [ + Path("/usr/bin/acestreamengine"), + Path("/usr/local/bin/acestreamengine"), + Path("/opt/acestream/start-engine"), + Path("/opt/acestream/acestreamengine"), + ] + + +def test_linux_engine_can_be_found_on_path(monkeypatch): + monkeypatch.setattr("app.acestream.install.shutil.which", lambda name: f"/custom/{name}") + + assert find_engine_executable([], platform="linux") is None + assert find_engine_executable(platform="linux") == "/custom/acestreamengine" + + def test_find_engine_returns_the_first_existing_candidate(tmp_path): exe = tmp_path / "ace_engine.exe" exe.write_bytes(b"") diff --git a/tests/test_web_engine_start.py b/tests/test_web_engine_start.py index 3759001..72ff502 100644 --- a/tests/test_web_engine_start.py +++ b/tests/test_web_engine_start.py @@ -57,7 +57,7 @@ def probe(self): def test_start_engine_launches_it_without_a_shell(exe): launcher = Launcher() - start_engine(exe, launcher=launcher) + start_engine(exe, launcher=launcher, platform="win32") [(command, kwargs)] = launcher.calls assert command == [exe] @@ -65,6 +65,16 @@ def test_start_engine_launches_it_without_a_shell(exe): assert kwargs["cwd"].endswith("engine") +def test_start_engine_uses_console_mode_on_linux(exe): + launcher = Launcher() + + start_engine(exe, launcher=launcher, platform="linux") + + [(command, _)] = launcher.calls + assert command == [exe, "--client-console"] + assert launcher.calls[0][1]["start_new_session"] is True + + def test_start_engine_needs_the_file(tmp_path): with pytest.raises(EngineStartError, match="not found"): start_engine(str(tmp_path / "missing.exe"), launcher=Launcher()) @@ -140,7 +150,7 @@ def test_start_without_an_executable_says_where_to_set_it(web, engine, monkeypat fragment = web.post("/engine/start").text - assert "No se encontró ace_engine.exe" in fragment + assert "No se encontró el ejecutable de Ace Stream" in fragment assert engine.launched == []