Metadata-Version: 2.5
Name: amarok-ytmusic
Version: 0.1.1
Summary: YouTube Music streaming, offline cache & web-auth integration bridge for Amarok 3.3+ (KDE)
Project-URL: Homepage, https://github.com/gerosalesc/amarok-ytmusic
Project-URL: Repository, https://github.com/gerosalesc/amarok-ytmusic
Project-URL: Issues, https://github.com/gerosalesc/amarok-ytmusic/issues
Author-email: German Rosales <rosalesgermane@gmail.com>
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Keywords: amarok,ampache,kde,mpris,music,streaming,youtube-music,ytmusic
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio :: Players
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.115.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: jeepney>=0.9.0
Requires-Dist: mutagen>=1.48.1
Requires-Dist: uvicorn[standard]>=0.32.0
Requires-Dist: yt-dlp[default]>=2026.11.23
Requires-Dist: ytmusicapi>=1.9.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Description-Content-Type: text/markdown

# amarok-ytmusic

**YouTube Music Web-Auth & Streaming Integration for Amarok 3.3+ on KDE Plasma**

`amarok-ytmusic` connects your **YouTube Music** account (Liked Music, Library Songs, Quick Picks, Playlists, Saved Albums, and live catalog search) directly into **Amarok 3.3+** (Flatpak or native) using a local Web Auth dashboard and an HTTP byte-range streaming proxy.

---

## Features

- **Native Amarok Integration (`Ampache (YouTube Music)`)**:
  - Uses Amarok 3.3's compiled C++/KF6 `amarok_service_ampache` plugin—no KF6 C++ compilation required and immune to Amarok 3.3.3's upstream `KPluginMetaData` JS script-loader bug.
  - Browses **★ My Library** (*Liked Music*, *Library Songs*, *Quick Picks & Home*), **♫ My Playlists**, **◎ Saved Albums**, **⬇ Offline Cache** (*All Offline Songs*, *Offline Liked Songs*, plus offline search fallback), and live search via Amarok's filter bar.
- **Local Web Authentication Dashboard (`http://127.0.0.1:18732`)**:
  - **1-Click Browser Session Sync**: Sign in at `https://music.youtube.com` in Chrome, Chromium, Firefox, Brave, Vivaldi, or Edge (with full Google 2FA & passkey support) and sync session cookies locally in one click (supports KDE `KWallet 5/6` and `GNOME Keyring`).
  - **Paste Request Headers**: Universal DevTools fallback.
  - **Google OAuth (TV Client)**: Optional device-code flow.
  - All credentials are stored strictly locally in `~/.config/amarok-ytmusic/` with `0600` permissions.
- **Never-Expiring Playlist Streams, Anti-Throttling Proxy & GStreamer Seeking**:
  - Every track gets a permanent local proxy URL (`http://127.0.0.1:18732/stream/<videoId>`), so saved Amarok playlists never expire.
  - Resolves fresh YouTube audio URLs just-in-time via `yt-dlp[default]` (`yt-dlp-ejs` + auto-discovered `deno`/`node`/`bun` JS runtime for YouTube Music Premium 256+ kbps streams, with automatic cookie-less fallback when no JS runtime is installed and automatic retry if an upstream signed URL expires with `HTTP 403/410`).
  - Streams upstream YouTube CDN audio in 512 KiB HTTP `Range` chunks to bypass YouTube's single-connection throttling (~32 KB/s) and pause timeouts, while exposing full `HTTP 206 Partial Content` (`Range` / `Accept-Ranges: bytes`) seeking to Amarok's GStreamer engine.
  - **Amarok-Safe Skip Guard**: If a track is genuinely deleted or region-blocked, returns a 120 ms silent WAV (`audio/wav`) to Amarok/GStreamer so it hits a clean `EOS` and advances to the next track instead of triggering Amarok 3.3.3's `EngineGstPipeline::cb_error()` wedge bug (non-Amarok HTTP clients still receive standard `404`/`502`).
- **MPRIS2 Live Sync, Scrobbling, Two-Way Ratings & Lyrics**:
  - Monitors Amarok's `org.mpris.MediaPlayer2.Player` D-Bus interface in real time (`mpris_monitor.py`).
  - **YouTube Music History Scrobbling**: Automatically reports tracks played in Amarok (`>= 15s`) to your YouTube Music listening history so your recommendations stay up to date.
  - **Two-Way Like / Fine-Grained Star Rating Sync**: Click any star (0–5★ / half-stars) directly inside Amarok's **Current Track** panel—even when playing from `Ampache (YouTube Music)`—to persist exact ratings locally, tag imported `.m4a` files (`FMPS_Rating`), and sync 4–5★ Likes / 1★ Dislikes back to YouTube Music.
  - **Live Local Score, Play History, Cover Art & Lyrics in Amarok Context Applets**:
    - Installs user-level KDE `KPackage` overrides for Amarok's **Current Track** (`org.kde.amarok.currenttrack`) and **Lyrics** (`org.kde.amarok.lyrics`) applets (`~/.var/app/org.kde.amarok/data/kpackage/amarok/`).
    - Because Amarok 3.3.3's `AmpacheTrack` returns an empty dummy `Statistics` object, the enhanced **Current Track** applet bridges live local history (`Play Count`, Amarok `Score`, `Last played`), clickable 5-star rating, high-res cover art, and real artist/album names straight from SQLite + Amarok's Local Collection D-Bus (`org.kde.amarok.Collection.Query`)—while leaving non-YouTube local tracks 100% stock.
    - The enhanced **Lyrics** applet displays YouTube Music lyrics directly inside Amarok's built-in Lyrics pane whenever Amarok's built-in lyrics engine is empty.
  - **Persistent Ampache IDs**: Saves assigned album/song IDs in `~/.config/amarok-ytmusic/ampache_state.json` so queued tracks and collection IDs survive daemon restarts.
  - **Offline Song Cache, Automated On-Play Import & Local-First Playback**:
    - Every time a YouTube Music song is played, automatically fetches & caches rich metadata (`title`, `artist`, `album`, `year`, high-res cover art, lyrics, `likeStatus`, `inLibrary`) plus user playback statistics (`play_count`, `score`, `first_played`, `last_played`) in SQLite (`~/.config/amarok-ytmusic/metadata_cache.db`).
    - Caches your user profile info locally so dashboard loads are instant.
    - Automatically downloads and embeds full MP4 metadata (`©nam`, `©ART`, `©alb`, `©day`, `©lyr`, `covr` cover art, `©cmt=ytmusic:<videoId>`, and Amarok's native `FMPS_Rating`, `FMPS_Playcount`, `FMPS_Rating_Amarok_Score` atoms) into your configurable offline cache folder (default `~/Music/YouTube Music/<Artist>/<Album>/<Title>.m4a`, unlimited retention by default with optional MB cap, folder migration, and folder re-indexing).
    - **Zero-Latency Offline & Online Replay**: `/stream/<videoId>` checks your local offline cache first and streams directly from disk with full HTTP `Range` seeking and zero-copy on-the-fly MP4 tag masking (`udta` → `free` in the HTTP response only, leaving the tagged `.m4a` on disk untouched) so saved Amarok playlists and Ampache tracks play 100% offline without triggering Amarok's GStreamer 0:00 `MetaStream::Track` bug.
  - **Live Lyrics**: View lyrics for the currently playing Amarok track from the Web UI (`http://127.0.0.1:18732`) or CLI (`amarok-ytmusic lyrics`).
- **Future-Ready `ScriptableService` Included**:
  - Also ships `amarok_script/` (`main.js`, `script.json`, `script.spec`) and an atomic directory/file IPC watcher (`ipc_watcher.py`) ready for future Amarok 3.x releases once upstream fixes `ScriptManager::loadScript()` to call `KPluginMetaData::fromJsonFile()`.

---

## Architecture

```mermaid
flowchart LR
    subgraph Amarok["Amarok 3.3+ (Flatpak / Native)"]
        UI["Internet → Ampache (YouTube Music)"]
        GST["GStreamer Engine (souphttpsrc)"]
    end

    subgraph Daemon["amarok-ytmusic Daemon (127.0.0.1:18732)"]
        WEB["Web Auth & Control UI (/)"]
        AMP["Ampache XML Bridge (/ampache/server/xml.server.php)"]
        CAT["YTMusicCatalogClient (TTL Cache)"]
        STR["Range Stream Proxy (/stream/{videoId})"]
        RES["StreamResolver (yt-dlp + TTL Cache)"]
        AUTH["AuthManager (~/.config/amarok-ytmusic/)"]
    end

    subgraph External["External Services"]
        BROWSER["Local Browser Cookies (Chrome / Firefox / KWallet)"]
        YTM["YouTube Music Innertube API"]
        GVID["googlevideo.com Audio Streams"]
    end

    WEB --> AUTH
    BROWSER --> AUTH
    UI <-->|"Ampache XML API"| AMP
    AMP --> CAT
    CAT --> AUTH
    CAT <--> YTM
    GST <-->|"HTTP GET/HEAD + Range (206)"| STR
    STR --> RES
    RES <--> YTM
    STR <-->|"Chunked Audio Stream"| GVID
```

---

## Prerequisites

- **Linux / KDE Plasma** with **Amarok 3.3+**:
  ```bash
  flatpak install flathub org.kde.amarok
  ```
- **Python 3.11+** and **[uv](https://docs.astral.sh/uv/)** package manager.
- *(Recommended for YouTube Music Premium)* **`deno`** (e.g. `curl -fsSL https://deno.land/install.sh | sh`) or `nodejs` on `PATH` (or `~/.deno/bin`, auto-discovered by the daemon) so `yt-dlp-ejs` can run cookie-authenticated extraction for YouTube Music Premium-only tracks (up to 273 kbps Opus / 258 kbps AAC) and private uploads. Public/non-Premium tracks still stream without a JS runtime.

---

## Quick Installation

### Option 1: PyPI via `uv` or `pipx` (Recommended — Any Linux Distro)

```bash
# With uv
uv tool install amarok-ytmusic
amarok-ytmusic setup

# Or with pipx
pipx install amarok-ytmusic
amarok-ytmusic setup
```

To upgrade later (including pulling the latest `yt-dlp`):
```bash
uv tool upgrade amarok-ytmusic && amarok-ytmusic setup
```

### Option 2: Arch Linux / AUR

```bash
yay -S amarok-ytmusic   # or: paru -S amarok-ytmusic
amarok-ytmusic setup --no-service
systemctl --user enable --now amarok-ytmusic.service
```

### Option 3: From Source

```bash
git clone https://github.com/gerosalesc/amarok-ytmusic.git
cd amarok-ytmusic
chmod +x install.sh
./install.sh
```

What `amarok-ytmusic setup` (and `./install.sh`) does:
1. Enables `amarok_service_ampache` and adds the **`YouTube Music`** server (`http://127.0.0.1:18732/ampache`) to `~/.var/app/org.kde.amarok/config/amarokrc` and/or `~/.config/amarokrc`.
2. Installs the enhanced Amarok Context Applets (**Current Track** + **Lyrics**) and `ScriptableService` files.
3. Installs, enables, and starts the **`amarok-ytmusic.service`** background daemon via `systemd --user` (unless `--no-service` is passed).

To remove the Amarok integration and systemd service later (preserving your offline music cache and config):
```bash
amarok-ytmusic uninstall
```

---

## Step-by-Step Usage

### 1. Authenticate with YouTube Music
Open **http://127.0.0.1:18732** in your browser:
- **1-Click Browser Session (Recommended)**:
  1. Make sure you are signed in at [music.youtube.com](https://music.youtube.com) in your desktop browser (Chrome, Chromium, Firefox, Brave, etc.).
  2. Select your browser in the dropdown and click **Connect Browser Session**.
- **Alternative (CLI)**:
  ```bash
  amarok-ytmusic auth --browser chrome
  ```
- **Alternative (Paste Request Headers)**:
  Open `music.youtube.com` → `F12` (Network tab) → filter by `/browse` → copy Request Headers from any `POST` to `/youtubei/v1/browse` and paste them into the **Paste Request Headers** tab.

### 2. Launch (or Restart) Amarok
> [!IMPORTANT]
> Closing Amarok's window with the `×` button only hides it to the KDE system tray (`HiddenOnExit=true`). Use **Amarok → Quit (`Ctrl+Q`)** before relaunching so Amarok reloads its configuration.

```bash
flatpak run org.kde.amarok
```

### 3. Browse & Stream in Amarok
1. In Amarok's left pane, navigate to **Media Sources → Internet → Ampache (YouTube Music)**.
2. Expand any category:
   - **`★ YouTube Music — My Library`** → *Liked Music*, *Library Songs*, *Quick Picks & Home*
   - **`♫ YouTube Music — My Playlists`** → All your personal playlists
   - **`◎ YouTube Music — Saved Albums`** → Albums saved in your library
3. Or type any artist/song into the **Enter search terms here** filter box at the top of the pane to search YouTube Music live:
   - Returns **real matching Artists** (expand any artist to browse their **★ Top Songs**, complete **Albums** with release years, and **Singles & EPs**) alongside **`★ Search: <query>`** (**★ Top Songs**, **★ Videos & Live**, matching Albums, and matching Playlists).
   - **Multi-word search tip:** Amarok 3.3.3's built-in `AmpacheServiceQueryMaker::addFilter()` has an upstream bug where unquoted spaces overwrite earlier words (so `gustavo cerati` only sends `cerati`). Wrap multi-word queries in quotes (**`"gustavo cerati"`**) or join terms with `+` / `_` (**`gustavo+cerati`** / **`gustavo_cerati`**) to send all search terms cleanly.
4. Double-click or drag tracks to the right-hand playlist queue to play!

---

## CLI Reference

```bash
# Check daemon health, detected browsers, and authenticated YouTube Music account
amarok-ytmusic status

# Show the currently playing YouTube Music track in Amarok via MPRIS2
amarok-ytmusic now

# Like, dislike, or clear rating on YouTube Music for the currently playing Amarok track
amarok-ytmusic like [VIDEO_ID] [--dislike | --clear]

# Fetch and display lyrics for the currently playing Amarok track
amarok-ytmusic lyrics [VIDEO_ID]

# Import/refresh full metadata, cover art, lyrics & tagged M4A into Amarok Local Collection
amarok-ytmusic import [VIDEO_ID] [--metadata-only] [--refresh]

# Inspect, configure, migrate, or scan the offline song cache folder
amarok-ytmusic cache [--limit 30] [--offline-only] [--search QUERY]
amarok-ytmusic cache --set-dir ~/Music/YTMusicCache --move --limit-mb 0
amarok-ytmusic cache --scan
amarok-ytmusic cache --sync-missing

# Configure Amarok (Ampache, Context Applets, Script) and systemd --user service
amarok-ytmusic setup [--no-service] [--host 127.0.0.1] [--port 18732]

# Remove Amarok integration and systemd --user service (preserves cache/config)
amarok-ytmusic uninstall

# Sync cookies directly from a local browser via CLI
amarok-ytmusic auth --browser chrome [--keyring KWALLET5] [--profile Default] [--authuser 0]

# Run the daemon in the foreground (useful for debugging)
amarok-ytmusic serve --host 127.0.0.1 --port 18732 [--open-auth] [--debug]
```

### Managing the `systemd --user` Service

```bash
systemctl --user status amarok-ytmusic.service
systemctl --user restart amarok-ytmusic.service
journalctl --user -u amarok-ytmusic.service -f
```

---

## Project Structure

```text
amarok-ytmusic/
├── .github/workflows/              # CI test matrix + automated PyPI & GitHub Release workflow
├── amarok_kpackage/                # KDE KPackage QML overrides (Current Track stats/rating/cover + Lyrics)
├── amarok_script/                  # Amarok ScriptableService (main.js, script.json, script.spec)
├── packaging/aur/                  # Arch Linux AUR PKGBUILD, .SRCINFO, install hooks & systemd unit
├── src/amarok_ytmusic/
│   ├── ampache_bridge.py           # Ampache XML API bridge with persistent ID cache & imported artists
│   ├── auth.py                     # Browser cookie extraction, raw headers parser, and OAuth
│   ├── cli.py                      # `amarok-ytmusic` CLI entrypoint
│   ├── config.py                   # XDG/Flatpak paths and persistent settings store
│   ├── installer.py                # Cross-distro `setup` / `uninstall` (Amarok config, applets & systemd)
│   ├── ipc_watcher.py              # Atomic directory/file IPC watcher for ScriptableService
│   ├── metadata_store.py           # SQLite cache for rich song metadata, user profile & play stats
│   ├── mpris_monitor.py            # MPRIS2 D-Bus monitor, auto-importer, scrobbler & rating sync
│   ├── server.py                   # FastAPI application, cover cache & Range-capable /stream proxy
│   ├── stream_resolver.py          # yt-dlp stream resolver with TTL cache & multi-mode fallback
│   ├── track_importer.py           # On-play metadata fetcher & Amarok FMPS-tagged M4A importer
│   ├── ytmusic_client.py           # ytmusicapi catalog client with rating, history & lyrics
│   └── web/index.html              # Single-file dark-mode Web Auth, Now-Playing & Cache UI
├── tests/                          # Pytest unit & integration test suite (48 tests)
├── install.sh                      # Automated installer (uv + Amarok config + systemd user service)
└── pyproject.toml                  # Package metadata and dependencies
```

---

## Development & Running Tests

```bash
uv sync --extra dev
uv run pytest -v
```

---

## Troubleshooting

- **`Ampache (YouTube Music)` does not appear under Internet in Amarok**:
  - Make sure you fully quit Amarok (`Ctrl+Q`) before running `./install.sh`, or open **Settings → Configure Amarok → Plugins**, check **Ampache**, click its wrench icon, and add:
    - **Name**: `YouTube Music`
    - **Server Address**: `http://127.0.0.1:18732/ampache`
    - **Username**: `ytmusic`
    - **Password**: `ytmusic`
- **Playlists or Library stopped updating after logging out of Google in your browser**:
  - Open **http://127.0.0.1:18732** and click **Connect Browser Session** again to refresh your cookies, then click **Clear Cache**.

---

## License

Released under the [GNU General Public License v3.0 or later (GPL-3.0-or-later)](LICENSE).
