Open-source music player for YouTube Music's catalog, with genres, full albums and playlists. Windows, macOS, Linux, Android, iPhone and Docker. No account needed.
TypeScript
feat: Musike 1.4.0 — Android, macOS and Linux apps
Ernani5ee907560cc4
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..e43741d--- /dev/null+++ b/.dockerignore@@ -0,0 +1,17 @@+# Only sources go into the build; dependencies are installed inside it.+**/node_modules+**/dist+**/dev-dist+**/dist-native+mobile/android+mobile/release+desktop/release+server/data+server/cache+docs+.git+.github+.claude+.agents+*.log+.envdiff --git a/.github/workflows/docker.yml b/.github/workflows/docker.ymlnew file mode 100644index 0000000..322cadd--- /dev/null+++ b/.github/workflows/docker.yml@@ -0,0 +1,51 @@+# Builds the Docker image for every release tag (v1.2.0 → :1.2.0, :1.2 and :latest) and publishes it+# to GitHub Container Registry as ghcr.io/<owner>/musike. Can also be started by hand from the Actions tab.+name: Docker image++on:+ push:+ tags: ["v*"]+ workflow_dispatch:++permissions:+ contents: read+ packages: write++jobs:+ image:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ # Registry names must be lowercase (the owner here is "Ernani1234").+ - name: Image name+ run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"++ - uses: docker/setup-qemu-action@v3+ - uses: docker/setup-buildx-action@v3++ - uses: docker/login-action@v3+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - id: meta+ uses: docker/metadata-action@v5+ with:+ images: ${{ env.IMAGE }}+ tags: |+ type=semver,pattern={{version}}+ type=semver,pattern={{major}}.{{minor}}+ type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }}+ type=sha,enable=${{ !startsWith(github.ref, 'refs/tags/v') }}++ - uses: docker/build-push-action@v6+ with:+ context: .+ platforms: linux/amd64,linux/arm64+ push: true+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha+ cache-to: type=gha,mode=maxdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..930f2e7--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,126 @@+# Builds every download for a release tag (v1.4.0) and attaches them to a draft GitHub release:+# the Windows installer, the macOS apps (Apple Silicon and Intel), the Linux packages and the Android APK.+# The draft only goes public when it's published by hand, after checking it.+#+# The APK is signed with the key in these repository secrets (Settings → Secrets and variables → Actions):+# MUSIKE_KEYSTORE_BASE64 the .jks file, base64-encoded+# MUSIKE_KEYSTORE_PASSWORD MUSIKE_KEY_ALIAS MUSIKE_KEY_PASSWORD+# Always the same key: Android only installs an update signed like the version already on the phone.+name: Release++on:+ push:+ tags: ["v*"]+ workflow_dispatch:++permissions:+ contents: read++jobs:+ windows:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ - run: pnpm --filter musike-desktop dist+ - uses: actions/upload-artifact@v4+ with:+ name: windows+ path: release/*+ if-no-files-found: error++ mac:+ runs-on: macos-14+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ # Ad-hoc signed (no Apple Developer ID): enough to run on Apple Silicon; Gatekeeper asks once.+ - run: pnpm --filter musike-desktop dist:mac+ env:+ CSC_IDENTITY_AUTO_DISCOVERY: "false"+ - uses: actions/upload-artifact@v4+ with:+ name: mac+ path: release/*+ if-no-files-found: error++ linux:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ # AppImage and .deb, for x64 and arm64 (the arm64 ones are packaged here too: nothing is compiled).+ - run: pnpm --filter musike-desktop dist:linux+ - uses: actions/upload-artifact@v4+ with:+ name: linux+ path: release/*+ if-no-files-found: error++ android:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ - uses: actions/setup-java@v4+ with:+ distribution: temurin+ java-version: 21+ - run: pnpm install --frozen-lockfile+ - name: Signing key+ env:+ KEYSTORE_BASE64: ${{ secrets.MUSIKE_KEYSTORE_BASE64 }}+ run: |+ if [ -z "$KEYSTORE_BASE64" ]; then+ echo "::warning::MUSIKE_KEYSTORE_BASE64 is not set: the APK will be unsigned and won't install."+ exit 0+ fi+ echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/musike-release.jks"+ echo "MUSIKE_KEYSTORE=$RUNNER_TEMP/musike-release.jks" >> "$GITHUB_ENV"+ - run: pnpm --filter @musike/mobile apk+ env:+ MUSIKE_KEYSTORE_PASSWORD: ${{ secrets.MUSIKE_KEYSTORE_PASSWORD }}+ MUSIKE_KEY_ALIAS: ${{ secrets.MUSIKE_KEY_ALIAS }}+ MUSIKE_KEY_PASSWORD: ${{ secrets.MUSIKE_KEY_PASSWORD }}+ - uses: actions/upload-artifact@v4+ with:+ name: android+ path: release/*+ if-no-files-found: error++ release:+ needs: [windows, mac, linux, android]+ if: startsWith(github.ref, 'refs/tags/v')+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/download-artifact@v4+ with:+ path: downloads+ merge-multiple: true+ - uses: softprops/action-gh-release@v2+ with:+ draft: true+ generate_release_notes: true+ files: downloads/*+ fail_on_unmatched_files: truediff --git a/.gitignore b/.gitignoreindex 36d1d15..0187f97 100644--- a/.gitignore+++ b/.gitignore@@ -1,9 +1,11 @@# Dependencies and buildsnode_modules/dist/+dist-native/dev-dist/desktop/dist/-desktop/release/+release/+desktop/out/# Local data (library, HD video cache)server/data/diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..4f0dd12--- /dev/null+++ b/Dockerfile@@ -0,0 +1,67 @@+# syntax=docker/dockerfile:1+#+# Musike server + web app in one image. The music library lives in /data, the HD video cache in /cache.+# docker run -d -p 4180:4180 -v musike-data:/data -v musike-cache:/cache ghcr.io/ernani1234/musike+#+# Multi-arch (amd64, arm64): the JavaScript is built once on the build machine, only the tools differ.++ARG NODE_VERSION=22++# ---- Build: the web app and the server, bundled into plain JavaScript ----+FROM --platform=$BUILDPLATFORM node:${NODE_VERSION}-bookworm-slim AS build+WORKDIR /src+ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0+RUN corepack enable+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./+COPY server/package.json server/+COPY web/package.json web/+COPY desktop/package.json desktop/+COPY mobile/package.json mobile/+# Only the server and web packages: the desktop and Android apps aren't needed here.+RUN pnpm install --frozen-lockfile --filter @musike/server --filter @musike/web+COPY server server+COPY web web+RUN pnpm --filter @musike/web build && pnpm --filter @musike/server bundle++# ---- Runtime: Node, FFmpeg, yt-dlp and Deno ----+FROM node:${NODE_VERSION}-bookworm-slim+ARG TARGETARCH++RUN apt-get update \+ && apt-get install -y --no-install-recommends ffmpeg ca-certificates curl unzip \+ && rm -rf /var/lib/apt/lists/*++# Official standalone builds of yt-dlp and Deno (Deno solves YouTube's player challenges for yt-dlp).+# They live in a folder the app user owns, so "Update" in Musike's Settings can replace yt-dlp.+RUN set -eux; \+ case "$TARGETARCH" in \+ arm64) ytdlp="yt-dlp_linux_aarch64"; deno="deno-aarch64-unknown-linux-gnu.zip" ;; \+ *) ytdlp="yt-dlp_linux"; deno="deno-x86_64-unknown-linux-gnu.zip" ;; \+ esac; \+ mkdir -p /opt/musike/bin; \+ curl -fsSL -o /opt/musike/bin/yt-dlp "https://github.com/yt-dlp/yt-dlp/releases/latest/download/$ytdlp"; \+ chmod +x /opt/musike/bin/yt-dlp; \+ curl -fsSL -o /tmp/deno.zip "https://github.com/denoland/deno/releases/latest/download/$deno"; \+ unzip -q /tmp/deno.zip -d /opt/musike/bin; \+ rm /tmp/deno.zip; \+ mkdir -p /data /cache; \+ chown -R node:node /opt/musike /data /cache++WORKDIR /app+COPY --from=build --chown=node:node /src/server/dist/server.mjs ./server.mjs+COPY --from=build --chown=node:node /src/web/dist ./web++ENV NODE_ENV=production \+ HOST=0.0.0.0 \+ PORT=4180 \+ MUSIKE_DATA_DIR=/data \+ MUSIKE_CACHE_DIR=/cache \+ MUSIKE_WEB_DIST=/app/web \+ PATH=/opt/musike/bin:$PATH++USER node+VOLUME ["/data", "/cache"]+EXPOSE 4180+HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \+ CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 4180) + '/api/health').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"+CMD ["node", "server.mjs"]diff --git a/README.md b/README.mdindex ff0c757..93b33f6 100644--- a/README.md+++ b/README.md@@ -1,118 +1,133 @@<div align="center">-<img src="desktop/build/icon.png" width="96" alt="Logo do Musike: três barras de equalizador formando um M" />+<img src="desktop/build/icon.png" width="96" alt="Musike logo: three equalizer bars forming an M" /># Musike-**Sua música, sem interrupção.**+**Your music, uninterrupted.**-Player pessoal que toca qualquer música ou clipe do YouTube, como **áudio** ou **vídeo**, sem anúncios.-Funciona no navegador, no celular (PWA) e como **app de computador** com instalador.+A personal music player for YouTube's catalog: any song or music video, as **audio** or **video**, with no ads, no account and no subscription.+Runs as a **Windows**, **macOS** and **Linux** app, as an **Android** app that needs no computer, in any **browser** (installable PWA) and in **Docker**.---+++++-<img src="docs/screenshots/desktop-app.png" alt="App desktop do Musike tocando um clipe no painel lateral" width="900" />+<img src="docs/screenshots/home.jpg" alt="Musike playing Radiohead, with playlists, recently played and the Now Playing panel" width="900" />++**[Download for Windows, macOS, Linux and Android](https://github.com/Ernani1234/musike/releases/latest)** · [Run with Docker](#option-5-docker) · [Run from source](#option-6-node-server--browser)</div>----## Sumário+## Contents-- [O que é](#o-que-é)-- [Recursos](#recursos)-- [Capturas de tela](#capturas-de-tela)-- [Como funciona](#como-funciona)-- [Instalação](#instalação)-- [Levar sua biblioteca para outra instância (backup)](#levar-sua-biblioteca-para-outra-instância-backup)-- [Atalhos de teclado](#atalhos-de-teclado)-- [Configuração](#configuração)+- [What it is](#what-it-is)+- [Features](#features)+- [Screenshots](#screenshots)+- [How it works](#how-it-works)+- [Installation](#installation)+- [Moving your library (backup)](#moving-your-library-backup)+- [Keyboard shortcuts](#keyboard-shortcuts)+- [Configuration](#configuration)- [API](#api)-- [Estrutura do projeto](#estrutura-do-projeto)-- [Solução de problemas](#solução-de-problemas)+- [Project structure](#project-structure)+- [Troubleshooting](#troubleshooting)- [Roadmap](#roadmap)-- [Aviso legal](#aviso-legal)-- [Licença](#licença)--## O que é--O Musike nasceu da ideia dos antigos bots de música do Discord: um servidor que busca o áudio direto do YouTube e o entrega pronto para tocar. Em vez de um chat, a interface é um player completo, rápido e simples, com cara de app moderno e um toque gamer.--- **Sem anúncios e sem conta:** o servidor obtém o stream original com o [yt-dlp](https://github.com/yt-dlp/yt-dlp) e repassa os bytes ao player.-- **Música ou clipe:** troque entre Áudio e Vídeo a qualquer momento, do mesmo ponto da faixa. Para músicas, o Musike encontra o clipe oficial do artista.-- **Em qualquer tela:** layout pensado para celulares de todos os tamanhos, tablets, notebooks e monitores grandes.-- **Seu, de verdade:** roda no seu computador. Playlists e favoritas ficam num arquivo local que você pode exportar e levar para qualquer outra instância.--## Recursos--**Ouvir**-- Busca no YouTube Music com abas **Músicas** e **Vídeos** e sugestões enquanto você digita-- Cole um **link do YouTube** na busca para tocar direto-- **Explorar por gênero:** o filtro **Gêneros** na busca abre os gêneros do YouTube Music (Rock, Sertanejo, MPB, Metal...). Cada um mostra as bandas e artistas do gênero (toque em um para ver os maiores sucessos) ou todas as músicas numa lista só, com seleção para tocar, favoritar ou mandar para uma playlist-- **Buscar lista:** escreva várias músicas separadas por vírgula ("Evidências, Trem-Bala, ..."); o Musike busca cada uma, já seleciona o melhor resultado (dá para trocar) e você toca, favorita ou manda as selecionadas para uma playlist nova ou existente-- Fila com tocar a seguir, aleatório e repetir (fila ou faixa)-- **Rádio automático:** quando a fila acaba, continua com músicas parecidas-- Avanço e retrocesso instantâneos (streaming com HTTP Range) e próxima faixa pré-carregada--**Vídeo**-- Modo Vídeo no painel lateral, na tela cheia do celular ou num mini player flutuante-- **Clipe oficial** encontrado automaticamente para faixas da aba Músicas (só aceita o canal do próprio artista)-- **Modo cinema:** maximize o clipe (botão, duplo clique ou tecla `F`), com controles que somem enquanto você assiste e tela cheia de verdade-- Qualidade SD (começa rápido) ou HD 720p (com cache local)--**Biblioteca**-- Playlists, Favoritas e histórico de tocadas recentemente-- **Backup em arquivo** para levar tudo a outra instância: juntar ou substituir, com prévia antes de importar--**Interface**-- **Em inglês por padrão, com troca de idioma em Ajustes > Language** (English e Português do Brasil). A escolha vale por aparelho e traduz também as mensagens do servidor e os nomes de gêneros e biografias que vêm do YouTube Music-- Tema escuro e claro, layout responsivo do celular de 320 px ao monitor ultrawide-- Controles na tela de bloqueio, fones e teclas de mídia (Media Session)-- Retoma a fila e a posição de onde você parou-- Instalável como app no celular (PWA) e atalhos de teclado no computador--**App desktop (Windows)**-- Janela nativa com barra de título própria, sem navegador-- Instalador que cria o atalho na área de trabalho-- Baixa e mantém sozinho as ferramentas de que precisa (yt-dlp, Deno, FFmpeg)--**Manutenção**-- Tela **Ajustes** mostra a versão do yt-dlp, avisa quando há atualização e atualiza com um clique (canal Estável ou Nightly)-- Erros de reprodução oferecem o botão "Atualizar" direto no aviso--## Capturas de tela+- [Legal notice](#legal-notice)+- [License](#license)++## What it is++Musike started from the idea behind the old Discord music bots: a server that fetches audio straight from YouTube and hands it over ready to play. Instead of a chat, the interface is a full music player: fast, simple, and built to feel like a modern app.++- **No ads, no account:** the server gets the original stream with [yt-dlp](https://github.com/yt-dlp/yt-dlp) and passes the bytes to the player.+- **Song or music video:** switch between Audio and Video at any time, from the same point in the track. For songs, Musike finds the artist's official music video.+- **Any screen:** designed for phones of every size, tablets, laptops and big monitors.+- **Yours:** it runs on your own computer. Playlists and favorites live in a local file you can export and take to any other Musike.++## Features++**Listen**+- Search YouTube Music with **Songs**, **Videos** and **Albums** tabs, with suggestions as you type+- Paste a **YouTube link** to play it right away+- **Browse by genre:** the **Genres** button opens YouTube Music's genres (Rock, Pop, Hip-hop, Indie, Metal, Jazz…). See each genre's bands and artists (with "Load more") or all its songs in one list+- **Artists:** greatest hits, plus every album and single+- **Albums:** open any album and play it in its original order, shuffle it, or save it as a playlist in one click+- **Search a list:** type several songs separated by commas ("Bohemian Rhapsody, Hotel California, …"). Musike finds each one, picks the best match (you can swap it) and lets you play, favorite or send them all to a playlist+- Queue with play next, shuffle and repeat (queue or track)+- **Autoplay radio:** when the queue ends, it keeps going with similar songs+- Instant seeking (HTTP Range streaming) and the next track preloaded++**Video**+- Video mode in the side panel, full screen on phones, or in a floating mini player+- **Official music video** found automatically for songs (only from the artist's own channel)+- **Cinema mode:** maximize the video (button, double-click or `F`), with controls that fade while you watch, and true full screen+- SD quality (starts fast) or HD 720p (cached locally)++**Library**+- Playlists, Favorites and recently played history+- Select many tracks at once to play, favorite or add to a playlist+- **Backup to a file** to move everything to another Musike: merge or replace, with a preview before importing++**Make it yours**+- **English** and **Brazilian Portuguese**, switchable in Settings (per device). Server messages and the genre names and bios that come from YouTube Music follow the same language+- Dark and light themes, and **any accent color**: 8 presets or a custom one. Musike adjusts text shades so they stay readable in both themes+- Show or hide panels: the Now Playing panel, playlists in the sidebar, a compact icons-only sidebar, the album column, the background texture, and each section of the Home page+- Responsive from 320 px phones to ultrawide monitors; lock screen, headphone and media key controls (Media Session); picks up the queue where you left off++**Desktop app (Windows, macOS and Linux)**+- Native window with its own title bar, no browser+- Windows installer with desktop and Start menu shortcuts; macOS app for Apple Silicon and Intel; Linux `.deb` and AppImage for x64 and arm64+- Updating keeps your library (it's backed up automatically before each update)+- Downloads and maintains the tools it needs (yt-dlp, Deno, FFmpeg)++**Android app**+- **Standalone:** no computer, no server. The phone searches YouTube Music and plays the audio straight from YouTube+- Same app as on the computer: search, genres, artists, albums, Search a list, playlists, favorites, themes and colors+- Keeps playing with the screen off, with controls in the notification, on the lock screen and on headphones; pauses for calls and when headphones are unplugged+- Audio only for now (no video mode)++**Self-hosting**+- **Docker image** for amd64 and arm64 (Raspberry Pi), with everything inside+- Open it from any device on your network, or from anywhere with Tailscale++**Maintenance**+- **Settings** shows the yt-dlp version, tells you when there's an update and updates it in one click (Stable or Nightly channel)+- Playback errors offer the "Update" button right in the notice++## Screenshots<table><tr>- <td align="center"><img src="docs/screenshots/mobile-busca.png" width="260" alt="Busca no celular com mini player" /><br /><sub>Busca e mini player no celular</sub></td>- <td align="center"><img src="docs/screenshots/mobile-tocando.png" width="260" alt="Tela Tocando agora no celular" /><br /><sub>Tocando agora</sub></td>+ <td align="center"><img src="docs/screenshots/album.jpg" width="440" alt="Nevermind album page with its tracks in order" /><br /><sub>Albums, in their original order</sub></td>+ <td align="center"><img src="docs/screenshots/genre.jpg" width="440" alt="Indie and alternative genre with its artists" /><br /><sub>Browse by genre</sub></td></tr>-</table>--<table><tr>- <td align="center"><img src="docs/screenshots/modo-cinema.png" width="440" alt="Modo cinema com o clipe maximizado" /><br /><sub>Modo cinema</sub></td>- <td align="center"><img src="docs/screenshots/backup.png" width="440" alt="Importação de backup com prévia" /><br /><sub>Importar backup com prévia</sub></td>+ <td align="center"><img src="docs/screenshots/cinema.jpg" width="440" alt="Cinema mode playing a music video" /><br /><sub>Cinema mode</sub></td>+ <td align="center"><img src="docs/screenshots/search-a-list.jpg" width="440" alt="Search a list: six songs found at once" /><br /><sub>Search a list</sub></td></tr><tr>- <td align="center" colspan="2"><img src="docs/screenshots/atualizar-yt-dlp.png" width="440" alt="Ajustes com atualização do yt-dlp disponível" /><br /><sub>Atualização do yt-dlp em um clique</sub></td>+ <td align="center"><img src="docs/screenshots/customize.jpg" width="440" alt="Violet accent color with a compact sidebar" /><br /><sub>Your colors and layout</sub></td>+ <td align="center"><img src="docs/screenshots/mobile.jpg" width="440" alt="Musike on three phone screens" /><br /><sub>On your phone</sub></td></tr></table>-## Como funciona+## How it works```mermaidflowchart LR- subgraph Clientes+ subgraph ClientsW["Web / PWA<br/>React + Vite"]- D["App desktop<br/>Electron"]+ D["Desktop app<br/>Electron"]end- subgraph S["Servidor Musike (Fastify)"]- API["API REST"]- P["Proxy de stream<br/>HTTP Range"]+ subgraph S["Musike server (Fastify)"]+ API["REST API"]+ P["Stream proxy<br/>HTTP Range"]L[("library.json")]endYTM["YouTube Music<br/>youtubei.js"]@@ -120,236 +135,326 @@ flowchart LRYT[("YouTube / googlevideo")]W --> API- D -- "servidor embutido" --> API- API -- "busca, sugestões, rádio, clipes" --> YTM- API -- "resolve streams, junta HD" --> T+ D -- "built-in server" --> API+ API -- "search, genres, artists, albums, radio" --> YTM+ API -- "resolves streams, merges HD" --> TT --> YTP --> YTAPI --> L```-1. **Busca:** o servidor consulta o YouTube Music com o [youtubei.js](https://github.com/LuanRT/YouTube.js) (busca, sugestões, rádio e escolha do clipe oficial).-2. **Reprodução:** o yt-dlp resolve as URLs do stream (áudio AAC, vídeo MP4). Essas URLs ficam presas ao IP de quem as resolveu, então o servidor faz o **proxy** dos bytes, repassando o cabeçalho `Range` para que o avanço seja instantâneo.-3. **Vídeo HD e clipes sem versão SD:** o yt-dlp baixa e junta vídeo + áudio com FFmpeg, guarda em cache (LRU, 2 GB por padrão) e o servidor entrega o arquivo com suporte a Range.-4. **Biblioteca:** playlists, favoritas e histórico ficam em `library.json`, gravado de forma atômica.-5. **Web:** um único elemento `<video>` é movido no DOM entre painel, tela cheia, mini player e modo cinema sem interromper a reprodução.+1. **Catalog:** the server queries YouTube Music with [youtubei.js](https://github.com/LuanRT/YouTube.js): search, suggestions, genres, artists, albums, radio and picking the official music video.+2. **Playback:** yt-dlp resolves the stream URLs (AAC audio, MP4 video), running YouTube's player code with Deno. Those URLs are tied to the IP that resolved them, so the server **proxies** the bytes, forwarding the `Range` header so seeking is instant. Nothing is written to disk for audio.+3. **HD video and videos without an SD version:** yt-dlp downloads and merges video + audio with FFmpeg, keeps it in a cache (least-recently-played first, 2 GB by default) and the server serves the file with Range support.+4. **Library:** playlists, favorites and history live in `library.json`, written atomically.-## Instalação+**On Android** there is no server. The app runs Musike's server code itself (catalog and library, from `server/src`) and asks YouTube for the audio stream from the phone, so the stream URL belongs to the phone's own connection and the player reads it directly, without a proxy. Which YouTube client the app uses to get streams is read from [`mobile/streaming.json`](mobile/streaming.json), so it can be adjusted without releasing a new app.+5. **Web:** a single `<video>` element moves around the page (panel, full screen, mini player, cinema mode) without interrupting playback.-### Opção 1: app de computador (Windows)+## Installation-Gere o instalador (ou baixe-o na página de Releases, se publicado):+### Option 1: Windows app-```powershell-pnpm install-pnpm installer # cria desktop\release\Musike-Setup-<versão>.exe+Download `Musike-Setup-<version>-Windows.exe` from the [latest release](https://github.com/Ernani1234/musike/releases/latest) and run it. The installer:++- installs for the current user only (no administrator needed) and lets you pick the folder;+- creates **Musike** shortcuts on the desktop and in the Start menu, and opens the app when it's done;+- uninstalls from Windows Settings > Apps.++On first launch, a screen shows the official tools being downloaded: **yt-dlp** and **Deno** (about 60 MB) and, in the background, **FFmpeg** (about 80 MB, for HD video). Everything lives in `%APPDATA%\Musike`:++| Folder | Contents |+|---|---|+| `bin` | Musike's own yt-dlp, Deno and FFmpeg (updatable in Settings) |+| `data` | `library.json` with playlists, favorites and history |+| `cache` | HD videos already downloaded |+| `backups` | copies of the library made at each update |++**To update, just install the new version over the old one.** `%APPDATA%\Musike` is separate from the program folder, and neither updating nor uninstalling deletes it. To be safe, the installer also copies the library to `backups\library-before-install-<version>.json` before replacing the old version, and the app keeps another dated copy on the first launch of each version (the 5 most recent). To restore one, close Musike and copy it over `data\library.json`.++> The installer isn't code-signed yet. On first run Windows shows "Windows protected your PC": click **More info**, then **Run anyway**.++To build the installer yourself: `pnpm install && pnpm installer` (creates `release\Musike-Setup-<version>-Windows.exe`).++### Option 2: macOS app++Download the `.dmg` for your Mac from the [latest release](https://github.com/Ernani1234/musike/releases/latest): `Musike-Setup-<version>-macOS-arm64.dmg` for Apple Silicon (M1 and newer) or `Musike-Setup-<version>-macOS-x64.dmg` for Intel. Open it and drag **Musike** to **Applications**. Requires macOS 12 or newer.++The app isn't notarized by Apple yet, so macOS blocks the first launch:++1. Open Musike once; macOS says it can't verify it. Click **Done**.+2. Open **System Settings > Privacy & Security**, scroll down and click **Open Anyway** next to Musike, then confirm.++If macOS says the app "is damaged and can't be opened", remove the download flag in Terminal and open it again:++```bash+xattr -dr com.apple.quarantine /Applications/Musike.app```-O instalador:+Like on Windows, the first launch downloads yt-dlp, Deno and FFmpeg. Everything lives in `~/Library/Application Support/Musike` (same folders as the table above), and updating (dragging the new version over the old one) keeps your library.-- instala só para o usuário atual (não pede administrador) e deixa escolher a pasta;-- cria o atalho **Musike** na área de trabalho e no Menu Iniciar e abre o app ao terminar;-- desinstala pelo Windows em Configurações > Aplicativos.+To build it yourself on a Mac: `pnpm install && pnpm --filter musike-desktop dist:mac` (creates the `.dmg` files in `release`).-Na primeira abertura, uma tela mostra o download das ferramentas oficiais: **yt-dlp** e **Deno** (cerca de 60 MB) e, em segundo plano, **FFmpeg** (cerca de 80 MB, para vídeo HD). Tudo fica em `%APPDATA%\Musike`:+### Option 3: Linux app-| Pasta | Conteúdo |-|---|---|-| `bin` | yt-dlp, Deno e FFmpeg do próprio Musike (atualizáveis em Ajustes) |-| `data` | `library.json` com playlists, favoritas e histórico |-| `cache` | vídeos HD já baixados |-| `backups` | cópias da biblioteca feitas a cada atualização |+From the [latest release](https://github.com/Ernani1234/musike/releases/latest), pick the package for your system: `x64` for most PCs, `arm64` for ARM computers such as a Raspberry Pi 4 or 5 running a 64-bit desktop.++- **Debian, Ubuntu, Linux Mint, Pop!_OS:** `Musike-Setup-<version>-Linux-x64.deb`. Open it with the software installer, or run `sudo apt install ./Musike-Setup-<version>-Linux-x64.deb`. Musike appears in the applications menu.+- **Any other distribution:** `Musike-Setup-<version>-Linux-x64.AppImage`. Make it executable and run it: `chmod +x Musike-*.AppImage && ./Musike-*.AppImage`.++> Ubuntu 24.04 and newer block the sandbox an AppImage needs, so there the AppImage closes right away: use the `.deb` (it sets up what's needed), or start the AppImage with `--no-sandbox`.++Like on Windows and macOS, the first launch downloads yt-dlp, Deno and FFmpeg. Everything lives in `~/.config/Musike` (same folders as the table above). To update, install the new `.deb` over the old one or replace the AppImage: your library stays.++To build it yourself on Linux: `pnpm install && pnpm --filter musike-desktop dist:linux` (creates the `.deb` and `.AppImage` files in `release`).++### Option 4: Android app++On the phone, download `Musike-Setup-<version>-Android.apk` from the [latest release](https://github.com/Ernani1234/musike/releases/latest) and open it. Android asks to allow installing apps from your browser (or Files): allow it, then tap **Install**. If Play Protect warns about an unknown app, tap **More details > Install anyway**. Requires Android 7.0 or newer.++- It works on its own: no computer and no Musike server needed, only an internet connection.+- Your playlists and favorites live on the phone. To move them to or from a computer, use [backup to a file](#moving-your-library-backup) (on Android, Export opens the share sheet: save to Files or Drive, or send it to yourself).+- **To update,** install the new APK over the old one. Your library stays.+- Audio only for now: the video mode is available on the desktop app and in the browser.-**Atualizar é só instalar a versão nova por cima.** A pasta `%APPDATA%\Musike` fica fora da pasta do programa e nem a atualização nem a desinstalação a apagam. Por segurança, antes de trocar a versão o instalador ainda copia a biblioteca para `backups\library-before-install-<versão>.json`, e o app guarda outra cópia datada na primeira abertura de cada versão (mantém as 5 mais recentes). Para restaurar uma delas, feche o Musike e copie o arquivo por cima de `data\library.json`.+To build the APK yourself you need JDK 21 and the Android SDK (Android Studio installs both): `pnpm install && pnpm --filter @musike/mobile apk` (creates `release/Musike-Setup-<version>-Android.apk`; unsigned unless `mobile/android/keystore.properties` points to your signing key).-> O instalador não é assinado digitalmente. Na primeira execução o Windows mostra "O Windows protegeu o computador": clique em **Mais informações** e depois **Executar assim mesmo**.+### Option 5: Docker-### Opção 2: servidor + navegador (computador e celular)+For a home server, NAS or Raspberry Pi. The image (amd64 and arm64) includes yt-dlp, Deno and FFmpeg.-Requisitos:+```yaml+# docker-compose.yml+services:+ musike:+ image: ghcr.io/ernani1234/musike:latest+ ports:+ - "4180:4180"+ volumes:+ - musike-data:/data # library: playlists, favorites, history+ - musike-cache:/cache # HD videos already downloaded+ restart: unless-stopped+volumes:+ musike-data:+ musike-cache:+```++```bash+docker compose up -d # then open http://<that machine>:4180+```++Or with plain Docker: `docker run -d -p 4180:4180 -v musike-data:/data -v musike-cache:/cache ghcr.io/ernani1234/musike`. To build the image from source instead: `docker build -t musike .`++- A new image is published for every release; `docker compose pull && docker compose up -d` updates it. The library stays in the `/data` volume.+- yt-dlp can also be updated from **Settings** without a new image (until the container is recreated).+- All the [environment variables](#configuration) work, e.g. `YTDLP_EXTRA_ARGS="--cookies /data/cookies.txt"` for YouTube's bot checks.++> **Run it at home, not on a VPS:** YouTube blocks datacenter IPs ("Sign in to confirm you're not a bot"). A home server uses your residential IP.-| Ferramenta | Versão | Windows |+### Option 6: Node server + browser++Requirements:++| Tool | Version | Windows ||---|---|---|| Node.js | 22.19+ | `winget install OpenJS.NodeJS.LTS` |-| pnpm | 10+ | `npm install -g pnpm` |-| yt-dlp | recente | `winget install yt-dlp.yt-dlp` (instala Deno e FFmpeg junto) |+| pnpm | 10+ | `corepack enable` |+| yt-dlp | recent | `winget install yt-dlp.yt-dlp` (installs Deno and FFmpeg too) |-```powershell+```bashpnpm install-pnpm build # compila a interface+pnpm build # builds the web apppnpm start # http://localhost:4180```-O servidor mostra os endereços de rede ao iniciar. Abra o endereço `Rede:` no celular conectado ao mesmo Wi-Fi (permita o Node no firewall em redes privadas). O servidor encontra o yt-dlp mesmo em terminais abertos antes da instalação, lendo o PATH do registro do Windows.--**Fora de casa:** instale o [Tailscale](https://tailscale.com) no computador e no celular. Para instalar como app (PWA) no celular, o navegador exige HTTPS: rode `tailscale serve --bg 4180` e use o endereço `https://...ts.net`.+The server prints its network addresses on start. Open the `Network:` address on a phone on the same Wi-Fi (allow Node through the firewall on private networks). On Windows the server finds yt-dlp even in terminals opened before it was installed, by reading the PATH from the registry.-> Não hospede em VPS ou nuvem: o YouTube bloqueia IPs de datacenter ("Sign in to confirm you're not a bot"). Rodar no seu computador usa seu IP residencial.+**Away from home:** install [Tailscale](https://tailscale.com) on the computer and the phone. To install Musike as an app (PWA) on the phone the browser requires HTTPS: run `tailscale serve --bg 4180` and use the `https://...ts.net` address.-### Desenvolvimento+### Development-```powershell-pnpm dev # servidor (4180) + Vite com recarga automática (5173)-pnpm desktop # abre o app Electron em modo de desenvolvimento-pnpm typecheck # checa os três pacotes+```bash+pnpm dev # server (4180) + Vite with hot reload (5173)+pnpm desktop # opens the Electron app in development mode+pnpm typecheck # checks every package```-## Levar sua biblioteca para outra instância (backup)+## Moving your library (backup)-Enquanto a sincronização em nuvem não existe, o Musike exporta tudo num arquivo que **qualquer instância** lê: web, desktop, outro computador.+Until cloud sync exists, Musike exports everything to a file that **any instance** can read: web, desktop, Android, Docker, another computer.-1. Na instância de origem, abra **Ajustes > Seus dados > Exportar** (ou o ícone de banco de dados na Biblioteca). Um arquivo `musike-backup-AAAA-MM-DD.musike.json` é salvo.-2. Na instância de destino, **Ajustes > Seus dados > Importar** e escolha o arquivo.-3. Confira a prévia (quantas playlists, faixas, favoritas) e escolha:- - **Juntar com a minha biblioteca** (padrão): adiciona o que falta e nunca apaga. Playlists com o mesmo nome ganham as faixas novas; importar duas vezes não duplica nada.- - **Substituir tudo:** deixa a biblioteca exatamente como no backup (pede confirmação).-4. Opcionalmente, aplica também o tema e as preferências do player.+1. On the source, open **Settings > Your data > Export** (or the database icon in the Library). A `musike-backup-YYYY-MM-DD.musike.json` file is saved (on Android, the share sheet opens so you can save or send it).+2. On the destination, **Settings > Your data > Import** and pick the file.+3. Check the preview (how many playlists, tracks, favorites) and choose:+ - **Merge with my library** (default): adds what's missing and never deletes. Playlists with the same name get the new tracks; importing twice duplicates nothing.+ - **Replace everything:** makes the library exactly like the backup (asks for confirmation).+4. Optionally, also apply the appearance, language and player preferences.-O arquivo é JSON legível e versionado:+The file is readable, versioned JSON:```json{"format": "musike-backup","version": 1,- "exportedAt": "2026-10-12T22:33:00.000Z",- "app": "Musike 0.1.0",+ "exportedAt": "2026-10-16T22:33:00.000Z",+ "app": "Musike 1.4.0","library": {- "favorites": [{ "id": "UpvruBhcH38", "title": "Oceano", "artist": "Djavan", "duration": 297, "thumb": "https://...", "art": "https://...", "kind": "song" }],- "playlists": [{ "id": "…", "name": "Foco", "createdAt": 1791842422955, "updatedAt": 1791842422955, "tracks": [] }],+ "favorites": [{ "id": "hTWKbfoikeg", "title": "Smells Like Teen Spirit", "artist": "Nirvana", "duration": 302, "thumb": "https://...", "art": "https://...", "kind": "song" }],+ "playlists": [{ "id": "…", "name": "Focus", "createdAt": 1791842422955, "updatedAt": 1791842422955, "tracks": [] }],"history": []},- "settings": { "theme": "dark", "preferVideo": false, "quality": "sd", "autoRadio": true, "volume": 0.9 }+ "settings": { "theme": "dark", "lang": "en", "preferVideo": false, "quality": "sd", "autoRadio": true, "volume": 0.9 }}```-Na importação o servidor valida cada faixa (ID do YouTube, tamanhos, só imagens `https://`), descarta entradas inválidas em vez de recusar o arquivo inteiro e recusa backups de versões mais novas com uma mensagem clara.+On import the server validates every track (YouTube ID, sizes, `https://` images only), skips invalid entries instead of rejecting the whole file, and refuses backups from newer versions with a clear message.-## Atalhos de teclado+## Keyboard shortcuts-| Tecla | Ação |+| Key | Action ||---|---|-| `Espaço` | Tocar / pausar |-| `←` `→` | Voltar / avançar 5 s |-| `Shift` + `←` `→` | Faixa anterior / próxima |+| `Space` | Play / pause |+| `←` `→` | Back / forward 5 s |+| `Shift` + `←` `→` | Previous / next track || `↑` `↓` | Volume |-| `M` | Mudo |-| `L` | Favoritar a faixa atual |-| `S` | Ordem aleatória |-| `R` | Repetir (desligado, fila, faixa) |-| `V` | Alternar Áudio / Vídeo |-| `F` | Modo cinema |-| `Q` | Fila |-| `/` | Buscar |-| `?` | Lista de atalhos |+| `M` | Mute |+| `L` | Favorite the current track |+| `S` | Shuffle |+| `R` | Repeat (off, queue, track) |+| `V` | Switch Audio / Video |+| `F` | Cinema mode |+| `Q` | Queue |+| `/` | Search |+| `?` | Shortcut list |-## Configuração+## Configuration-Variáveis de ambiente do servidor (todas opcionais):+Server environment variables (all optional):-| Variável | Padrão | Uso |+| Variable | Default | Use ||---|---|---|-| `PORT` | `4180` | Porta HTTP |-| `HOST` | `0.0.0.0` | Use `127.0.0.1` para aceitar só este computador |-| `YTDLP_PATH` | automático | Força um executável específico do yt-dlp |-| `YTDLP_EXTRA_ARGS` | | Flags extras, ex.: `--cookies-from-browser firefox` |-| `MUSIKE_DATA_DIR` | `server/data` | Onde fica `library.json` |-| `MUSIKE_CACHE_DIR` | `server/cache` | Vídeos HD baixados |-| `MUSIKE_CACHE_MAX_MB` | `2048` | Limite do cache de vídeo (apaga os menos tocados) |-| `MUSIKE_BIN_DIR` | | Pasta privada de ferramentas (o app desktop usa `%APPDATA%\Musike\bin`) |-| `MUSIKE_LANG` / `MUSIKE_LOCATION` | `en` / `BR` | Idioma do YouTube Music quando a requisição não informa um (o app sempre informa o idioma escolhido) e região da busca |+| `PORT` | `4180` | HTTP port |+| `HOST` | `0.0.0.0` | Use `127.0.0.1` to accept only this computer |+| `YTDLP_PATH` | automatic | Forces a specific yt-dlp executable |+| `YTDLP_EXTRA_ARGS` | | Extra flags, e.g. `--cookies-from-browser firefox` |+| `MUSIKE_DATA_DIR` | `server/data` (`/data` in Docker) | Where `library.json` lives |+| `MUSIKE_CACHE_DIR` | `server/cache` (`/cache` in Docker) | Downloaded HD videos |+| `MUSIKE_CACHE_MAX_MB` | `2048` | Video cache limit (least recently played go first) |+| `MUSIKE_BIN_DIR` | | Private tools folder (the desktop app uses `%APPDATA%\Musike\bin`) |+| `MUSIKE_LANG` | `en` | YouTube Music language when a request doesn't say (the app always sends the chosen language) |+| `MUSIKE_LOCATION` | `BR` | Region for YouTube Music results |## API-Todas as rotas respondem JSON. Erros vêm como `{ "error": "mensagem", "code"?: "tool_missing" | "maybe_outdated" | "bot_check" }`.+Every route answers JSON. Errors look like `{ "error": "message", "code"?: "tool_missing" | "maybe_outdated" | "bot_check" }`, with the message in the language of the `x-musike-lang` request header (`en` or `pt-BR`).-| Método | Rota | Descrição |+| Method | Route | Description ||---|---|---|-| `GET` | `/api/search?q=&type=song\|video` | Busca no YouTube Music |-| `GET` | `/api/suggest?q=` | Sugestões de busca |-| `GET` | `/api/radio/:id` | Faixas relacionadas (rádio) |-| `GET` | `/api/genres` | Gêneros do YouTube Music |-| `GET` | `/api/genres/:gid` | Artistas e músicas de um gênero |-| `GET` | `/api/genres/:gid/artists?offset=` | Mais artistas do gênero ("Carregar mais") |-| `GET` | `/api/artists/:aid` | Maiores sucessos de um artista |-| `GET` | `/api/video-for/:id?title=&artist=&duration=` | Clipe oficial de uma música |-| `POST` | `/api/prepare/:id` | Resolve o stream antes de tocar |-| `GET` | `/api/stream/:id/audio` | Áudio com HTTP Range |-| `GET` | `/api/stream/:id/video?q=sd\|hd` | Vídeo com HTTP Range |-| `GET` | `/api/library` | Biblioteca completa |-| `PUT` / `DELETE` | `/api/favorites/:id` | Favoritar / desfavoritar |-| `POST` | `/api/favorites` | Favorita várias de uma vez (`{ tracks }`) |-| `POST` | `/api/history` | Registra uma faixa tocada |-| `POST` | `/api/playlists` | Cria playlist |-| `PATCH` / `DELETE` | `/api/playlists/:pid` | Renomeia / exclui |-| `POST` / `DELETE` | `/api/playlists/:pid/tracks[/:id]` | Adiciona (uma faixa ou `{ tracks }`) / remove faixa |-| `POST` | `/api/library/import` | Importa backup (`{ backup, mode: "merge" \| "replace" }`) |-| `GET` | `/api/system` | Versões do yt-dlp, Deno, FFmpeg e downloads |-| `POST` | `/api/system/ytdlp` | Atualiza ou instala o yt-dlp (`{ channel: "stable" \| "nightly" }`) |--## Estrutura do projeto+| `GET` | `/api/search?q=&type=song\|video` | Search YouTube Music |+| `GET` | `/api/search/albums?q=` | Search albums |+| `GET` | `/api/suggest?q=` | Search suggestions |+| `GET` | `/api/radio/:id` | Related tracks (radio) |+| `GET` | `/api/genres` | YouTube Music genres |+| `GET` | `/api/genres/:gid` | A genre's artists and songs |+| `GET` | `/api/genres/:gid/artists?offset=` | More of a genre's artists ("Load more") |+| `GET` | `/api/artists/:aid` | An artist's greatest hits, albums and singles |+| `GET` | `/api/albums/:alid` | An album's tracks in order |+| `GET` | `/api/video-for/:id?title=&artist=&duration=` | A song's official music video |+| `POST` | `/api/prepare/:id` | Resolves a stream before playing |+| `GET` | `/api/stream/:id/audio` | Audio with HTTP Range |+| `GET` | `/api/stream/:id/video?q=sd\|hd` | Video with HTTP Range |+| `GET` | `/api/library` | The whole library |+| `PUT` / `DELETE` | `/api/favorites/:id` | Favorite / unfavorite |+| `POST` | `/api/favorites` | Favorite many at once (`{ tracks }`) |+| `POST` | `/api/history` | Records a played track |+| `POST` | `/api/playlists` | Creates a playlist |+| `PATCH` / `DELETE` | `/api/playlists/:pid` | Renames / deletes |+| `POST` / `DELETE` | `/api/playlists/:pid/tracks[/:id]` | Adds (one track or `{ tracks }`) / removes a track |+| `POST` | `/api/library/import` | Imports a backup (`{ backup, mode: "merge" \| "replace" }`) |+| `GET` | `/api/system` | yt-dlp, Deno and FFmpeg versions and downloads |+| `POST` | `/api/system/ytdlp` | Updates or installs yt-dlp (`{ channel: "stable" \| "nightly" }`) |++## Project structure```musike/├─ server/ Fastify + yt-dlp + youtubei.js│ └─ src/-│ ├─ app.ts rotas e inicialização (usado pelo CLI e pelo desktop)-│ ├─ ytdlp.ts resolução de streams, cache HD, tradução de erros-│ ├─ stream.ts proxy com HTTP Range-│ ├─ search.ts busca, sugestões, rádio e escolha do clipe oficial-│ ├─ library.ts playlists, favoritas, histórico e import de backup-│ ├─ tools.ts localiza yt-dlp, Deno, FFmpeg (registro do Windows, winget)-│ ├─ bootstrap.ts baixa as ferramentas para o app desktop-│ └─ system.ts versão e atualização do yt-dlp+│ ├─ app.ts routes and startup (used by the CLI, the desktop app and Docker)+│ ├─ browse.ts genres, artists, albums+│ ├─ search.ts search, suggestions, radio and official music videos+│ ├─ ytdlp.ts stream resolution, HD cache, error messages+│ ├─ stream.ts proxy with HTTP Range+│ ├─ library.ts playlists, favorites, history and backup import+│ ├─ i18n.ts server messages in each language+│ ├─ tools.ts finds yt-dlp, Deno, FFmpeg (Windows registry, winget, PATH)+│ ├─ bootstrap.ts downloads the tools for the desktop app+│ └─ system.ts yt-dlp version and updates├─ web/ React 19 + Vite + Tailwind v4 + Motion + Phosphor (PWA)│ └─ src/-│ ├─ player/ motor de reprodução (áudio, vídeo, fila, Media Session)-│ ├─ components/ player, painéis, modo cinema, Ajustes, backup-│ ├─ views/ Início, Buscar, Biblioteca, playlists-│ └─ stores/ estado (zustand)-├─ desktop/ Electron: janela, servidor embutido, instalador NSIS-└─ docs/ benchmark de UX, design system e capturas de tela+│ ├─ player/ playback engine (audio, video, queue, Media Session)+│ ├─ components/ player, panels, cinema mode, Settings, backup+│ ├─ views/ Home, Search, Library, playlists, genres, artists, albums+│ ├─ i18n/ English (the source) and Portuguese+│ ├─ native/ Android: server code running in the app, streams, media controls+│ └─ stores/ state (zustand), appearance preferences+├─ desktop/ Electron: window, built-in server, Windows installer, macOS and Linux packages+├─ mobile/ Android app (Capacitor): playback service, signing, streaming.json+├─ Dockerfile server + web app image (amd64, arm64)+└─ docs/ UX benchmark, design system and screenshots```-**Stack:** TypeScript em tudo · Fastify 5 · youtubei.js · yt-dlp · React 19 · Vite 8 · Tailwind CSS 4 · Motion · Zustand · React Router · Phosphor Icons · Geist · Electron 44 · electron-builder.+**Stack:** TypeScript everywhere · Fastify 5 · youtubei.js · yt-dlp · React 19 · Vite 8 · Tailwind CSS 4 · Motion · Zustand · React Router · Phosphor Icons · Geist · Electron 44 · electron-builder · Capacitor 8.-**Design:** a identidade (marca de equalizador em M, cor Volt, Geist) e as regras de layout estão em [docs/design-system.md](docs/design-system.md). O estudo de UX que guiou o layout está em [docs/ux-benchmark.md](docs/ux-benchmark.md): observação do web player do Spotify, sem descompilar código.+**Design:** the identity (the equalizer M mark, the Volt color, Geist) and the layout rules are in [docs/design-system.md](docs/design-system.md). The UX study behind the layout is in [docs/ux-benchmark.md](docs/ux-benchmark.md).-## Solução de problemas+**Adding a language:** copy `web/src/i18n/pt.ts`, translate it (TypeScript fails the build if a key is missing), list it in `web/src/i18n/index.ts`, and add the server messages in `server/src/i18n.ts`.-**Parou de tocar ou "O YouTube recusou o stream"**-O YouTube muda com frequência e o yt-dlp acompanha. Abra **Ajustes** e toque em **Atualizar**. Se a correção ainda não chegou ao canal Estável, escolha **Nightly**.+## Troubleshooting-**"O YouTube pediu verificação anti-bot"**-Passe cookies de um navegador logado (o Firefox funciona melhor no Windows):+**Songs stopped playing, or "YouTube refused the stream"**+YouTube changes often and yt-dlp keeps up. Open **Settings** and click **Update**. If the fix hasn't reached the Stable channel yet, pick **Nightly**.-```powershell-$env:YTDLP_EXTRA_ARGS = "--cookies-from-browser firefox"; pnpm start+**"YouTube asked for an anti-bot check"**+Pass cookies from a signed-in browser (Firefox works best on Windows):++```bash+YTDLP_EXTRA_ARGS="--cookies-from-browser firefox" pnpm start```-**"yt-dlp não encontrado"**-No app desktop, use **Instalar** em Ajustes. No servidor, instale com `winget install yt-dlp.yt-dlp` ou defina `YTDLP_PATH`.+In Docker, export a `cookies.txt` into the data volume and set `YTDLP_EXTRA_ARGS="--cookies /data/cookies.txt"`.++**"yt-dlp wasn't found"**+In the desktop app, use **Install** in Settings. For the Node server, install it with `winget install yt-dlp.yt-dlp` or set `YTDLP_PATH`.-**O vídeo demora para começar**-Muitos vídeos não têm versão SD combinada; o servidor baixa e junta vídeo e áudio antes de tocar (alguns segundos na primeira vez, instantâneo depois, pelo cache).+**Video takes a while to start**+Many videos have no combined SD version; the server downloads and merges video and audio before playing (a few seconds the first time, instant after that thanks to the cache).-**"Esta música não tem clipe no YouTube"**-O Musike só aceita clipes publicados pelo canal do próprio artista, para não tocar covers ou versões erradas. A música continua tocando em áudio.+**"This song has no music video on YouTube"**+Musike only accepts music videos from the artist's own channel, so it never plays covers or wrong versions. The song keeps playing as audio.**iPhone**-O iOS limita a reprodução em segundo plano de PWAs; o modo Áudio funciona melhor que o Vídeo.+iOS limits background playback for PWAs; Audio mode works better than Video.## Roadmap-- [ ] Sincronização da biblioteca em nuvem (hoje: [backup em arquivo](#levar-sua-biblioteca-para-outra-instância-backup))-- [ ] Baixar faixas em MP3 / MP4-- [ ] Importar playlists do YouTube por link-- [ ] Instaladores para macOS e Linux-- [ ] Atualização automática do app desktop+- [x] Albums and artist discographies+- [x] Docker image+- [x] Languages and appearance settings+- [x] macOS app+- [x] Linux app+- [x] Android app (audio)+- [ ] Cloud sync for the library (today: [backup to a file](#moving-your-library-backup))+- [ ] Import YouTube playlists from a link+- [ ] Video mode on Android+- [ ] Automatic updates for the desktop app++Ideas and bug reports are welcome in [Issues](https://github.com/Ernani1234/musike/issues).-## Aviso legal+## Legal notice-O Musike é um projeto para **uso pessoal e educacional**. Reproduzir conteúdo do YouTube sem anúncios por extração de stream viola os [Termos de Serviço do YouTube](https://www.youtube.com/t/terms); serviços públicos que fizeram isso, como os bots Groovy e Rythm, foram encerrados após notificação do Google. Não publique o Musike como serviço, não o monetize e respeite os direitos dos artistas. O projeto não hospeda, distribui nem armazena conteúdo do YouTube além do cache local temporário de quem o executa.+Musike is a project for **personal and educational use**. Playing YouTube content without ads by extracting its streams goes against [YouTube's Terms of Service](https://www.youtube.com/t/terms); public services that did this, such as the Groovy and Rythm bots, were shut down after notices from Google. Don't offer Musike as a public service, don't monetize it, and respect the artists' rights. The project doesn't host, distribute or store YouTube content beyond the temporary local cache of whoever runs it.-## Licença+## License[MIT](LICENSE) © 2026 Ernani Netodiff --git a/desktop/build/collect.cjs b/desktop/build/collect.cjsnew file mode 100644index 0000000..d68e096--- /dev/null+++ b/desktop/build/collect.cjs@@ -0,0 +1,23 @@+// electron-builder hook (artifactBuildCompleted): copies each finished download to release/ at the repository root,+// named after its system: Musike-Setup-1.4.0-Windows.exe, Musike-Setup-1.4.0-macOS-arm64.dmg,+// Musike-Setup-1.4.0-Linux-x64.deb… The Android build (mobile/scripts/build-apk.mjs) puts its APK there too.+const { copyFileSync, mkdirSync } = require("node:fs");+const path = require("node:path");++const SYSTEMS = { win32: "Windows", darwin: "macOS", linux: "Linux" };+const ARCHS = ["ia32", "x64", "armv7l", "arm64", "universal"]; // electron-builder's Arch enum, in order+const DOWNLOADS = new Set([".exe", ".dmg", ".AppImage", ".deb"]);+const release = path.resolve(__dirname, "..", "..", "release");++module.exports = function collect(artifact) {+ const ext = path.extname(artifact.file);+ // Skip by-products such as blockmaps.+ if (!DOWNLOADS.has(ext) || artifact.file.includes("__uninstaller")) return;+ const system = SYSTEMS[artifact.packager.platform.nodeName];+ // Windows ships one build; macOS and Linux one per processor.+ const arch = system === "Windows" || artifact.arch == null ? "" : `-${ARCHS[artifact.arch]}`;+ const name = `Musike-Setup-${artifact.packager.appInfo.version}-${system}${arch}${ext}`;+ mkdirSync(release, { recursive: true });+ copyFileSync(artifact.file, path.join(release, name));+ console.log(` • collected ${path.join("release", name)}`);+};diff --git a/desktop/build/icon-mac.png b/desktop/build/icon-mac.pngnew file mode 100644index 0000000..8947dddBinary files /dev/null and b/desktop/build/icon-mac.png differdiff --git a/desktop/package.json b/desktop/package.jsonindex 60b1eb4..c3a5a4d 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -1,15 +1,19 @@{"name": "musike-desktop","productName": "Musike",- "version": "1.2.0",+ "version": "1.4.0","description": "Your music, uninterrupted.","author": "Musike",+ "homepage": "https://github.com/Ernani1234/musike",+ "desktopName": "musike.desktop","private": true,"main": "dist/main.mjs","scripts": {"bundle": "node scripts/bundle.mjs","start": "pnpm --filter @musike/web build && node scripts/bundle.mjs && electron .","dist": "pnpm --filter @musike/web build && node scripts/bundle.mjs && electron-builder --win nsis --publish never",+ "dist:mac": "pnpm --filter @musike/web build && node scripts/bundle.mjs && electron-builder --mac dmg --publish never",+ "dist:linux": "pnpm --filter @musike/web build && node scripts/bundle.mjs && electron-builder --linux AppImage deb --publish never","typecheck": "tsc --noEmit"},"build": {@@ -17,7 +21,7 @@"productName": "Musike","copyright": "Musike","directories": {- "output": "release",+ "output": "out","buildResources": "build"},"files": [@@ -30,6 +34,7 @@"to": "web"}],+ "artifactBuildCompleted": "build/collect.cjs","asar": true,"npmRebuild": false,"win": {@@ -44,6 +49,55 @@"icon": "build/icon.ico","artifactName": "Musike-Setup-${version}.${ext}"},+ "mac": {+ "target": [+ {+ "target": "dmg",+ "arch": [+ "arm64",+ "x64"+ ]+ }+ ],+ "icon": "build/icon-mac.png",+ "category": "public.app-category.music",+ "minimumSystemVersion": "12.0",+ "darkModeSupport": true,+ "identity": "-",+ "hardenedRuntime": false,+ "gatekeeperAssess": false+ },+ "linux": {+ "target": [+ {+ "target": "AppImage",+ "arch": [+ "x64",+ "arm64"+ ]+ },+ {+ "target": "deb",+ "arch": [+ "x64",+ "arm64"+ ]+ }+ ],+ "icon": "build/icon.png",+ "executableName": "musike",+ "syncDesktopName": true,+ "category": "AudioVideo",+ "synopsis": "Your music, uninterrupted.",+ "description": "A personal music player for YouTube's catalog: songs and music videos, with no ads and no account.",+ "maintainer": "Musike <https://github.com/Ernani1234/musike>"+ },+ "deb": {+ "packageName": "musike"+ },+ "dmg": {+ "title": "Musike ${version}"+ },"nsis": {"oneClick": false,"perMachine": false,diff --git a/desktop/src/main.mts b/desktop/src/main.mtsindex 62aec8a..9931851 100644--- a/desktop/src/main.mts+++ b/desktop/src/main.mts@@ -10,6 +10,7 @@ import { backupLibraryOnUpdate } from "./backup.js";const here = path.dirname(fileURLToPath(import.meta.url));const PORT = 4280; // fixed so the web origin (and its saved settings) stays the same between launches+const isMac = process.platform === "darwin";if (!app.requestSingleInstanceLock()) {app.quit();@@ -116,9 +117,12 @@ function createMainWindow(url: string): BrowserWindow {title: "Musike",icon: path.join(here, "icon.png"),backgroundColor: THEME.dark.color,- // Our own title bar (drawn by the web app) with native window buttons on top.+ // Our own title bar (drawn by the web app) with the native window buttons on top of it:+ // macOS traffic lights on the left, centred in the bar; Windows and Linux controls on the right.titleBarStyle: "hidden",- titleBarOverlay: { ...THEME.dark, height: TITLEBAR_HEIGHT },+ ...(isMac+ ? { trafficLightPosition: { x: 14, y: (TITLEBAR_HEIGHT - 14) / 2 } }+ : { titleBarOverlay: { ...THEME.dark, height: TITLEBAR_HEIGHT } }),webPreferences: {preload: path.join(here, "preload.cjs"),contextIsolation: true,@@ -182,7 +186,7 @@ async function launch() {ipcMain.on("musike:theme", (event, theme: "dark" | "light") => {const win = BrowserWindow.fromWebContents(event.sender);const colors = THEME[theme] ?? THEME.dark;- win?.setTitleBarOverlay({ ...colors, height: TITLEBAR_HEIGHT });+ if (!isMac) win?.setTitleBarOverlay({ ...colors, height: TITLEBAR_HEIGHT });win?.setBackgroundColor(colors.color);});@@ -213,6 +217,9 @@ app.on("window-all-closed", () => app.quit());app.on("before-quit", () => void server?.close());void app.whenReady().then(() => {- Menu.setApplicationMenu(null);+ // macOS needs an app menu: without the Edit menu, Cmd+C/V/A don't reach text fields, and Cmd+Q has no home.+ Menu.setApplicationMenu(+ isMac ? Menu.buildFromTemplate([{ role: "appMenu" }, { role: "editMenu" }, { role: "windowMenu" }]) : null,+ );return launch();});diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 0000000..9259d2c--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,22 @@+# Musike on any machine with Docker: docker compose up -d, then open http://<this machine>:4180+services:+ musike:+ image: ghcr.io/ernani1234/musike:latest+ # Or build it from this folder instead:+ # build: .+ container_name: musike+ ports:+ - "4180:4180"+ volumes:+ - musike-data:/data # library: playlists, favorites, history+ - musike-cache:/cache # HD videos already downloaded+ environment:+ # Optional, see the README: cookies for YouTube's bot checks, region for search results.+ # YTDLP_EXTRA_ARGS: "--cookies /data/cookies.txt"+ # MUSIKE_LOCATION: "US"+ MUSIKE_CACHE_MAX_MB: "2048"+ restart: unless-stopped++volumes:+ musike-data:+ musike-cache:diff --git a/docs/screenshots/album.jpg b/docs/screenshots/album.jpgnew file mode 100644index 0000000..a54ec96Binary files /dev/null and b/docs/screenshots/album.jpg differdiff --git a/docs/screenshots/atualizar-yt-dlp.png b/docs/screenshots/atualizar-yt-dlp.pngdeleted file mode 100644index 198581d..0000000Binary files a/docs/screenshots/atualizar-yt-dlp.png and /dev/null differdiff --git a/docs/screenshots/backup.png b/docs/screenshots/backup.pngdeleted file mode 100644index 6d2e32e..0000000Binary files a/docs/screenshots/backup.png and /dev/null differdiff --git a/docs/screenshots/cinema.jpg b/docs/screenshots/cinema.jpgnew file mode 100644index 0000000..a95dc0aBinary files /dev/null and b/docs/screenshots/cinema.jpg differdiff --git a/docs/screenshots/customize.jpg b/docs/screenshots/customize.jpgnew file mode 100644index 0000000..0fe51f0Binary files /dev/null and b/docs/screenshots/customize.jpg differdiff --git a/docs/screenshots/desktop-app.png b/docs/screenshots/desktop-app.pngdeleted file mode 100644index 9897d25..0000000Binary files a/docs/screenshots/desktop-app.png and /dev/null differdiff --git a/docs/screenshots/genre.jpg b/docs/screenshots/genre.jpgnew file mode 100644index 0000000..a9b5f03Binary files /dev/null and b/docs/screenshots/genre.jpg differdiff --git a/docs/screenshots/home.jpg b/docs/screenshots/home.jpgnew file mode 100644index 0000000..b6ee1b3Binary files /dev/null and b/docs/screenshots/home.jpg differdiff --git a/docs/screenshots/mobile-busca.png b/docs/screenshots/mobile-busca.pngdeleted file mode 100644index 4ad72ba..0000000Binary files a/docs/screenshots/mobile-busca.png and /dev/null differdiff --git a/docs/screenshots/mobile-tocando.png b/docs/screenshots/mobile-tocando.pngdeleted file mode 100644index 5918e40..0000000Binary files a/docs/screenshots/mobile-tocando.png and /dev/null differdiff --git a/docs/screenshots/mobile.jpg b/docs/screenshots/mobile.jpgnew file mode 100644index 0000000..9ec7c67Binary files /dev/null and b/docs/screenshots/mobile.jpg differdiff --git a/docs/screenshots/modo-cinema.png b/docs/screenshots/modo-cinema.pngdeleted file mode 100644index 3212fa3..0000000Binary files a/docs/screenshots/modo-cinema.png and /dev/null differdiff --git a/docs/screenshots/search-a-list.jpg b/docs/screenshots/search-a-list.jpgnew file mode 100644index 0000000..cfbfd52Binary files /dev/null and b/docs/screenshots/search-a-list.jpg differdiff --git a/mobile/android/.gitignore b/mobile/android/.gitignorenew file mode 100644index 0000000..f2f1c7c--- /dev/null+++ b/mobile/android/.gitignore@@ -0,0 +1,101 @@+# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore++# Built application files+*.apk+*.aar+*.ap_+*.aab++# Files for the ART/Dalvik VM+*.dex++# Java class files+*.class++# Generated files+bin/+gen/+out/+# Uncomment the following line in case you need and you don't have the release build type files in your app+# release/++# Gradle files+.gradle/+build/++# Local configuration file (sdk path, etc)+local.properties++# Proguard folder generated by Eclipse+proguard/++# Log Files+*.log++# Android Studio Navigation editor temp files+.navigation/++# Android Studio captures folder+captures/++# IntelliJ+*.iml+.idea/workspace.xml+.idea/tasks.xml+.idea/gradle.xml+.idea/assetWizardSettings.xml+.idea/dictionaries+.idea/libraries+# Android Studio 3 in .gitignore file.+.idea/caches+.idea/modules.xml+# Comment next line if keeping position of elements in Navigation Editor is relevant for you+.idea/navEditor.xml++# Keystore files: the release signing key never goes in the repository+*.jks+*.keystore+keystore.properties++# External native build folder generated in Android Studio 2.2 and later+.externalNativeBuild+.cxx/++# Google Services (e.g. APIs or Firebase)+# google-services.json++# Freeline+freeline.py+freeline/+freeline_project_description.json++# fastlane+fastlane/report.xml+fastlane/Preview.html+fastlane/screenshots+fastlane/test_output+fastlane/readme.md++# Version control+vcs.xml++# lint+lint/intermediates/+lint/generated/+lint/outputs/+lint/tmp/+# lint/reports/++# Android Profiling+*.hprof++# Cordova plugins for Capacitor+capacitor-cordova-android-plugins++# Copied web assets+app/src/main/assets/public++# Generated Config files+app/src/main/assets/capacitor.config.json+app/src/main/assets/capacitor.plugins.json+app/src/main/res/xml/config.xmldiff --git a/mobile/android/app/.gitignore b/mobile/android/app/.gitignorenew file mode 100644index 0000000..043df80--- /dev/null+++ b/mobile/android/app/.gitignore@@ -0,0 +1,2 @@+/build/*+!/build/.npmkeepdiff --git a/mobile/android/app/build.gradle b/mobile/android/app/build.gradlenew file mode 100644index 0000000..4215baa--- /dev/null+++ b/mobile/android/app/build.gradle@@ -0,0 +1,77 @@+apply plugin: 'com.android.application'++// One version for the whole app: mobile/package.json (1.3.0 becomes versionCode 10300).+def appVersion = new groovy.json.JsonSlurper().parse(file('../../package.json')).version+def versionParts = appVersion.tokenize('.').collect { it.find(/\d+/).toInteger() }++// Release signing, kept out of the repository: android/keystore.properties locally, environment variables in CI.+// Without either, the release APK is built unsigned.+def keystoreProps = new Properties()+def keystoreFile = rootProject.file('keystore.properties')+if (keystoreFile.exists()) keystoreFile.withInputStream { keystoreProps.load(it) }+def signingValue = { String prop, String env -> keystoreProps.getProperty(prop) ?: System.getenv(env) }+def releaseStore = signingValue('storeFile', 'MUSIKE_KEYSTORE')++android {+ namespace = "app.musike.android"+ compileSdk = rootProject.ext.compileSdkVersion+ defaultConfig {+ applicationId "app.musike.android"+ minSdkVersion rootProject.ext.minSdkVersion+ targetSdkVersion rootProject.ext.targetSdkVersion+ versionCode versionParts[0] * 10000 + versionParts[1] * 100 + versionParts[2]+ versionName appVersion+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"+ aaptOptions {+ // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.+ // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61+ ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'+ }+ }+ signingConfigs {+ if (releaseStore) {+ release {+ storeFile rootProject.file(releaseStore)+ storePassword signingValue('storePassword', 'MUSIKE_KEYSTORE_PASSWORD')+ keyAlias signingValue('keyAlias', 'MUSIKE_KEY_ALIAS')+ keyPassword signingValue('keyPassword', 'MUSIKE_KEY_PASSWORD')+ }+ }+ }+ buildTypes {+ release {+ if (releaseStore) signingConfig signingConfigs.release+ minifyEnabled false+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'+ }+ }+}++repositories {+ flatDir{+ dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'+ }+}++dependencies {+ implementation fileTree(include: ['*.jar'], dir: 'libs')+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"+ implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"+ implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"+ implementation project(':capacitor-android')+ testImplementation "junit:junit:$junitVersion"+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"+ implementation project(':capacitor-cordova-android-plugins')+}++apply from: 'capacitor.build.gradle'++try {+ def servicesJSON = file('google-services.json')+ if (servicesJSON.text) {+ apply plugin: 'com.google.gms.google-services'+ }+} catch(Exception e) {+ logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")+}diff --git a/mobile/android/app/capacitor.build.gradle b/mobile/android/app/capacitor.build.gradlenew file mode 100644index 0000000..d70a2b0--- /dev/null+++ b/mobile/android/app/capacitor.build.gradle@@ -0,0 +1,21 @@+// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN++android {+ compileOptions {+ sourceCompatibility JavaVersion.VERSION_21+ targetCompatibility JavaVersion.VERSION_21+ }+}++apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"+dependencies {+ implementation project(':capacitor-app')+ implementation project(':capacitor-filesystem')+ implementation project(':capacitor-share')++}+++if (hasProperty('postBuildExtras')) {+ postBuildExtras()+}diff --git a/mobile/android/app/proguard-rules.pro b/mobile/android/app/proguard-rules.pronew file mode 100644index 0000000..f1b4245--- /dev/null+++ b/mobile/android/app/proguard-rules.pro@@ -0,0 +1,21 @@+# Add project specific ProGuard rules here.+# You can control the set of applied configuration files using the+# proguardFiles setting in build.gradle.+#+# For more details, see+# http://developer.android.com/guide/developing/tools/proguard.html++# If your project uses WebView with JS, uncomment the following+# and specify the fully qualified class name to the JavaScript interface+# class:+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {+# public *;+#}++# Uncomment this to preserve the line number information for+# debugging stack traces.+#-keepattributes SourceFile,LineNumberTable++# If you keep the line number information, uncomment this to+# hide the original source file name.+#-renamesourcefileattribute SourceFilediff --git a/mobile/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/mobile/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.javanew file mode 100644index 0000000..f2c2217--- /dev/null+++ b/mobile/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java@@ -0,0 +1,26 @@+package com.getcapacitor.myapp;++import static org.junit.Assert.*;++import android.content.Context;+import androidx.test.ext.junit.runners.AndroidJUnit4;+import androidx.test.platform.app.InstrumentationRegistry;+import org.junit.Test;+import org.junit.runner.RunWith;++/**+ * Instrumented test, which will execute on an Android device.+ *+ * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>+ */+@RunWith(AndroidJUnit4.class)+public class ExampleInstrumentedTest {++ @Test+ public void useAppContext() throws Exception {+ // Context of the app under test.+ Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();++ assertEquals("com.getcapacitor.app", appContext.getPackageName());+ }+}diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..3030edc--- /dev/null+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,51 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- Permissions -->++ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />++ <application+ android:allowBackup="true"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher_round"+ android:supportsRtl="true"+ android:theme="@style/AppTheme">++ <activity+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"+ android:name=".MainActivity"+ android:label="@string/title_activity_main"+ android:theme="@style/AppTheme.NoActionBarLaunch"+ android:launchMode="singleTask"+ android:exported="true">++ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>++ </activity>++ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.fileprovider"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths"></meta-data>+ </provider>++ <!-- Keeps the music going with the screen off; shows the media notification and lock screen controls. -->+ <service+ android:name=".PlaybackService"+ android:exported="false"+ android:foregroundServiceType="mediaPlayback" />+ </application>++</manifest>diff --git a/mobile/android/app/src/main/java/app/musike/android/MainActivity.java b/mobile/android/app/src/main/java/app/musike/android/MainActivity.javanew file mode 100644index 0000000..b76d646--- /dev/null+++ b/mobile/android/app/src/main/java/app/musike/android/MainActivity.java@@ -0,0 +1,19 @@+package app.musike.android;++import android.graphics.Color;+import android.os.Bundle;+import androidx.activity.EdgeToEdge;+import androidx.activity.SystemBarStyle;+import com.getcapacitor.BridgeActivity;++public class MainActivity extends BridgeActivity {++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ registerPlugin(MusikePlaybackPlugin.class);+ super.onCreate(savedInstanceState);+ // Draw behind the status and navigation bars on every Android version; the page pads itself+ // (env(safe-area-inset-*)) and the SystemBars plugin keeps the icons readable for the theme.+ EdgeToEdge.enable(this, SystemBarStyle.dark(Color.TRANSPARENT), SystemBarStyle.dark(Color.TRANSPARENT));+ }+}diff --git a/mobile/android/app/src/main/java/app/musike/android/MusikePlaybackPlugin.java b/mobile/android/app/src/main/java/app/musike/android/MusikePlaybackPlugin.javanew file mode 100644index 0000000..7033c57--- /dev/null+++ b/mobile/android/app/src/main/java/app/musike/android/MusikePlaybackPlugin.java@@ -0,0 +1,66 @@+package app.musike.android;++import android.os.Handler;+import android.os.Looper;+import android.os.SystemClock;+import com.getcapacitor.JSObject;+import com.getcapacitor.Plugin;+import com.getcapacitor.PluginCall;+import com.getcapacitor.PluginMethod;+import com.getcapacitor.annotation.CapacitorPlugin;++/**+ * The app's side of PlaybackService (web/src/native/media.ts): the player reports the track and its progress+ * through update(), and the buttons pressed outside the app come back as "action" events.+ */+@CapacitorPlugin(name = "MusikePlayback")+public class MusikePlaybackPlugin extends Plugin {++ private final Handler main = new Handler(Looper.getMainLooper());++ @Override+ public void load() {+ PlaybackService.listener = (action, position) -> {+ JSObject event = new JSObject();+ event.put("action", action);+ if (position >= 0) event.put("position", position);+ notifyListeners("action", event);+ };+ }++ @PluginMethod+ public void update(PluginCall call) {+ String title = call.getString("title");+ String artist = call.getString("artist");+ String album = call.getString("album");+ String artwork = call.getString("artwork");+ Boolean playing = call.getBoolean("playing");+ Double position = call.getDouble("position");+ Double duration = call.getDouble("duration");+ main.post(() -> {+ PlaybackService.NowPlaying state = PlaybackService.state;+ long now = SystemClock.elapsedRealtime();+ if (position != null) {+ state.positionMs = Math.max(0, Math.round(position * 1000));+ } else {+ state.positionMs = state.currentPositionMs();+ }+ state.positionAt = now;+ if (title != null) state.title = title;+ if (artist != null) state.artist = artist;+ if (album != null) state.album = album;+ if (artwork != null) state.artwork = artwork;+ if (playing != null) state.playing = playing;+ if (duration != null) state.durationMs = Math.max(0, Math.round(duration * 1000));+ else if (title != null) state.durationMs = 0; // a new track, not loaded yet+ PlaybackService.refresh(getContext());+ });+ call.resolve();+ }++ @Override+ protected void handleOnDestroy() {+ PlaybackService.listener = null;+ PlaybackService.shutdown(getContext());+ }+}diff --git a/mobile/android/app/src/main/java/app/musike/android/PlaybackService.java b/mobile/android/app/src/main/java/app/musike/android/PlaybackService.javanew file mode 100644index 0000000..d16621b--- /dev/null+++ b/mobile/android/app/src/main/java/app/musike/android/PlaybackService.java@@ -0,0 +1,456 @@+package app.musike.android;++import android.annotation.SuppressLint;+import android.app.Notification;+import android.app.NotificationChannel;+import android.app.NotificationManager;+import android.app.PendingIntent;+import android.app.Service;+import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;+import android.content.IntentFilter;+import android.content.pm.ServiceInfo;+import android.graphics.Bitmap;+import android.graphics.BitmapFactory;+import android.graphics.drawable.Icon;+import android.media.AudioAttributes;+import android.media.AudioFocusRequest;+import android.media.AudioManager;+import android.media.MediaMetadata;+import android.media.session.MediaSession;+import android.media.session.PlaybackState;+import android.os.Build;+import android.os.Handler;+import android.os.IBinder;+import android.os.Looper;+import android.os.PowerManager;+import android.os.SystemClock;+import android.util.Log;+import java.io.InputStream;+import java.net.HttpURLConnection;+import java.net.URL;++/**+ * Keeps Musike alive while music plays and connects it to the system: the media notification, the lock screen,+ * headphone and Bluetooth buttons, phone calls and other apps taking over the audio. The music itself plays in+ * the WebView; this service only mirrors what the app reports (see MusikePlaybackPlugin) and relays the buttons back.+ * Everything here runs on the main thread.+ */+// A media-session notification doesn't need the notification permission (Android 13+ exempts it).+@SuppressLint("NotificationPermission")+public class PlaybackService extends Service {++ private static final String TAG = "MusikePlayback";+ private static final String CHANNEL = "playback";+ private static final int NOTIFICATION_ID = 1;+ private static final String ACTION = "app.musike.android.action.";++ /** What the app last reported. */+ static final class NowPlaying {+ String title = "";+ String artist = "";+ String album = "";+ String artwork = "";+ boolean playing;+ long positionMs;+ /** When positionMs was measured (elapsedRealtime), so the system can keep the clock moving on its own. */+ long positionAt = SystemClock.elapsedRealtime();+ long durationMs;++ long currentPositionMs() {+ return playing ? positionMs + (SystemClock.elapsedRealtime() - positionAt) : positionMs;+ }+ }++ /** Receives the buttons pressed in the notification, on the lock screen or on headphones. */+ interface Listener {+ /** position is in seconds, or negative when the action has none. */+ void onAction(String action, double position);+ }++ static final NowPlaying state = new NowPlaying();+ static Listener listener;+ private static PlaybackService instance;++ private final Handler main = new Handler(Looper.getMainLooper());+ private MediaSession session;+ private NotificationManager notifications;+ private AudioManager audio;+ private AudioFocusRequest focusRequest;+ private PowerManager.WakeLock wakeLock;+ private boolean foreground;+ private boolean hasFocus;+ private boolean resumeAfterFocusLoss;+ private boolean noisyRegistered;+ private String artworkUrl = "";+ private Bitmap artwork;++ /** Shows what the app reported, starting the service when music starts. */+ static void refresh(Context context) {+ if (instance != null) {+ instance.render();+ return;+ }+ if (!state.playing) return;+ Intent intent = new Intent(context, PlaybackService.class);+ try {+ if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent);+ else context.startService(intent);+ } catch (RuntimeException e) {+ // Android may refuse while the app is in the background; the next report from the app tries again.+ Log.w(TAG, "Could not start the playback service", e);+ }+ }++ static void shutdown(Context context) {+ context.stopService(new Intent(context, PlaybackService.class));+ }++ @Override+ public void onCreate() {+ super.onCreate();+ instance = this;+ notifications = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);+ audio = (AudioManager) getSystemService(AUDIO_SERVICE);+ wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Musike:playback");+ wakeLock.setReferenceCounted(false);++ if (Build.VERSION.SDK_INT >= 26) {+ NotificationChannel channel = new NotificationChannel(CHANNEL, getString(R.string.playback_channel), NotificationManager.IMPORTANCE_LOW);+ channel.setShowBadge(false);+ notifications.createNotificationChannel(channel);+ }++ session = new MediaSession(this, "Musike");+ session.setSessionActivity(openApp());+ if (Build.VERSION.SDK_INT < 26) {+ session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);+ }+ session.setCallback(+ new MediaSession.Callback() {+ @Override+ public void onPlay() {+ emit("play", -1);+ }++ @Override+ public void onPause() {+ emit("pause", -1);+ }++ @Override+ public void onStop() {+ emit("pause", -1);+ }++ @Override+ public void onSkipToNext() {+ emit("next", -1);+ }++ @Override+ public void onSkipToPrevious() {+ emit("previous", -1);+ }++ @Override+ public void onSeekTo(long positionMs) {+ // Show the new position right away; the app confirms it once the audio gets there.+ state.positionMs = positionMs;+ state.positionAt = SystemClock.elapsedRealtime();+ render();+ emit("seek", positionMs / 1000.0);+ }+ },+ main+ );+ session.setActive(true);+ }++ @Override+ public int onStartCommand(Intent intent, int flags, int startId) {+ String action = intent == null ? null : intent.getAction();+ if (action != null && action.startsWith(ACTION)) {+ String name = action.substring(ACTION.length());+ if (listener == null) {+ // A leftover notification from an app Android already closed: there is no music to control.+ stopSelf();+ return START_NOT_STICKY;+ }+ if (name.equals("dismiss")) {+ if (!state.playing) stopSelf();+ } else {+ emit(name, -1);+ }+ } else {+ // Started by the app with startForegroundService: Android requires startForeground right away,+ // even if the music was paused again in the meantime.+ goForeground(buildNotification());+ }+ render();+ return START_NOT_STICKY;+ }++ @Override+ public void onTaskRemoved(Intent rootIntent) {+ // Swiping Musike away closes the page that plays the music, so the controls have nothing left to control.+ stopSelf();+ }++ @Override+ public void onDestroy() {+ instance = null;+ releaseWakeLock();+ setNoisyReceiver(false);+ abandonFocus();+ session.setActive(false);+ session.release();+ stopForeground(STOP_FOREGROUND_REMOVE);+ notifications.cancel(NOTIFICATION_ID);+ super.onDestroy();+ }++ @Override+ public IBinder onBind(Intent intent) {+ return null;+ }++ private void emit(String action, double position) {+ if (listener != null) listener.onAction(action, position);+ }++ private void render() {+ loadArtwork(state.artwork);+ session.setMetadata(metadata());+ session.setPlaybackState(playbackState());+ Notification notification = buildNotification();+ if (state.playing) {+ // Renewed by every progress report from the app; lapses if the app stops reporting.+ wakeLock.acquire(30 * 60 * 1000L);+ setNoisyReceiver(true);+ if (!hasFocus) requestFocus();+ goForeground(notification);+ } else {+ releaseWakeLock();+ setNoisyReceiver(false);+ if (foreground) {+ // Paused: the notification stays (and can be swiped away), but Android may reclaim the service.+ stopForeground(STOP_FOREGROUND_DETACH);+ foreground = false;+ }+ notifications.notify(NOTIFICATION_ID, notification);+ }+ }++ private void goForeground(Notification notification) {+ if (foreground) {+ notifications.notify(NOTIFICATION_ID, notification);+ return;+ }+ try {+ if (Build.VERSION.SDK_INT >= 29) startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);+ else startForeground(NOTIFICATION_ID, notification);+ foreground = true;+ } catch (RuntimeException e) {+ // Resuming from the background can be refused on recent Android; keep the controls up regardless.+ Log.w(TAG, "Could not enter the foreground", e);+ notifications.notify(NOTIFICATION_ID, notification);+ }+ }++ private MediaMetadata metadata() {+ MediaMetadata.Builder b = new MediaMetadata.Builder()+ .putString(MediaMetadata.METADATA_KEY_TITLE, state.title)+ .putString(MediaMetadata.METADATA_KEY_ARTIST, state.artist)+ .putString(MediaMetadata.METADATA_KEY_ALBUM, state.album)+ .putLong(MediaMetadata.METADATA_KEY_DURATION, state.durationMs > 0 ? state.durationMs : -1);+ if (artwork != null) b.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, artwork);+ return b.build();+ }++ private PlaybackState playbackState() {+ long actions =+ PlaybackState.ACTION_PLAY |+ PlaybackState.ACTION_PAUSE |+ PlaybackState.ACTION_PLAY_PAUSE |+ PlaybackState.ACTION_STOP |+ PlaybackState.ACTION_SKIP_TO_NEXT |+ PlaybackState.ACTION_SKIP_TO_PREVIOUS |+ PlaybackState.ACTION_SEEK_TO;+ return new PlaybackState.Builder()+ .setActions(actions)+ .setState(+ state.playing ? PlaybackState.STATE_PLAYING : PlaybackState.STATE_PAUSED,+ state.positionMs,+ state.playing ? 1f : 0f,+ state.positionAt+ )+ .build();+ }++ private Notification buildNotification() {+ Notification.Builder b = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(this, CHANNEL) : new Notification.Builder(this);+ b.setSmallIcon(R.drawable.ic_stat_musike)+ .setContentTitle(state.title)+ .setContentText(state.artist)+ .setLargeIcon(artwork)+ .setContentIntent(openApp())+ .setDeleteIntent(command("dismiss"))+ .setVisibility(Notification.VISIBILITY_PUBLIC)+ .setShowWhen(false)+ .setOngoing(state.playing)+ .setColor(0xFFC3EC52)+ .addAction(action(R.drawable.ic_media_previous, R.string.playback_previous, "previous"))+ .addAction(+ state.playing+ ? action(R.drawable.ic_media_pause, R.string.playback_pause, "pause")+ : action(R.drawable.ic_media_play, R.string.playback_play, "play")+ )+ .addAction(action(R.drawable.ic_media_next, R.string.playback_next, "next"))+ .setStyle(new Notification.MediaStyle().setMediaSession(session.getSessionToken()).setShowActionsInCompactView(0, 1, 2));+ return b.build();+ }++ private Notification.Action action(int icon, int label, String name) {+ return new Notification.Action.Builder(Icon.createWithResource(this, icon), getString(label), command(name)).build();+ }++ private PendingIntent command(String name) {+ Intent intent = new Intent(this, PlaybackService.class).setAction(ACTION + name);+ return PendingIntent.getService(this, name.hashCode(), intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);+ }++ private PendingIntent openApp() {+ Intent intent = new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);+ return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);+ }++ private void releaseWakeLock() {+ if (wakeLock.isHeld()) wakeLock.release();+ }++ // Audio focus: pause for calls and other players, and pick up again after a short interruption.++ private final AudioManager.OnAudioFocusChangeListener onFocusChange = (change) -> {+ switch (change) {+ case AudioManager.AUDIOFOCUS_GAIN:+ hasFocus = true;+ if (resumeAfterFocusLoss) {+ resumeAfterFocusLoss = false;+ emit("play", -1);+ }+ break;+ case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:+ hasFocus = false;+ if (state.playing) {+ resumeAfterFocusLoss = true;+ emit("pause", -1);+ }+ break;+ case AudioManager.AUDIOFOCUS_LOSS:+ hasFocus = false;+ resumeAfterFocusLoss = false;+ if (state.playing) emit("pause", -1);+ break;+ default:+ // Ducking (a navigation prompt, a notification sound): the system lowers the volume by itself.+ break;+ }+ };++ private void requestFocus() {+ int result;+ if (Build.VERSION.SDK_INT >= 26) {+ if (focusRequest == null) {+ AudioAttributes attributes = new AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_MEDIA)+ .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)+ .build();+ focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)+ .setAudioAttributes(attributes)+ .setOnAudioFocusChangeListener(onFocusChange, main)+ .build();+ }+ result = audio.requestAudioFocus(focusRequest);+ } else {+ result = audio.requestAudioFocus(onFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);+ }+ hasFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;+ resumeAfterFocusLoss = false;+ }++ private void abandonFocus() {+ if (Build.VERSION.SDK_INT >= 26) {+ if (focusRequest != null) audio.abandonAudioFocusRequest(focusRequest);+ } else {+ audio.abandonAudioFocus(onFocusChange);+ }+ hasFocus = false;+ }++ // Headphones unplugged or Bluetooth disconnected: pause instead of playing out loud.++ private final BroadcastReceiver onNoisy = new BroadcastReceiver() {+ @Override+ public void onReceive(Context context, Intent intent) {+ if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction()) && state.playing) emit("pause", -1);+ }+ };++ private void setNoisyReceiver(boolean on) {+ if (on == noisyRegistered) return;+ if (on) {+ IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);+ if (Build.VERSION.SDK_INT >= 33) registerReceiver(onNoisy, filter, RECEIVER_NOT_EXPORTED);+ else registerReceiver(onNoisy, filter);+ } else {+ unregisterReceiver(onNoisy);+ }+ noisyRegistered = on;+ }++ // Cover art for the notification and the lock screen, downloaded once per track.++ private void loadArtwork(String url) {+ if (url.equals(artworkUrl)) return;+ artworkUrl = url;+ artwork = null;+ if (url.isEmpty()) return;+ new Thread(+ () -> {+ Bitmap bitmap = download(url);+ main.post(() -> {+ if (instance != this || !url.equals(artworkUrl) || bitmap == null) return;+ artwork = bitmap;+ render();+ });+ },+ "musike-artwork"+ ).start();+ }++ private static Bitmap download(String url) {+ HttpURLConnection connection = null;+ try {+ connection = (HttpURLConnection) new URL(url).openConnection();+ connection.setConnectTimeout(10_000);+ connection.setReadTimeout(10_000);+ try (InputStream in = connection.getInputStream()) {+ Bitmap bitmap = BitmapFactory.decodeStream(in);+ if (bitmap == null) return null;+ // Large bitmaps can exceed what the system accepts for a notification.+ int max = 512;+ int side = Math.max(bitmap.getWidth(), bitmap.getHeight());+ if (side <= max) return bitmap;+ float scale = (float) max / side;+ return Bitmap.createScaledBitmap(bitmap, Math.round(bitmap.getWidth() * scale), Math.round(bitmap.getHeight() * scale), true);+ }+ } catch (Exception e) {+ Log.w(TAG, "Could not load the cover art", e);+ return null;+ } finally {+ if (connection != null) connection.disconnect();+ }+ }+}diff --git a/mobile/android/app/src/main/res/drawable-land-hdpi/splash.png b/mobile/android/app/src/main/res/drawable-land-hdpi/splash.pngnew file mode 100644index 0000000..39805baBinary files /dev/null and b/mobile/android/app/src/main/res/drawable-land-hdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-land-mdpi/splash.png b/mobile/android/app/src/main/res/drawable-land-mdpi/splash.pngnew file mode 100644index 0000000..ec394f0Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-land-mdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-land-xhdpi/splash.png b/mobile/android/app/src/main/res/drawable-land-xhdpi/splash.pngnew file mode 100644index 0000000..7300638Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-land-xhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/mobile/android/app/src/main/res/drawable-land-xxhdpi/splash.pngnew file mode 100644index 0000000..8738551Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-land-xxhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/mobile/android/app/src/main/res/drawable-land-xxxhdpi/splash.pngnew file mode 100644index 0000000..d784193Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-port-hdpi/splash.png b/mobile/android/app/src/main/res/drawable-port-hdpi/splash.pngnew file mode 100644index 0000000..d21e278Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-port-hdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-port-mdpi/splash.png b/mobile/android/app/src/main/res/drawable-port-mdpi/splash.pngnew file mode 100644index 0000000..59d7fc7Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-port-mdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-port-xhdpi/splash.png b/mobile/android/app/src/main/res/drawable-port-xhdpi/splash.pngnew file mode 100644index 0000000..7333dccBinary files /dev/null and b/mobile/android/app/src/main/res/drawable-port-xhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/mobile/android/app/src/main/res/drawable-port-xxhdpi/splash.pngnew file mode 100644index 0000000..e0dbd86Binary files /dev/null and b/mobile/android/app/src/main/res/drawable-port-xxhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/mobile/android/app/src/main/res/drawable-port-xxxhdpi/splash.pngnew file mode 100644index 0000000..aab981eBinary files /dev/null and b/mobile/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differdiff --git a/mobile/android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/mobile/android/app/src/main/res/drawable/ic_launcher_monochrome.xmlnew file mode 100644index 0000000..7fd42aa--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_launcher_monochrome.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Themed icon (Android 13+): the logo at the size of the colored one, in the launcher's tint. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="108"+ android:viewportHeight="108">+ <group android:translateX="32" android:translateY="32" android:scaleX="1.5714" android:scaleY="1.5714">+ <path android:fillColor="#FFFFFFFF" android:pathData="M4,0a4,4 0 0 1 4,4v20a4,4 0 0 1 -8,0v-20a4,4 0 0 1 4,-4z M14,0a4,4 0 0 1 4,4v8a4,4 0 0 1 -8,0v-8a4,4 0 0 1 4,-4z M24,0a4,4 0 0 1 4,4v20a4,4 0 0 1 -8,0v-20a4,4 0 0 1 4,-4z" />+ </group>+</vector>diff --git a/mobile/android/app/src/main/res/drawable/ic_media_next.xml b/mobile/android/app/src/main/res/drawable/ic_media_next.xmlnew file mode 100644index 0000000..1334648--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_media_next.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path android:fillColor="#FFFFFFFF" android:pathData="M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z" />+</vector>diff --git a/mobile/android/app/src/main/res/drawable/ic_media_pause.xml b/mobile/android/app/src/main/res/drawable/ic_media_pause.xmlnew file mode 100644index 0000000..48a87a5--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_media_pause.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path android:fillColor="#FFFFFFFF" android:pathData="M6,19h4V5H6v14zM14,5v14h4V5h-4z" />+</vector>diff --git a/mobile/android/app/src/main/res/drawable/ic_media_play.xml b/mobile/android/app/src/main/res/drawable/ic_media_play.xmlnew file mode 100644index 0000000..d7de48a--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_media_play.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path android:fillColor="#FFFFFFFF" android:pathData="M8,5v14l11,-7z" />+</vector>diff --git a/mobile/android/app/src/main/res/drawable/ic_media_previous.xml b/mobile/android/app/src/main/res/drawable/ic_media_previous.xmlnew file mode 100644index 0000000..d4e8d6b--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_media_previous.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path android:fillColor="#FFFFFFFF" android:pathData="M6,6h2v12H6zM9.5,12l8.5,6V6z" />+</vector>diff --git a/mobile/android/app/src/main/res/drawable/ic_stat_musike.xml b/mobile/android/app/src/main/res/drawable/ic_stat_musike.xmlnew file mode 100644index 0000000..ba40e80--- /dev/null+++ b/mobile/android/app/src/main/res/drawable/ic_stat_musike.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Musike's logo for the status bar: Android draws it in a single color. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="34"+ android:viewportHeight="34">+ <group android:translateX="3" android:translateY="3">+ <path android:fillColor="#FFFFFFFF" android:pathData="M4,0a4,4 0 0 1 4,4v20a4,4 0 0 1 -8,0v-20a4,4 0 0 1 4,-4z M14,0a4,4 0 0 1 4,4v8a4,4 0 0 1 -8,0v-8a4,4 0 0 1 4,-4z M24,0a4,4 0 0 1 4,4v20a4,4 0 0 1 -8,0v-20a4,4 0 0 1 4,-4z" />+ </group>+</vector>diff --git a/mobile/android/app/src/main/res/drawable/splash.png b/mobile/android/app/src/main/res/drawable/splash.pngnew file mode 100644index 0000000..ec394f0Binary files /dev/null and b/mobile/android/app/src/main/res/drawable/splash.png differdiff --git a/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 0000000..858386c--- /dev/null+++ b/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background"/>+ <foreground android:drawable="@mipmap/ic_launcher_foreground"/>+ <monochrome android:drawable="@drawable/ic_launcher_monochrome"/>+</adaptive-icon>diff --git a/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xmlnew file mode 100644index 0000000..858386c--- /dev/null+++ b/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background"/>+ <foreground android:drawable="@mipmap/ic_launcher_foreground"/>+ <monochrome android:drawable="@drawable/ic_launcher_monochrome"/>+</adaptive-icon>diff --git a/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.pngnew file mode 100644index 0000000..4c1d2b2Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differdiff --git a/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..518122bBinary files /dev/null and b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differdiff --git a/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.pngnew file mode 100644index 0000000..b17ce47Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differdiff --git a/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.pngnew file mode 100644index 0000000..c9c570aBinary files /dev/null and b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differdiff --git a/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..aca5406Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differdiff --git a/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.pngnew file mode 100644index 0000000..6593e06Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngnew file mode 100644index 0000000..ed8b7c8Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..d9b6712Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..0e4d4ccBinary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngnew file mode 100644index 0000000..1ffcf78Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..fe66f86Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..8e3d134Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngnew file mode 100644index 0000000..62d9652Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..3b16ab5Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differdiff --git a/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..1c1b0deBinary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differdiff --git a/mobile/android/app/src/main/res/values-pt/strings.xml b/mobile/android/app/src/main/res/values-pt/strings.xmlnew file mode 100644index 0000000..6525803--- /dev/null+++ b/mobile/android/app/src/main/res/values-pt/strings.xml@@ -0,0 +1,8 @@+<?xml version='1.0' encoding='utf-8'?>+<resources>+ <string name="playback_channel">Reprodução</string>+ <string name="playback_play">Tocar</string>+ <string name="playback_pause">Pausar</string>+ <string name="playback_next">Próxima</string>+ <string name="playback_previous">Anterior</string>+</resources>diff --git a/mobile/android/app/src/main/res/values/ic_launcher_background.xml b/mobile/android/app/src/main/res/values/ic_launcher_background.xmlnew file mode 100644index 0000000..d64eddc--- /dev/null+++ b/mobile/android/app/src/main/res/values/ic_launcher_background.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <color name="ic_launcher_background">#0B0C0F</color>+</resources>diff --git a/mobile/android/app/src/main/res/values/strings.xml b/mobile/android/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..16504bb--- /dev/null+++ b/mobile/android/app/src/main/res/values/strings.xml@@ -0,0 +1,12 @@+<?xml version='1.0' encoding='utf-8'?>+<resources>+ <string name="app_name" translatable="false">Musike</string>+ <string name="title_activity_main" translatable="false">Musike</string>+ <string name="package_name" translatable="false">app.musike.android</string>+ <string name="custom_url_scheme" translatable="false">app.musike.android</string>+ <string name="playback_channel">Playback</string>+ <string name="playback_play">Play</string>+ <string name="playback_pause">Pause</string>+ <string name="playback_next">Next</string>+ <string name="playback_previous">Previous</string>+</resources>diff --git a/mobile/android/app/src/main/res/values/styles.xml b/mobile/android/app/src/main/res/values/styles.xmlnew file mode 100644index 0000000..dedb1b8--- /dev/null+++ b/mobile/android/app/src/main/res/values/styles.xml@@ -0,0 +1,28 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>++ <!-- Base application theme. -->+ <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">+ <!-- Customize your theme here. -->+ <item name="colorPrimary">@color/colorPrimary</item>+ <item name="colorPrimaryDark">@color/colorPrimaryDark</item>+ <item name="colorAccent">@color/colorAccent</item>+ </style>++ <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">+ <item name="windowActionBar">false</item>+ <item name="windowNoTitle">true</item>+ <item name="android:background">@null</item>+ <!-- Musike's background behind the page while it loads, instead of a white flash. -->+ <item name="android:windowBackground">@color/ic_launcher_background</item>+ </style>+++ <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">+ <item name="android:background">@drawable/splash</item>+ <!-- Android 12+ draws its own launch screen: the logo on Musike's background. -->+ <item name="windowSplashScreenBackground">@color/ic_launcher_background</item>+ <item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher_foreground</item>+ <item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>+ </style>+</resources>diff --git a/mobile/android/app/src/main/res/xml/file_paths.xml b/mobile/android/app/src/main/res/xml/file_paths.xmlnew file mode 100644index 0000000..bd0c4d8--- /dev/null+++ b/mobile/android/app/src/main/res/xml/file_paths.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<paths xmlns:android="http://schemas.android.com/apk/res/android">+ <external-path name="my_images" path="." />+ <cache-path name="my_cache_images" path="." />+</paths>\ No newline at end of filediff --git a/mobile/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/mobile/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.javanew file mode 100644index 0000000..0297327--- /dev/null+++ b/mobile/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java@@ -0,0 +1,18 @@+package com.getcapacitor.myapp;++import static org.junit.Assert.*;++import org.junit.Test;++/**+ * Example local unit test, which will execute on the development machine (host).+ *+ * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>+ */+public class ExampleUnitTest {++ @Test+ public void addition_isCorrect() throws Exception {+ assertEquals(4, 2 + 2);+ }+}diff --git a/mobile/android/build.gradle b/mobile/android/build.gradlenew file mode 100644index 0000000..f8f0e43--- /dev/null+++ b/mobile/android/build.gradle@@ -0,0 +1,29 @@+// Top-level build file where you can add configuration options common to all sub-projects/modules.++buildscript {++ repositories {+ google()+ mavenCentral()+ }+ dependencies {+ classpath 'com.android.tools.build:gradle:8.13.0'+ classpath 'com.google.gms:google-services:4.4.4'++ // NOTE: Do not place your application dependencies here; they belong+ // in the individual module build.gradle files+ }+}++apply from: "variables.gradle"++allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++task clean(type: Delete) {+ delete rootProject.buildDir+}diff --git a/mobile/android/capacitor.settings.gradle b/mobile/android/capacitor.settings.gradlenew file mode 100644index 0000000..04075c5--- /dev/null+++ b/mobile/android/capacitor.settings.gradle@@ -0,0 +1,12 @@+// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN+include ':capacitor-android'+project(':capacitor-android').projectDir = new File('../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/android/capacitor')++include ':capacitor-app'+project(':capacitor-app').projectDir = new File('../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/app/android')++include ':capacitor-filesystem'+project(':capacitor-filesystem').projectDir = new File('../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/filesystem/android')++include ':capacitor-share'+project(':capacitor-share').projectDir = new File('../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/share/android')diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.propertiesnew file mode 100644index 0000000..2e87c52--- /dev/null+++ b/mobile/android/gradle.properties@@ -0,0 +1,22 @@+# Project-wide Gradle settings.++# IDE (e.g. Android Studio) users:+# Gradle settings configured through the IDE *will override*+# any settings specified in this file.++# For more details on how to configure your build environment visit+# http://www.gradle.org/docs/current/userguide/build_environment.html++# Specifies the JVM arguments used for the daemon process.+# The setting is particularly useful for tweaking memory settings.+org.gradle.jvmargs=-Xmx1536m++# When configured, Gradle will run in incubating parallel mode.+# This option should only be used with decoupled projects. More details, visit+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects+# org.gradle.parallel=true++# AndroidX package structure to make it clearer which packages are bundled with the+# Android operating system, and which are packaged with your app's APK+# https://developer.android.com/topic/libraries/support-library/androidx-rn+android.useAndroidX=truediff --git a/mobile/android/gradle/wrapper/gradle-wrapper.jar b/mobile/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 0000000..1b33c55Binary files /dev/null and b/mobile/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/mobile/android/gradle/wrapper/gradle-wrapper.properties b/mobile/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..7705927--- /dev/null+++ b/mobile/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,7 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip+networkTimeout=10000+validateDistributionUrl=true+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/mobile/android/gradlew b/mobile/android/gradlewnew file mode 100755index 0000000..23d15a9--- /dev/null+++ b/mobile/android/gradlew@@ -0,0 +1,251 @@+#!/bin/sh++#+# Copyright © 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH="\\\"\\\""+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/mobile/android/gradlew.bat b/mobile/android/gradlew.batnew file mode 100644index 0000000..db3a6ac--- /dev/null+++ b/mobile/android/gradlew.bat@@ -0,0 +1,94 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables with windows NT shell+if "%OS%"=="Windows_NT" setlocal++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:execute+@rem Setup the command line++set CLASSPATH=+++@rem Execute Gradle+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*++:end+@rem End local scope for the variables with windows NT shell+if %ERRORLEVEL% equ 0 goto mainEnd++:fail+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of+rem the _cmd.exe /c_ return code!+set EXIT_CODE=%ERRORLEVEL%+if %EXIT_CODE% equ 0 set EXIT_CODE=1+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%+exit /b %EXIT_CODE%++:mainEnd+if "%OS%"=="Windows_NT" endlocal++:omegadiff --git a/mobile/android/settings.gradle b/mobile/android/settings.gradlenew file mode 100644index 0000000..3b4431d--- /dev/null+++ b/mobile/android/settings.gradle@@ -0,0 +1,5 @@+include ':app'+include ':capacitor-cordova-android-plugins'+project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')++apply from: 'capacitor.settings.gradle'\ No newline at end of filediff --git a/mobile/android/variables.gradle b/mobile/android/variables.gradlenew file mode 100644index 0000000..ee4ba41--- /dev/null+++ b/mobile/android/variables.gradle@@ -0,0 +1,16 @@+ext {+ minSdkVersion = 24+ compileSdkVersion = 36+ targetSdkVersion = 36+ androidxActivityVersion = '1.11.0'+ androidxAppCompatVersion = '1.7.1'+ androidxCoordinatorLayoutVersion = '1.3.0'+ androidxCoreVersion = '1.17.0'+ androidxFragmentVersion = '1.8.9'+ coreSplashScreenVersion = '1.2.0'+ androidxWebkitVersion = '1.14.0'+ junitVersion = '4.13.2'+ androidxJunitVersion = '1.3.0'+ androidxEspressoCoreVersion = '3.7.0'+ cordovaAndroidVersion = '14.0.1'+}\ No newline at end of filediff --git a/mobile/capacitor.config.ts b/mobile/capacitor.config.tsnew file mode 100644index 0000000..1cd363c--- /dev/null+++ b/mobile/capacitor.config.ts@@ -0,0 +1,23 @@+import type { CapacitorConfig } from "@capacitor/cli";++const config: CapacitorConfig = {+ appId: "app.musike.android",+ appName: "Musike",+ // The web app built in Android mode: same UI, backend running on the phone (see web/src/native).+ webDir: "../web/dist-native",+ backgroundColor: "#0B0C0F",+ android: {+ // Music keeps loading while the screen is off or another app is in front.+ allowMixedContent: false,+ },+ plugins: {+ SystemBars: {+ // The app already pads itself with env(safe-area-inset-*), like on an iPhone.+ insetsHandling: "native",+ initialViewportFitValueHint: "cover",+ style: "DARK",+ },+ },+};++export default config;diff --git a/mobile/package.json b/mobile/package.jsonnew file mode 100644index 0000000..5a51035--- /dev/null+++ b/mobile/package.json@@ -0,0 +1,23 @@+{+ "name": "@musike/mobile",+ "private": true,+ "version": "1.4.0",+ "description": "Musike for Android: the web app with the server's work done on the phone (Capacitor).",+ "type": "module",+ "scripts": {+ "build": "pnpm --filter @musike/web build:native && cap sync android",+ "apk": "pnpm run build && node scripts/build-apk.mjs",+ "open": "cap open android"+ },+ "dependencies": {+ "@capacitor/android": "8.5.3",+ "@capacitor/app": "8.1.2",+ "@capacitor/core": "8.5.3",+ "@capacitor/filesystem": "8.1.5",+ "@capacitor/share": "8.0.3"+ },+ "devDependencies": {+ "@capacitor/cli": "8.5.3",+ "typescript": "^7.0.2"+ }+}diff --git a/mobile/scripts/build-apk.mjs b/mobile/scripts/build-apk.mjsnew file mode 100644index 0000000..bc05d4c--- /dev/null+++ b/mobile/scripts/build-apk.mjs@@ -0,0 +1,29 @@+// Builds the release APK and copies it to release/Musike-Setup-<version>-Android.apk at the repository root,+// next to the desktop downloads.+// Needs JDK 17+ (JAVA_HOME) and the Android SDK (ANDROID_HOME or android/local.properties).+// Signed when android/keystore.properties or the MUSIKE_KEYSTORE* variables are set; unsigned otherwise.+import { spawnSync } from "node:child_process";+import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));+const android = join(root, "android");+const win = process.platform === "win32";++const task = "assembleRelease --console=plain";+const gradle = win+ ? // Batch files only run through a shell, as one command line with the path quoted.+ spawnSync(`"${join(android, "gradlew.bat")}" ${task}`, { cwd: android, stdio: "inherit", shell: true })+ : // Through sh, so it runs even when the executable bit was lost (files committed from Windows).+ spawnSync("sh", [join(android, "gradlew"), ...task.split(" ")], { cwd: android, stdio: "inherit" });+if (gradle.status !== 0) process.exit(gradle.status ?? 1);++const outputs = join(android, "app", "build", "outputs", "apk", "release");+const signed = join(outputs, "app-release.apk");+const apk = existsSync(signed) ? signed : join(outputs, "app-release-unsigned.apk");+const target = join(root, "..", "release", `Musike-Setup-${version}-Android${apk === signed ? "" : "-unsigned"}.apk`);+mkdirSync(dirname(target), { recursive: true });+copyFileSync(apk, target);+console.log(`\n${target}`);diff --git a/mobile/streaming.json b/mobile/streaming.jsonnew file mode 100644index 0000000..340c9ac--- /dev/null+++ b/mobile/streaming.json@@ -0,0 +1,3 @@+{+ "clients": ["VISIONOS"]+}diff --git a/package.json b/package.jsonindex 947dcff..b04fe03 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "musike","private": true,- "version": "1.2.0",+ "version": "1.4.0","type": "module","scripts": {"dev": "pnpm --parallel --filter ./server --filter ./web dev",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9af696f..36e5b77 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -26,6 +26,31 @@ importers:specifier: ^7.0.2version: 7.0.2+ mobile:+ dependencies:+ '@capacitor/android':+ specifier: 8.5.3+ version: 8.5.3(@capacitor/[email protected])+ '@capacitor/app':+ specifier: 8.1.2+ version: 8.1.2(@capacitor/[email protected])+ '@capacitor/core':+ specifier: 8.5.3+ version: 8.5.3+ '@capacitor/filesystem':+ specifier: 8.1.5+ version: 8.1.5(@capacitor/[email protected])+ '@capacitor/share':+ specifier: 8.0.3+ version: 8.0.3(@capacitor/[email protected])+ devDependencies:+ '@capacitor/cli':+ specifier: 8.5.3+ version: 8.5.3+ typescript:+ specifier: ^7.0.2+ version: 7.0.2+server:dependencies:'@fastify/static':@@ -41,6 +66,9 @@ importers:'@types/node':specifier: ^22.20.5version: 22.20.5+ esbuild:+ specifier: 0.28.2+ version: 0.28.2tsx:specifier: 4.23.15version: 4.23.15@@ -50,6 +78,18 @@ importers:web:dependencies:+ '@capacitor/app':+ specifier: 8.1.2+ version: 8.1.2(@capacitor/[email protected])+ '@capacitor/core':+ specifier: 8.5.3+ version: 8.5.3+ '@capacitor/filesystem':+ specifier: 8.1.5+ version: 8.1.5(@capacitor/[email protected])+ '@capacitor/share':+ specifier: 8.0.3+ version: 8.0.3(@capacitor/[email protected])'@fontsource-variable/geist':specifier: 5.3.0version: 5.3.0@@ -77,7 +117,10 @@ importers:devDependencies:'@tailwindcss/vite':specifier: 4.3.3- version: 4.3.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.3.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@types/node':+ specifier: ^22.20.5+ version: 22.20.5'@types/react':specifier: ^19.3.0version: 19.3.0@@ -86,7 +129,7 @@ importers:version: 19.3.0(@types/[email protected])'@vitejs/plugin-react':specifier: ^6.1.2- version: 6.1.2([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 6.1.2([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))tailwindcss:specifier: 4.3.3version: 4.3.3@@ -95,10 +138,10 @@ importers:version: 7.0.2vite:specifier: 8.3.4- version: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-pwa:specifier: 2.0.0- version: 2.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])+ version: 2.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])workbox-window:specifier: ^7.4.1version: 7.4.1@@ -615,6 +658,37 @@ packages:'@bufbuild/[email protected]':resolution: {integrity: sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q==}+ '@capacitor/[email protected]':+ resolution: {integrity: sha512-ilH4gSSz3DrketMkzDVAvY9JsWJ//rCQnECLTdcFRO7xXDogwAbUvQAnIAbiqefwV/D1xfjEL4Gw1MJXEcaA9g==}+ peerDependencies:+ '@capacitor/core': ^8.5.0++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-uKBlsrXH0IdvUn69e/KKYbZ32A06pcrUdG8LWuZ/6y33YMXZXLEEdNSwl+jKS/SrsTWqnePs8EqSWaiQM3mUGA==}+ peerDependencies:+ '@capacitor/core': '>=8.0.0'++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-/G6xwna+p4GS3lthSdWN3OThCH2F85O0Ukdy8rv3oAXvgEMeyFgPEIA3PMAS++IkHwUuBYBAKOQJnZfcrh1n0w==}+ engines: {node: '>=22.0.0'}+ hasBin: true++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-oBE1oGuYE4ZzYYrulC75OuHdSsD6zLUy7d5o1tFwDLG4govGoubY15cxpiI5l0+q87Lm5p0bhbehMdzJg4aFag==}++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-m1RkI8L83NJeppEKyRWioK3MDp2vjlA+QfUQcF8/xRlcXNC2HYxqoyYJ+K4M0EcVovy+g+4F24S05+bhK4Vgdg==}+ peerDependencies:+ '@capacitor/core': '>=8.0.0'++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-gnvZBV1NPu2B8vd1UKncR56G15ueHd0aZLqgDov++t3SmTBG9Q0VrAZ1VnHn5stxlmglVaTb4RwopMgbpLzroA==}+ peerDependencies:+ '@capacitor/core': '>=8.0.0'++ '@capacitor/[email protected]':+ resolution: {integrity: sha512-/C1FUo8/OkKuAT4nCIu/34ny9siNHr9qtFezu4kxm6GY1wNFxrCFWjfYx5C1tUhVGz3fxBABegupkpjXvjCHrw==}+'@electron-internal/[email protected]':resolution: {integrity: sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==}engines: {node: '>=22.12.0'}@@ -851,6 +925,38 @@ packages:'@fontsource-variable/[email protected]':resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==}+ '@ionic/[email protected]':+ resolution: {integrity: sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==}+ engines: {node: '>=16.0.0'}++ '@ionic/[email protected]':+ resolution: {integrity: sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==}+ engines: {node: '>=16.0.0'}+'@isaacs/[email protected]':resolution: {integrity: sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==}engines: {node: '>=18'}@@ -1313,6 +1419,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==}+'@types/[email protected]':resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==}@@ -1345,6 +1454,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==}+'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}@@ -1545,6 +1657,10 @@ packages:resolution: {integrity: sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==}engines: {node: '>=12.0.0'}+ resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==}engines: {node: '>=0.12.0'}@@ -1607,6 +1723,10 @@ packages:engines: {node: '>=6.0.0'}hasBin: true+ resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==}+ engines: {node: '>=0.6'}+resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}@@ -1614,6 +1734,17 @@ packages:resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.+ resolution: {integrity: sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==}++ resolution: {integrity: sha512-PyJxiNtA5T2PlLIeBot4lbp7rj4OadzjnMZD/G5zuBNt8ei/yCU7+wW0h2bag9vr8c+/WuRWmSxbqAl9hL1rBA==}+ engines: {node: '>= 5.10.0'}++ resolution: {integrity: sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==}+ engines: {node: '>= 5.10.0'}+resolution: {integrity: sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==}@@ -1629,6 +1760,9 @@ packages:engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}hasBin: true+ resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}+resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}@@ -1704,6 +1838,10 @@ packages:resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}@@ -1798,6 +1936,10 @@ packages:resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}engines: {node: '>= 0.4'}@@ -1870,6 +2012,10 @@ packages:engines: {node: '>= 22.12.0'}hasBin: true+ resolution: {integrity: sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==}+ engines: {node: '>= 0.4.0'}+resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}@@ -1982,6 +2128,9 @@ packages:resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==}+ resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==}+resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}engines: {node: '>=12.0.0'}@@ -2190,6 +2339,10 @@ packages:resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}+ resolution: {integrity: sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==}+ engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}engines: {node: '>= 0.4'}@@ -2230,6 +2383,11 @@ packages:resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==}+ engines: {node: '>=8'}+ hasBin: true+resolution: {integrity: sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==}engines: {node: '>= 0.4'}@@ -2309,6 +2467,10 @@ packages:resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==}@@ -2389,6 +2551,14 @@ packages:resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}+ resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}+ engines: {node: '>=6'}+resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==}@@ -2656,6 +2826,11 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true+ resolution: {integrity: sha512-U1PllBuzW5d1gfan+88L+Hky2eZx+9gv3Pf6rNBxKbORxi7boHzqiA6QFGSnqMem4j0A9tZ08NMIs5+0m/VS1Q==}+ engines: {node: '>=16.0.0'}+ hasBin: true+resolution: {integrity: sha512-O9XXMXLeRHQtvh43NCah3y9N1K69tecOmu8Y5p2ay4iXvtpbQr0VaroJF9EmRVp3vkdoj3qn4IFfX+ZYtC94fw==}engines: {node: '>=22.12.0'}@@ -2703,6 +2878,10 @@ packages:resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}+ resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==}engines: {node: '>= 0.4'}@@ -2737,6 +2916,9 @@ packages:resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}engines: {node: '>=12', npm: '>=6'}+ resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}+resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}@@ -2801,6 +2983,10 @@ packages:resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==}engines: {node: '>=10'}+ resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}@@ -2847,6 +3033,10 @@ packages:resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==}+ resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==}@@ -2919,6 +3109,11 @@ packages:deprecated: Rimraf versions prior to v4 are no longer supportedhasBin: true+ resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==}+ engines: {node: 20 || >=22}+ hasBin: true+resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==}engines: {node: '>=8.0'}@@ -2959,6 +3154,9 @@ packages:resolution: {integrity: sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==}+ resolution: {integrity: sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==}+resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==}engines: {node: '>=11.0.0'}@@ -3047,10 +3245,20 @@ packages:resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}engines: {node: '>=14'}+ resolution: {integrity: sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw==}+resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==}engines: {node: '>=10'}+ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}++ resolution: {integrity: sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-RQsvleCbF8cVHEv+xuDGaA4pOizFqJ0GgjtMSRo6oP8pnN7WsigHgVGey6aILRBKv4W2YOMHLqbKdnB6hpB9fw==}engines: {node: '>=20.0.0'}@@ -3092,6 +3300,10 @@ packages:resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==}+ engines: {node: '>= 0.10.0'}+resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}engines: {node: '>=8'}@@ -3174,6 +3386,9 @@ packages:resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==}engines: {node: '>=20'}+ resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==}+resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}@@ -3196,6 +3411,10 @@ packages:resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}engines: {node: '>=0.6'}+ resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}+ hasBin: true+resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==}@@ -3282,6 +3501,10 @@ packages:resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}+ resolution: {integrity: sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==}@@ -3301,6 +3524,11 @@ packages:resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}+ resolution: {integrity: sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==}+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).+ hasBin: true+resolution: {integrity: sha512-6G9dsPKT9QKYpeTuTLJM28zZL3HsXUTUM/QUZBEgQk2jbfrPJDq2i8gTewAKqi1c9Mt6MiidrL4SFI+HthiQMg==}engines: {node: '>=20.19.0'}@@ -3446,6 +3674,18 @@ packages:resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}+ resolution: {integrity: sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==}+ engines: {node: '>=10.0.0'}++ resolution: {integrity: sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==}+ engines: {node: '>=4.0.0'}++ resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==}+ engines: {node: '>=4.0'}+resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==}engines: {node: '>=8.0'}@@ -3472,6 +3712,9 @@ packages:resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==}engines: {node: '>=12'}+ resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}+resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}@@ -4170,6 +4413,52 @@ snapshots:'@bufbuild/[email protected]': {}+ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.3++ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.3++ '@capacitor/[email protected]':+ dependencies:+ '@ionic/cli-framework-output': 2.2.8+ '@ionic/utils-subprocess': 3.0.1+ '@ionic/utils-terminal': 2.3.5+ commander: 12.1.0+ debug: 4.4.3+ env-paths: 2.2.1+ fs-extra: 11.4.1+ kleur: 4.1.5+ native-run: 2.0.3+ open: 8.4.2+ plist: 3.1.0+ prompts: 2.4.2+ rimraf: 6.1.3+ semver: 7.8.5+ tar: 7.5.22+ tslib: 2.8.1+ xcode: 3.0.1+ xml2js: 0.6.2+ transitivePeerDependencies:+ - supports-color++ '@capacitor/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.3+ '@capacitor/synapse': 1.0.4++ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.3++ '@capacitor/[email protected]': {}+'@electron-internal/[email protected]': {}'@electron/[email protected]':@@ -4391,6 +4680,82 @@ snapshots:'@fontsource-variable/[email protected]': {}+ '@ionic/[email protected]':+ dependencies:+ '@ionic/utils-terminal': 2.3.5+ debug: 4.4.3+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ debug: 4.4.3+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ '@types/fs-extra': 8.1.5+ debug: 4.4.3+ fs-extra: 9.1.0+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ debug: 4.4.3+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ '@ionic/utils-object': 2.1.6+ '@ionic/utils-terminal': 2.3.5+ debug: 4.4.3+ signal-exit: 3.0.7+ tree-kill: 1.2.2+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ debug: 4.4.3+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ '@ionic/utils-array': 2.1.6+ '@ionic/utils-fs': 3.1.7+ '@ionic/utils-process': 2.1.12+ '@ionic/utils-stream': 3.1.7+ '@ionic/utils-terminal': 2.3.5+ cross-spawn: 7.0.6+ debug: 4.4.3+ tslib: 2.8.1+ transitivePeerDependencies:+ - supports-color++ '@ionic/[email protected]':+ dependencies:+ '@types/slice-ansi': 4.0.0+ debug: 4.4.3+ signal-exit: 3.0.7+ slice-ansi: 4.0.0+ string-width: 4.2.3+ strip-ansi: 6.0.1+ tslib: 2.8.1+ untildify: 4.0.0+ wrap-ansi: 7.0.0+ transitivePeerDependencies:+ - supports-color+'@isaacs/[email protected]': {}'@isaacs/[email protected]':@@ -4708,12 +5073,12 @@ snapshots:'@tailwindcss/oxide-win32-arm64-msvc': 4.3.3'@tailwindcss/oxide-win32-x64-msvc': 4.3.3- '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@tailwindcss/node': 4.3.3'@tailwindcss/oxide': 4.3.3tailwindcss: 4.3.3- vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])'@trickfilm400/[email protected]':dependencies:@@ -4735,6 +5100,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.5+'@types/[email protected]':dependencies:'@types/node': 22.20.5@@ -4769,6 +5138,8 @@ snapshots:dependencies:'@types/node': 22.20.5+ '@types/[email protected]': {}+'@types/[email protected]': {}'@typescript/[email protected]':@@ -4831,10 +5202,10 @@ snapshots:'@typescript/[email protected]':optional: true- '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@rolldown/pluginutils': 1.0.1- vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])'@xmldom/[email protected]': {}@@ -4934,6 +5305,8 @@ snapshots:pvutils: 1.2.0tslib: 2.8.1+ [email protected]: {}+@@ -4989,11 +5362,25 @@ snapshots:+ [email protected]: {}+optional: true+ dependencies:+ stream-buffers: 2.2.0++ dependencies:+ big-integer: 1.6.52++ dependencies:+ big-integer: 1.6.52+dependencies:balanced-match: 1.0.2@@ -5015,6 +5402,8 @@ snapshots:node-releases: 2.0.58update-browserslist-db: 1.3.4([email protected])+ [email protected]: {}+@@ -5109,6 +5498,8 @@ snapshots:dependencies:delayed-stream: 1.0.0+ [email protected]: {}+@@ -5185,6 +5576,8 @@ snapshots:es-errors: 1.3.0gopd: 1.2.0+ [email protected]: {}+dependencies:define-data-property: 1.1.4@@ -5298,6 +5691,10 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ sax: 1.1.4+@@ -5497,6 +5894,10 @@ snapshots:dependencies:reusify: 1.1.0+ dependencies:+ pend: 1.2.0+optionalDependencies:picomatch: 4.0.7@@ -5754,6 +6155,8 @@ snapshots:+ [email protected]: {}+dependencies:es-errors: 1.3.0@@ -5802,6 +6205,8 @@ snapshots:call-bound: 1.0.4has-tostringtag: 1.0.2+ [email protected]: {}+dependencies:call-bound: 1.0.4@@ -5876,6 +6281,10 @@ snapshots:call-bound: 1.0.4get-intrinsic: 1.3.0+ dependencies:+ is-docker: 2.2.1+@@ -5939,6 +6348,10 @@ snapshots:dependencies:json-buffer: 3.0.1+ [email protected]: {}++ [email protected]: {}+@@ -6137,6 +6550,22 @@ snapshots:+ dependencies:+ '@ionic/utils-fs': 3.1.7+ '@ionic/utils-terminal': 2.3.5+ bplist-parser: 0.3.2+ debug: 4.4.3+ elementtree: 0.1.7+ ini: 4.1.3+ plist: 3.1.0+ split2: 4.2.0+ through2: 4.0.2+ tslib: 2.8.1+ yauzl: 2.10.0+ transitivePeerDependencies:+ - supports-color+dependencies:semver: 7.8.5@@ -6187,6 +6616,12 @@ snapshots:dependencies:wrappy: 1.0.2+ dependencies:+ define-lazy-prop: 2.0.0+ is-docker: 2.2.1+ is-wsl: 2.2.0+dependencies:call-bound: 1.0.4@@ -6215,6 +6650,8 @@ snapshots:+ [email protected]: {}+@@ -6284,6 +6721,11 @@ snapshots:err-code: 2.0.3retry: 0.12.0+ dependencies:+ kleur: 3.0.3+ sisteransi: 1.0.5+dependencies:graceful-fs: 4.2.11@@ -6336,6 +6778,12 @@ snapshots:string_decoder: 1.1.1util-deprecate: 1.0.2+ dependencies:+ inherits: 2.0.4+ string_decoder: 1.1.1+ util-deprecate: 1.0.2+@@ -6412,6 +6860,11 @@ snapshots:dependencies:glob: 7.2.3+ dependencies:+ glob: 13.0.6+ package-json-from-dist: 1.0.1+dependencies:boolean: 3.2.0@@ -6506,6 +6959,8 @@ snapshots:dependencies:truncate-utf8-bytes: 1.0.2+ [email protected]: {}+@@ -6594,10 +7049,24 @@ snapshots:+ dependencies:+ bplist-creator: 0.1.0+ bplist-parser: 0.3.1+ plist: 3.1.0+dependencies:semver: 7.8.5+ [email protected]: {}++ dependencies:+ ansi-styles: 4.3.0+ astral-regex: 2.0.0+ is-fullwidth-code-point: 3.0.0+@@ -6629,6 +7098,8 @@ snapshots:es-errors: 1.3.0internal-slot: 1.1.0+ [email protected]: {}+dependencies:emoji-regex: 8.0.0@@ -6745,6 +7216,10 @@ snapshots:dependencies:real-require: 1.0.0+ dependencies:+ readable-stream: 3.6.2+dependencies:semver: 5.7.2@@ -6764,6 +7239,8 @@ snapshots:+ [email protected]: {}+dependencies:utf8-byte-length: 1.0.5@@ -6871,6 +7348,8 @@ snapshots:+ [email protected]: {}+dependencies:bluebird: 3.7.2@@ -6891,18 +7370,20 @@ snapshots:- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected]):+ [email protected]: {}++ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected]):dependencies:debug: 4.4.3pretty-bytes: 6.1.1tinyglobby: 0.2.17- vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.3.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])workbox-build: 7.4.1workbox-window: 7.4.1transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.33.0picomatch: 4.0.7@@ -6910,7 +7391,7 @@ snapshots:rolldown: 1.2.13tinyglobby: 0.2.17optionalDependencies:- '@types/node': 24.19.2+ '@types/node': 22.20.5esbuild: 0.28.2fsevents: 2.3.3jiti: 2.7.0@@ -7099,6 +7580,18 @@ snapshots:+ dependencies:+ simple-plist: 1.3.1+ uuid: 7.0.3++ dependencies:+ sax: 1.6.1+ xmlbuilder: 11.0.1++ [email protected]: {}+@@ -7121,6 +7614,11 @@ snapshots:y18n: 5.0.8yargs-parser: 21.1.1+ dependencies:+ buffer-crc32: 0.2.13+ fd-slicer: 1.1.0+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex bf66e43..55ac4f4 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -2,6 +2,7 @@ packages:- server- web- desktop+ - mobileonlyBuiltDependencies:- esbuilddiff --git a/server/package.json b/server/package.jsonindex 55e85a3..d9fdefc 100644--- a/server/package.json+++ b/server/package.json@@ -1,11 +1,12 @@{"name": "@musike/server","private": true,- "version": "1.2.0",+ "version": "1.4.0","type": "module","scripts": {"dev": "tsx watch --clear-screen=false src/index.ts","start": "tsx src/index.ts",+ "bundle": "node scripts/bundle.mjs","typecheck": "tsc --noEmit"},"dependencies": {@@ -15,6 +16,7 @@},"devDependencies": {"@types/node": "^22.20.5",+ "esbuild": "0.28.2","tsx": "4.23.15","typescript": "^7.0.2"}diff --git a/server/scripts/bundle.mjs b/server/scripts/bundle.mjsnew file mode 100644index 0000000..be55447--- /dev/null+++ b/server/scripts/bundle.mjs@@ -0,0 +1,22 @@+// Bundles the server into one file (dist/server.mjs) that runs with plain Node: no node_modules, no tsx.+// Used by the Docker image.+import path from "node:path";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");++await build({+ entryPoints: [path.join(root, "src", "index.ts")],+ outfile: path.join(root, "dist", "server.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ // Some bundled CommonJS dependencies call require() for Node built-ins.+ banner: { js: "import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);" },+ sourcemap: false,+ minify: false,+ logLevel: "warning",+});+console.log("server bundle ok");diff --git a/server/src/app.ts b/server/src/app.tsindex fa53a63..96ff49f 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -2,9 +2,10 @@ import { existsSync } from "node:fs";import { createServer } from "node:net";import fastifyStatic from "@fastify/static";import Fastify from "fastify";-import { ARTIST_ID, artist, GENRE_ID, genre, genreArtists, genres } from "./browse.js";+import { ALBUM_ID, album, ARTIST_ID, artist, GENRE_ID, genre, genreArtists, genres, searchAlbums } from "./browse.js";import { config } from "./config.js";import * as library from "./library.js";+import { fileStorage } from "./libraryFile.js";import { findVideoFor, radio, search, suggestions } from "./search.js";import { proxyStream, serveFile } from "./stream.js";import { langOf, msg, tr } from "./i18n.js";@@ -40,6 +41,7 @@ export interface RunningServer {/** Builds the Musike HTTP server (API + web app) and starts listening. */export async function startServer(opts: StartOptions = {}): Promise<RunningServer> {+ library.useLibraryStorage(fileStorage());const found = await refreshTools();const app = Fastify({ logger: { level: process.env.LOG_LEVEL ?? "warn" } });@@ -103,6 +105,17 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServereturn artist(aid, langOf(req));});+ app.get("/api/albums/:alid", async (req) => {+ const { alid } = req.params as { alid: string };+ if (!ALBUM_ID.test(alid)) throw new HttpError(400, msg("invalidAlbum"));+ return album(alid, langOf(req));+ });++ app.get("/api/search/albums", async (req) => {+ const { q } = req.query as { q?: string };+ return { albums: await searchAlbums(query(q), langOf(req)) };+ });+/** The music video for a song, so "Vídeo" mode can show the clip instead of a still cover. */app.get("/api/video-for/:id", async (req) => {const { title, artist, duration } = req.query as { title?: string; artist?: string; duration?: string };diff --git a/server/src/bootstrap.ts b/server/src/bootstrap.tsindex 685f101..f49d913 100644--- a/server/src/bootstrap.ts+++ b/server/src/bootstrap.ts@@ -1,6 +1,6 @@import { execFile } from "node:child_process";import { createWriteStream, existsSync } from "node:fs";-import { cp, mkdir, readdir, rename, rm } from "node:fs/promises";+import { chmod, cp, mkdir, readdir, rename, rm } from "node:fs/promises";import path from "node:path";import { Readable, Transform } from "node:stream";import { pipeline } from "node:stream/promises";@@ -9,6 +9,7 @@ import { config } from "./config.js";import { refreshTools, tools } from "./tools.js";import { msg, tr, type Lang, type Text } from "./i18n.js";import { HttpError } from "./types.js";+import { unzip } from "./unzip.js";const exec = promisify(execFile);@@ -21,12 +22,41 @@ export interface DownloadState {error?: Text;}-/** Official Windows builds. FFmpeg is the LGPL "shared" build: about half the size of the static one. */-const SOURCES: Record<Component, string> = {- "yt-dlp": "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe",- deno: "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-pc-windows-msvc.zip",- ffmpeg: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-lgpl-shared.zip",-};+const isMac = process.platform === "darwin";+const isLinux = process.platform === "linux";+const arm = process.arch === "arm64";+const exe = process.platform === "win32" ? ".exe" : "";++/**+ * Official builds for the desktop app's platform. On Windows, FFmpeg is the LGPL "shared" build (about half the+ * size of the static one). On macOS and Linux it comes from Martin Riedl's builds, a single binary: a release,+ * except on Apple Silicon, where the latest snapshot is the only arm64 build published.+ */+const SOURCES: Record<Component, string> = isMac+ ? {+ "yt-dlp": "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos",+ deno: `https://github.com/denoland/deno/releases/latest/download/deno-${arm ? "aarch64" : "x86_64"}-apple-darwin.zip`,+ ffmpeg: arm+ ? "https://ffmpeg.martin-riedl.de/redirect/latest/macos/arm64/snapshot/ffmpeg.zip"+ : "https://ffmpeg.martin-riedl.de/redirect/latest/macos/amd64/release/ffmpeg.zip",+ }+ : isLinux+ ? {+ "yt-dlp": `https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux${arm ? "_aarch64" : ""}`,+ deno: `https://github.com/denoland/deno/releases/latest/download/deno-${arm ? "aarch64" : "x86_64"}-unknown-linux-gnu.zip`,+ ffmpeg: `https://ffmpeg.martin-riedl.de/redirect/latest/linux/${arm ? "arm64" : "amd64"}/release/ffmpeg.zip`,+ }+ : {+ "yt-dlp": "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe",+ deno: "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-pc-windows-msvc.zip",+ ffmpeg: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-lgpl-shared.zip",+ };++/** Moves a downloaded binary into place, executable. */+async function install(from: string, to: string) {+ await rename(from, to);+ if (!exe) await chmod(to, 0o755);+}const states = new Map<Component, DownloadState>();const inflight = new Map<Component, Promise<void>>();@@ -64,17 +94,28 @@ export function ensureComponent(c: Component): Promise<void> {await pipeline(Readable.fromWeb(res.body as never), count, createWriteStream(tmp));if (c === "yt-dlp") {- await rename(tmp, path.join(bin, "yt-dlp.exe"));+ await install(tmp, path.join(bin, `yt-dlp${exe}`));} else {state.status = "extracting";const out = path.join(bin, `.${c}-extract`);await rm(out, { recursive: true, force: true });await mkdir(out, { recursive: true });- // Windows 10+ ships bsdtar, which reads zip files.- const tar = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe");- await exec(existsSync(tar) ? tar : "tar", ["-xf", tmp, "-C", out], { windowsHide: true });+ if (isLinux) {+ // GNU tar can't read zip files.+ await unzip(tmp, out);+ } else {+ // Windows 10+ and macOS ship bsdtar, which reads zip files.+ const tar = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe");+ await exec(existsSync(tar) ? tar : "tar", ["-xf", tmp, "-C", out], { windowsHide: true });+ }if (c === "deno") {- await rename(path.join(out, "deno.exe"), path.join(bin, "deno.exe"));+ await install(path.join(out, `deno${exe}`), path.join(bin, `deno${exe}`));+ } else if (isMac || isLinux) {+ // The macOS and Linux zips hold the ffmpeg binary alone.+ const target = path.join(bin, "ffmpeg");+ await rm(target, { recursive: true, force: true });+ await mkdir(target, { recursive: true });+ await install(path.join(out, "ffmpeg"), path.join(target, "ffmpeg"));} else {// ffmpeg-<build>/bin holds ffmpeg.exe, ffprobe.exe and the DLLs they need.const root = (await readdir(out)).find((d) => d.startsWith("ffmpeg"));diff --git a/server/src/browse.ts b/server/src/browse.tsindex 11fddd3..5611869 100644--- a/server/src/browse.ts+++ b/server/src/browse.ts@@ -2,7 +2,7 @@ import type { Innertube } from "youtubei.js";import { isLang, msg, type Lang } from "./i18n.js";import { sized, text, toTrack, withClient } from "./search.js";import type { Track } from "./types.js";-import { HttpError } from "./types.js";+import { HttpError, VIDEO_ID } from "./types.js";export interface Genre {/** YouTube Music's opaque "params" for the genre page. */@@ -29,14 +29,42 @@ export interface GenrePage {tracks: Track[];}+/** An album or single as a cover in a list (artist page, search). */+export interface AlbumCard {+ id: string;+ title: string;+ /** Empty on an artist's own page, where it goes without saying. */+ artist: string;+ year: string;+ thumb: string;+ art: string;+}+export interface ArtistPage {id: string;name: string;description: string;banner: string;tracks: Track[];+ albums: AlbumCard[];+ singles: AlbumCard[];+}++export interface AlbumPage {+ id: string;+ title: string;+ artist: string;+ artistId: string | null;+ /** YouTube Music's own lines, in the request's language: "Album • 1991", "13 songs • 49 minutes". */+ kind: string;+ info: string;+ thumb: string;+ art: string;+ tracks: Track[];}+export const ALBUM_ID = /^MPRE[\w-]{6,60}$/;+export const GENRE_ID = /^[\w-]{8,120}={0,2}$/;export const ARTIST_ID = /^UC[\w-]{22}$/;@@ -261,6 +289,36 @@ export async function genreArtists(id: string, offset: number, lang: Lang): Prom}/** An artist's most played songs (the "Top songs" shelf, expanded to its full list). */+function albumCard(item: any): AlbumCard | null {+ const id = typeof item?.id === "string" ? item.id : "";+ if (!ALBUM_ID.test(id)) return null;+ const subtitle = text(item.subtitle);+ const artists: string[] = (item.artists ?? []).map((a: { name?: string }) => text(a?.name)).filter(Boolean);+ return {+ id,+ title: text(item.title),+ artist: artists.join(", ") || text(item.author?.name),+ year: String(item.year ?? subtitle.match(/\b(19|20)\d\d\b/)?.[0] ?? ""),+ ...imagesOf(item),+ };+}++const albumCards = (items: any[]) => items.map(albumCard).filter((a): a is AlbumCard => !!a && !!a.title);++/** Every album of an artist: the page shows ten, its "more" link opens the whole discography. */+async function allAlbums(shelf: any, lang: Lang): Promise<AlbumCard[]> {+ const shown = albumCards(itemsOf(shelf));+ const more = shelf?.header?.more_content?.endpoint?.payload;+ if (!more?.browseId) return shown;+ try {+ const page = await withClient((yt) => browse(yt, { browseId: more.browseId, params: more.params }), lang);+ const all = albumCards(page.contents_memo?.get("MusicTwoRowItem") ?? []);+ return all.length >= shown.length ? all : shown;+ } catch {+ return shown;+ }+}+const artistPage = cached(30 * MINUTE, async (key): Promise<ArtistPage> => {const { lang, id } = parseKey(key);const page = await withClient((yt) => yt.music.getArtist(id), lang).catch(() => {@@ -268,13 +326,16 @@ const artistPage = cached(30 * MINUTE, async (key): Promise<ArtistPage> => {});const header: any = page.header;const shelf: any = page.sections.find((s) => s.type === "MusicShelf");+ // Album shelves are told apart by what they hold, not by their (translated) titles: albums come first, then singles.+ const releaseShelves: any[] = page.sections.filter((s: any) => itemsOf(s).some((i) => i.item_type === "album"));let items: any[] = itemsOf(shelf);// The shelf shows 5; its "show all" link is a playlist with the full ranking.const fullList = shelf?.endpoint?.payload?.browseId;- if (typeof fullList === "string" && fullList.startsWith("VL")) {- const more = await playlistItems(fullList, MAX_HITS * 2, lang);- if (more.length) items = more;- }+ const [more, albums] = await Promise.all([+ typeof fullList === "string" && fullList.startsWith("VL") ? playlistItems(fullList, MAX_HITS * 2, lang) : Promise.resolve([]),+ releaseShelves[0] ? allAlbums(releaseShelves[0], lang) : Promise.resolve([]),+ ]);+ if (more.length) items = more;const banner = (header?.thumbnail?.contents ?? header?.thumbnail ?? [])[0]?.url;const name = text(header?.title);const tracks = uniqueTracks(items.map((i) => toTrack(i, "song"))).slice(0, MAX_HITS);@@ -285,7 +346,56 @@ const artistPage = cached(30 * MINUTE, async (key): Promise<ArtistPage> => {description: text(header?.description),banner: typeof banner === "string" && banner.startsWith("https://") ? banner : "",tracks,+ albums,+ singles: releaseShelves[1] ? albumCards(itemsOf(releaseShelves[1])) : [],};});export const artist = (id: string, lang: Lang) => artistPage(keyOf(lang, id));++/** An album's tracks in order. Its tracks carry no cover or artist of their own: they get the album's. */+const albumPage = cached(60 * MINUTE, async (key): Promise<AlbumPage> => {+ const { lang, id } = parseKey(key);+ const album: any = await withClient((yt) => yt.music.getAlbum(id), lang).catch(() => {+ throw new HttpError(502, msg("albumUnavailable"));+ });+ const header = album.header;+ const title = text(header?.title);+ const artistRuns: any[] = header?.strapline_text_one?.runs ?? [];+ const artist = text(header?.strapline_text_one) || text(header?.author?.name);+ const artistId: string | null = artistRuns.map((r) => r?.endpoint?.payload?.browseId).find((b) => ARTIST_ID.test(b ?? "")) ?? null;+ const cover = imagesOf(header);+ const tracks = (album.contents ?? [])+ .filter((i: any) => typeof i?.id === "string" && VIDEO_ID.test(i.id))+ .map(+ (i: any): Track => ({+ id: i.id,+ title: text(i.title) || "Untitled",+ artist: (i.artists ?? []).map((a: { name?: string }) => text(a?.name)).filter(Boolean).join(", ") || artist,+ album: title,+ duration: i.duration?.seconds ?? 0,+ thumb: sized(cover.art, 120),+ art: cover.art,+ kind: "song",+ }),+ );+ if (!title && !tracks.length) throw new HttpError(404, msg("albumNotFound"));+ return {+ id,+ title,+ artist,+ artistId,+ kind: text(header?.subtitle),+ info: text(header?.second_subtitle),+ thumb: cover.thumb,+ art: cover.art,+ tracks,+ };+});++export const album = (id: string, lang: Lang) => albumPage(keyOf(lang, id));++export async function searchAlbums(query: string, lang: Lang): Promise<AlbumCard[]> {+ const result: any = await withClient((yt) => yt.music.search(query, { type: "album" }), lang);+ return albumCards(itemsOf(result.contents?.[0]));+}diff --git a/server/src/config.ts b/server/src/config.tsindex 2223574..3caceff 100644--- a/server/src/config.ts+++ b/server/src/config.ts@@ -24,4 +24,6 @@ export const config = {/** YouTube Music language when a request doesn't say (the app always does). */lang: process.env.MUSIKE_LANG ?? "en",location: process.env.MUSIKE_LOCATION ?? "BR",+ /** HTTP for youtubei.js; the platform's own fetch here (the Android app passes its native one). */+ fetch: undefined as typeof fetch | undefined,};diff --git a/server/src/i18n.ts b/server/src/i18n.tsindex b278b97..d61cf82 100644--- a/server/src/i18n.ts+++ b/server/src/i18n.ts@@ -27,6 +27,9 @@ const en = {genreEmpty: "Nothing found for this genre.",artistUnavailable: "Couldn't open this artist right now. Try again.",artistNotFound: "Artist not found.",+ albumUnavailable: "Couldn't open this album right now. Try again.",+ albumNotFound: "Album not found.",+ invalidAlbum: "Invalid album.",ytdlpMissing: "yt-dlp wasn't found on this computer. Open Settings in Musike to install it.",ytdlpTimeout: "yt-dlp took too long to answer.",ytdlpCantRun: "Couldn't run yt-dlp ({error}). Open Settings in Musike.",@@ -74,6 +77,9 @@ const pt: Record<MsgKey, string> = {genreEmpty: "Nada encontrado para este gênero.",artistUnavailable: "Não foi possível abrir este artista agora. Tente de novo.",artistNotFound: "Artista não encontrado.",+ albumUnavailable: "Não foi possível abrir este álbum agora. Tente de novo.",+ albumNotFound: "Álbum não encontrado.",+ invalidAlbum: "Álbum inválido.",ytdlpMissing: "O yt-dlp não foi encontrado neste computador. Abra Ajustes no Musike para instalar.",ytdlpTimeout: "O yt-dlp demorou demais para responder.",ytdlpCantRun: "Não foi possível executar o yt-dlp ({error}). Abra Ajustes no Musike.",diff --git a/server/src/library.ts b/server/src/library.tsindex d1984ef..48bc116 100644--- a/server/src/library.ts+++ b/server/src/library.ts@@ -1,36 +1,40 @@-import { randomUUID } from "node:crypto";-import { existsSync } from "node:fs";-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";-import path from "node:path";-import { config } from "./config.js";import { msg } from "./i18n.js";import { HttpError, VIDEO_ID, type Library, type Playlist, type Track } from "./types.js";-const FILE = path.join(config.dataDir, "library.json");+// No Node-only imports here: the Android app runs this same module, with its own storage.+const HISTORY_LIMIT = 60;+/** Where the library is kept: a file on the server and the desktop app, app storage on Android. */+export interface LibraryStorage {+ read(): Promise<string | null>;+ write(json: string): Promise<void>;+}++let storage: LibraryStorage | null = null;let state: Library | null = null;let writeChain: Promise<void> = Promise.resolve();+/** Set once at startup, before any request. */+export function useLibraryStorage(s: LibraryStorage) {+ storage = s;+ state = null;+}++const randomUUID = () => globalThis.crypto.randomUUID();+async function load(): Promise<Library> {if (state) return state;- if (existsSync(FILE)) {- state = JSON.parse(await readFile(FILE, "utf8")) as Library;- } else {- state = { favorites: [], playlists: [], history: [] };- }+ if (!storage) throw new Error("Library storage not configured");+ const json = await storage.read();+ state = json ? (JSON.parse(json) as Library) : { favorites: [], playlists: [], history: [] };return state;}-/** Serialized, atomic writes so concurrent requests never corrupt the file. */+/** Serialized writes so concurrent requests never interleave. */function persist(): Promise<void> {const snapshot = JSON.stringify(state, null, 2);- writeChain = writeChain.then(async () => {- await mkdir(config.dataDir, { recursive: true });- const tmp = `${FILE}.tmp`;- await writeFile(tmp, snapshot, "utf8");- await rename(tmp, FILE);- });+ writeChain = writeChain.then(() => storage!.write(snapshot));return writeChain;}diff --git a/server/src/libraryFile.ts b/server/src/libraryFile.tsnew file mode 100644index 0000000..9e95fbd--- /dev/null+++ b/server/src/libraryFile.ts@@ -0,0 +1,19 @@+import { existsSync } from "node:fs";+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import path from "node:path";+import { config } from "./config.js";+import type { LibraryStorage } from "./library.js";++/** The library as data/library.json, replaced atomically (write a temp file, then rename over). */+export function fileStorage(dir = config.dataDir): LibraryStorage {+ const file = path.join(dir, "library.json");+ return {+ read: async () => (existsSync(file) ? readFile(file, "utf8") : null),+ write: async (json) => {+ await mkdir(dir, { recursive: true });+ const tmp = `${file}.tmp`;+ await writeFile(tmp, json, "utf8");+ await rename(tmp, file);+ },+ };+}diff --git a/server/src/search.ts b/server/src/search.tsindex 66cd08a..09c3628 100644--- a/server/src/search.ts+++ b/server/src/search.ts@@ -11,7 +11,7 @@ const clients = new Map<string, Promise<Innertube>>();function yt(hl: string): Promise<Innertube> {let client = clients.get(hl);if (!client) {- client = Innertube.create({ retrieve_player: false, lang: hl, location: config.location }).catch((err) => {+ client = Innertube.create({ retrieve_player: false, lang: hl, location: config.location, fetch: config.fetch }).catch((err) => {clients.delete(hl);throw err;});diff --git a/server/src/unzip.ts b/server/src/unzip.tsnew file mode 100644index 0000000..29af902--- /dev/null+++ b/server/src/unzip.ts@@ -0,0 +1,79 @@+import { mkdir, readFile, writeFile } from "node:fs/promises";+import path from "node:path";+import { inflateRawSync } from "node:zlib";++const EOCD = 0x06054b50;+const CENTRAL = 0x02014b50;+const LOCAL = 0x04034b50;+const ZIP64_EXTRA = 0x0001;+const MAX32 = 0xffffffff;++/**+ * Extracts a zip archive into `outDir`. Linux needs this: its tar (GNU) can't read zip files, and unzip isn't+ * installed everywhere. Covers what the tool downloads use (stored and deflated entries, zip64 sizes); the+ * whole archive is read into memory, which is fine for a few tens of megabytes.+ */+export async function unzip(file: string, outDir: string): Promise<void> {+ const zip = await readFile(file);+ const root = path.resolve(outDir);++ // The end-of-central-directory record sits in the last 22 bytes, plus a comment of up to 64 KB.+ let eocd = zip.length - 22;+ const stop = Math.max(0, zip.length - 22 - 0xffff);+ while (eocd >= stop && zip.readUInt32LE(eocd) !== EOCD) eocd--;+ if (eocd < stop) throw new Error("Not a zip file");+ const entries = zip.readUInt16LE(eocd + 10);+ let p = zip.readUInt32LE(eocd + 16);++ for (let i = 0; i < entries; i++) {+ if (zip.readUInt32LE(p) !== CENTRAL) throw new Error("Damaged zip file");+ const method = zip.readUInt16LE(p + 10);+ let compressed = zip.readUInt32LE(p + 20);+ let size = zip.readUInt32LE(p + 24);+ const nameLength = zip.readUInt16LE(p + 28);+ const extraLength = zip.readUInt16LE(p + 30);+ const commentLength = zip.readUInt16LE(p + 32);+ let offset = zip.readUInt32LE(p + 42);+ const name = zip.toString("utf8", p + 46, p + 46 + nameLength);++ // Sizes too big for 32 bits live in the zip64 extra field, in this order, only when needed.+ let extra = p + 46 + nameLength;+ const extraEnd = extra + extraLength;+ while (extra + 4 <= extraEnd) {+ const id = zip.readUInt16LE(extra);+ const length = zip.readUInt16LE(extra + 2);+ if (id === ZIP64_EXTRA) {+ let field = extra + 4;+ const next = () => {+ const value = Number(zip.readBigUInt64LE(field));+ field += 8;+ return value;+ };+ if (size === MAX32) size = next();+ if (compressed === MAX32) compressed = next();+ if (offset === MAX32) offset = next();+ }+ extra += 4 + length;+ }+ p = extraEnd + commentLength;++ const target = path.resolve(root, name);+ if (!target.startsWith(root + path.sep)) throw new Error(`Unsafe path in zip: ${name}`);+ if (name.endsWith("/")) {+ await mkdir(target, { recursive: true });+ continue;+ }++ if (zip.readUInt32LE(offset) !== LOCAL) throw new Error("Damaged zip file");+ const start = offset + 30 + zip.readUInt16LE(offset + 26) + zip.readUInt16LE(offset + 28);+ const data = zip.subarray(start, start + compressed);+ let content: Buffer;+ if (method === 0) content = data;+ else if (method === 8) content = inflateRawSync(data);+ else throw new Error(`Unsupported zip compression (${method})`);+ if (content.length !== size) throw new Error(`Damaged zip entry: ${name}`);++ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, content);+ }+}diff --git a/web/index.html b/web/index.htmlindex f347624..db9fddb 100644--- a/web/index.html+++ b/web/index.html@@ -18,6 +18,17 @@// Before the app loads, so screen readers and the browser see the chosen language right away.var l = localStorage.getItem("musike:lang");if (l === "en" || l === "pt-BR") document.documentElement.lang = l;+ // Appearance chosen in Settings, applied before the first paint.+ var css = localStorage.getItem("musike:accent-css");+ if (css) {+ var s = document.createElement("style");+ s.id = "musike-accent";+ s.textContent = css;+ document.head.appendChild(s);+ }+ var a = JSON.parse(localStorage.getItem("musike:appearance") || "{}");+ if (a.compactSidebar === true) document.documentElement.dataset.rail = "compact";+ if (a.texture === false) document.documentElement.dataset.texture = "off";} catch (e) {}</script></head>diff --git a/web/package.json b/web/package.jsonindex 07c1551..91a807b 100644--- a/web/package.json+++ b/web/package.json@@ -1,15 +1,20 @@{"name": "@musike/web","private": true,- "version": "1.2.0",+ "version": "1.4.0","type": "module","scripts": {"dev": "vite --host","build": "tsc --noEmit && vite build",+ "build:native": "tsc --noEmit -p tsconfig.native.json && vite build --mode native","preview": "vite preview --host",- "typecheck": "tsc --noEmit"+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json"},"dependencies": {+ "@capacitor/app": "8.1.2",+ "@capacitor/core": "8.5.3",+ "@capacitor/filesystem": "8.1.5",+ "@capacitor/share": "8.0.3","@fontsource-variable/geist": "5.3.0","@fontsource-variable/geist-mono": "5.3.0","@phosphor-icons/react": "2.1.10",@@ -21,6 +26,7 @@},"devDependencies": {"@tailwindcss/vite": "4.3.3",+ "@types/node": "^22.20.5","@types/react": "^19.3.0","@types/react-dom": "^19.3.0","@vitejs/plugin-react": "^6.1.2",diff --git a/web/src/App.tsx b/web/src/App.tsxindex c61b7d3..74bfd66 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -14,12 +14,14 @@ import { FloatingVideo, Theater } from "./components/Video";import { MD, useMediaQuery } from "./hooks/useMediaQuery";import { useShortcuts } from "./hooks/useShortcuts";import { getT } from "./i18n";+import { capabilities } from "./lib/api";import { cn } from "./lib/format";import { legacyRedirect, NOW_PLAYING_HASH, paths } from "./lib/routes";import { usePlayer } from "./player/player";import { useLibrary } from "./stores/library";import { openSettings, useSystem } from "./stores/system";import { toast, useUi } from "./stores/ui";+import Album from "./views/Album";import Artist from "./views/Artist";import BatchSearch from "./views/BatchSearch";import Collection from "./views/Collection";@@ -48,8 +50,9 @@ export default function App() {void loadLibrary();}, [loadLibrary]);- // Check yt-dlp shortly after start and say so once if something needs doing.+ // Check yt-dlp shortly after start and say so once if something needs doing (not on Android: no yt-dlp there).useEffect(() => {+ if (!capabilities.engineSettings) return;const t = setTimeout(async () => {await loadSystem();const info = useSystem.getState().info;@@ -124,6 +127,7 @@ export default function App() {<Route path={paths.searchList} element={<BatchSearch />} /><Route path="/search/genre/:id" element={<Genre />} /><Route path="/search/artist/:id" element={<Artist />} />+ <Route path="/search/album/:id" element={<Album />} /><Route path={paths.library} element={<Library />} /><Route path={paths.favorites} element={<Collection kind="favorites" />} /><Route path={paths.history} element={<Collection kind="history" />} />diff --git a/web/src/components/AlbumTiles.tsx b/web/src/components/AlbumTiles.tsxnew file mode 100644index 0000000..d777319--- /dev/null+++ b/web/src/components/AlbumTiles.tsx@@ -0,0 +1,54 @@+import { Link } from "react-router";+import { cn } from "../lib/format";+import { paths } from "../lib/routes";+import type { AlbumCard } from "../lib/types";+import { Artwork } from "./Artwork";++/** An album cover with its title; opens the album. */+export function AlbumTile({ album, className }: { album: AlbumCard; className?: string }) {+ const sub = [album.artist, album.year].filter(Boolean).join(" · ");+ return (+ <Link to={paths.album(album.id)} state={{ name: album.title }} className={cn("group flex flex-col gap-2", className)}>+ <span className="block overflow-hidden rounded-[14px]">+ <Artwork+ src={album.art}+ fallback={album.thumb}+ className="aspect-square w-full transition-transform duration-300 ease-out-expo group-hover:scale-[1.04]"+ />+ </span>+ <span className="min-w-0">+ <span className="block truncate text-sm font-semibold">{album.title}</span>+ {sub && <span className="block truncate text-xs text-fg-2">{sub}</span>}+ </span>+ </Link>+ );+}++/** A titled, horizontally scrolling row of albums (an artist's albums or singles). */+export function AlbumRow({ title, albums }: { title: string; albums: AlbumCard[] }) {+ return (+ <section className="flex flex-col gap-3 pt-6">+ <h2 className="px-4 text-xl font-semibold tracking-tight md:px-6">{title}</h2>+ <ul className="no-scrollbar flex snap-x snap-mandatory scroll-px-4 gap-4 overflow-x-auto px-4 md:scroll-px-6 md:px-6">+ {albums.map((a) => (+ <li key={a.id} className="w-36 shrink-0 snap-start md:w-44">+ <AlbumTile album={a} />+ </li>+ ))}+ </ul>+ </section>+ );+}++/** Albums as a responsive grid (search results). */+export function AlbumGrid({ albums }: { albums: AlbumCard[] }) {+ return (+ <ul className="grid grid-cols-2 gap-x-3 gap-y-5 px-2 sm:grid-cols-3 md:px-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">+ {albums.map((a) => (+ <li key={a.id}>+ <AlbumTile album={a} />+ </li>+ ))}+ </ul>+ );+}diff --git a/web/src/components/BackupSection.tsx b/web/src/components/BackupSection.tsxindex c507139..a580778 100644--- a/web/src/components/BackupSection.tsx+++ b/web/src/components/BackupSection.tsx@@ -21,7 +21,7 @@ export function BackupSection() {setBusy("export");try {const backup = await createBackup();- downloadBackup(backup);+ await downloadBackup(backup);const s = summarize(backup);toast(t.backup.created(s.playlists, s.favorites));} catch (e) {diff --git a/web/src/components/Controls.tsx b/web/src/components/Controls.tsxindex 9f21e72..e686f11 100644--- a/web/src/components/Controls.tsx+++ b/web/src/components/Controls.tsx@@ -16,6 +16,7 @@ import {import { useState } from "react";import { useShallow } from "zustand/react/shallow";import { useT } from "../i18n";+import { capabilities } from "../lib/api";import { cn, formatTime } from "../lib/format";import type { Track } from "../lib/types";import { usePlayer } from "../player/player";@@ -166,6 +167,8 @@ export function ModeSwitch({ className }: { className?: string }) {const quality = usePlayer((s) => s.quality);const setQuality = usePlayer((s) => s.setQuality);const showingVideo = usePlayer((s) => s.mediaKind === "video");+ // The Android app plays audio only for now.+ if (!capabilities.video) return null;const seg = (on: boolean) =>cn(diff --git a/web/src/components/CustomizeSection.tsx b/web/src/components/CustomizeSection.tsxnew file mode 100644index 0000000..2e0008e--- /dev/null+++ b/web/src/components/CustomizeSection.tsx@@ -0,0 +1,148 @@+import { CheckIcon, PaletteIcon } from "@phosphor-icons/react";+import { useT } from "../i18n";+import { inkFor } from "../lib/accent";+import { cn } from "../lib/format";+import { ACCENTS, useAppearance } from "../stores/appearance";+import { useUi } from "../stores/ui";++/** Ready-made accent swatches plus any colour from the system picker. */+export function AccentPicker() {+ const t = useT();+ const accent = useAppearance((s) => s.accent);+ const set = useAppearance((s) => s.set);+ const custom = !ACCENTS.some((a) => a.color === accent);+ const swatch = "grid size-8 shrink-0 place-items-center rounded-full ring-offset-2 ring-offset-surface-2 transition-transform active:scale-90";++ return (+ <div className="flex flex-col gap-2 pt-1">+ <p className="text-[13px] text-fg-2">{t.customize.accent}</p>+ <div role="radiogroup" aria-label={t.customize.accent} className="flex flex-wrap items-center gap-2.5">+ {ACCENTS.map(({ id, color }) => {+ const on = accent === color;+ return (+ <button+ key={id}+ type="button"+ role="radio"+ aria-checked={on}+ aria-label={t.customize.colors[id]}+ title={t.customize.colors[id]}+ onClick={() => set({ accent: color })}+ className={cn(swatch, on && "ring-2 ring-fg")}+ style={{ background: color }}+ >+ {on && <CheckIcon size={15} weight="bold" style={{ color: inkFor(color) }} />}+ </button>+ );+ })}+ <label+ title={t.customize.customColor}+ className={cn(swatch, "relative cursor-pointer", custom && "ring-2 ring-fg")}+ style={{ background: custom ? accent : "conic-gradient(#f43f5e, #fbbf24, #a3e635, #22d3ee, #6366f1, #d946ef, #f43f5e)" }}+ >+ <input+ type="color"+ value={accent}+ onChange={(e) => set({ accent: e.target.value })}+ aria-label={t.customize.customColor}+ className="absolute inset-0 size-full cursor-pointer rounded-full opacity-0"+ />+ {custom ? (+ <CheckIcon size={15} weight="bold" style={{ color: inkFor(accent) }} />+ ) : (+ <PaletteIcon size={15} weight="bold" className="text-white drop-shadow" />+ )}+ </label>+ </div>+ </div>+ );+}++function SwitchRow({ label, body, checked, onChange }: { label: string; body?: string; checked: boolean; onChange: (on: boolean) => void }) {+ return (+ <label className="flex cursor-pointer items-center justify-between gap-3 px-3 py-2.5">+ <span>+ <span className="block text-sm font-medium">{label}</span>+ {body && <span className="block text-xs text-fg-2">{body}</span>}+ </span>+ <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} className="peer sr-only" />+ <span+ aria-hidden="true"+ className={cn(+ "relative h-6 w-10 shrink-0 rounded-full transition-colors duration-200 peer-focus-visible:outline-2 peer-focus-visible:outline-accent",+ checked ? "bg-accent" : "bg-surface-4",+ )}+ >+ <span+ className={cn(+ "absolute top-1 left-1 size-4 rounded-full transition-transform duration-200 ease-out-expo",+ checked ? "translate-x-4 bg-accent-ink" : "bg-fg-2",+ )}+ />+ </span>+ </label>+ );+}++/** What the app shows: panels, sidebar, list columns and the Home sections. */+export function LayoutSection() {+ const t = useT();+ const a = useAppearance();+ const panelOpen = useUi((s) => s.panelOpen);+ const setPanelDocked = useUi((s) => s.setPanelDocked);++ const homeSections = [+ ["homeShortcuts", t.customize.homeShortcuts],+ ["homeRecent", t.nav.recentlyPlayed],+ ["homeFavorites", t.home.yourFavorites],+ ] as const;++ return (+ <section className="flex flex-col gap-2">+ <h3 className="text-xs font-medium text-fg-3">{t.customize.layout}</h3>+ <div className="flex flex-col divide-y divide-line rounded-[16px] bg-surface-1 ring-1 ring-line">+ <SwitchRow label={t.customize.panel} body={t.customize.panelBody} checked={panelOpen} onChange={setPanelDocked} />+ <SwitchRow label={t.customize.sidebarPlaylists} checked={a.sidebarPlaylists} onChange={(v) => a.set({ sidebarPlaylists: v })} />+ <SwitchRow+ label={t.customize.compactSidebar}+ body={t.customize.compactSidebarBody}+ checked={a.compactSidebar}+ onChange={(v) => a.set({ compactSidebar: v })}+ />+ <SwitchRow label={t.customize.albumColumn} checked={a.albumColumn} onChange={(v) => a.set({ albumColumn: v })} />+ <SwitchRow label={t.customize.texture} checked={a.texture} onChange={(v) => a.set({ texture: v })} />+ </div>++ <p className="pt-2 text-[13px] text-fg-2">{t.customize.home}</p>+ <div className="flex flex-wrap gap-2">+ {homeSections.map(([key, label]) => (+ <button+ key={key}+ type="button"+ role="checkbox"+ aria-checked={a[key]}+ onClick={() => a.set({ [key]: !a[key] })}+ className={cn(+ "flex h-9 items-center gap-1.5 rounded-full px-3.5 text-[13px] font-medium ring-1 transition-colors",+ a[key] ? "bg-accent-soft text-accent-text ring-accent/40" : "text-fg-2 ring-line hover:text-fg",+ )}+ >+ {a[key] && <CheckIcon size={14} weight="bold" />}+ {label}+ </button>+ ))}+ </div>++ <button+ type="button"+ onClick={() => {+ a.reset();+ setPanelDocked(true);+ }}+ className="mt-1 self-start text-[13px] font-medium text-fg-2 underline-offset-2 hover:text-fg hover:underline"+ >+ {t.customize.reset}+ </button>+ </section>+ );+}diff --git a/web/src/components/Modal.tsx b/web/src/components/Modal.tsxindex a07b617..e9043c8 100644--- a/web/src/components/Modal.tsx+++ b/web/src/components/Modal.tsx@@ -46,6 +46,7 @@ export function Modal({ open, onClose, title, children }: Props) {role="dialog"aria-modal="true"aria-label={title}+ data-escape-closesinitial={from}animate={{ opacity: 1, scale: 1, y: 0 }}exit={from}diff --git a/web/src/components/NowPlaying.tsx b/web/src/components/NowPlaying.tsxindex dc08182..567d0ca 100644--- a/web/src/components/NowPlaying.tsx+++ b/web/src/components/NowPlaying.tsx@@ -7,7 +7,7 @@ import {XIcon,} from "@phosphor-icons/react";import { AnimatePresence, motion, useDragControls, useReducedMotion } from "motion/react";-import { useState } from "react";+import { useEffect, useState } from "react";import { createPortal } from "react-dom";import { useT } from "../i18n";import { cn } from "../lib/format";@@ -187,6 +187,13 @@ export function PanelDrawer() {const reduce = useReducedMotion();const t = useT();+ useEffect(() => {+ if (!open) return;+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [open, close]);+return createPortal(<AnimatePresence>{open && (@@ -194,6 +201,7 @@ export function PanelDrawer() {<motion.div className="absolute inset-0 bg-scrim" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={close} /><motion.asidearia-label={t.nowPlaying.panel}+ data-escape-closesinitial={reduce ? { opacity: 0 } : { x: "105%" }}animate={{ x: 0, opacity: 1 }}exit={reduce ? { opacity: 0 } : { x: "105%" }}diff --git a/web/src/components/Rail.tsx b/web/src/components/Rail.tsxindex 6ce2854..0d94059 100644--- a/web/src/components/Rail.tsx+++ b/web/src/components/Rail.tsx@@ -12,6 +12,7 @@ import { NavLink, useNavigate } from "react-router";import { useT } from "../i18n";import { cn } from "../lib/format";import { paths } from "../lib/routes";+import { useAppearance } from "../stores/appearance";import { useLibrary } from "../stores/library";import { needsAttention, useSystem } from "../stores/system";import { useUi } from "../stores/ui";@@ -38,14 +39,14 @@ function SettingsButton() {onClick={() => setOpen(true)}aria-label={attention ? t.nav.settingsAttention : t.nav.settings}title={t.nav.settings}- className="relative flex h-10 w-full items-center justify-center gap-2 rounded-full px-3 text-sm text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg xl:justify-start"+ className="relative flex h-10 w-full items-center justify-center gap-2 rounded-full px-3 text-sm text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg wide:justify-start"><GearSixIcon size={19} />- <span className="hidden flex-1 text-left xl:inline">{t.nav.settings}</span>+ <span className="hidden flex-1 text-left wide:inline">{t.nav.settings}</span>{attention && (<>- <span className="absolute top-2 right-[calc(50%-14px)] size-2 rounded-full bg-accent ring-2 ring-surface-2 xl:hidden" />- <span className="hidden rounded-full bg-accent-soft px-2 py-0.5 text-[11px] font-semibold text-accent-text xl:inline">+ <span className="absolute top-2 right-[calc(50%-14px)] size-2 rounded-full bg-accent ring-2 ring-surface-2 wide:hidden" />+ <span className="hidden rounded-full bg-accent-soft px-2 py-0.5 text-[11px] font-semibold text-accent-text wide:inline">{updatable ? t.nav.updatePill : t.nav.checkPill}</span></>@@ -63,9 +64,9 @@ function RailLink({ to, label, sub, end, children }: { to: string; label: stringtitle={label}className={({ isActive }) =>cn(- "group flex items-center justify-center gap-3 rounded-[14px] p-1.5 transition-colors duration-200 xl:justify-start",- "hover:bg-surface-3 xl:pr-3",- isActive && "xl:bg-surface-3",+ "group flex items-center justify-center gap-3 rounded-[14px] p-1.5 transition-colors duration-200 wide:justify-start",+ "hover:bg-surface-3 wide:pr-3",+ isActive && "wide:bg-surface-3",)}>@@ -79,7 +80,7 @@ function RailLink({ to, label, sub, end, children }: { to: string; label: string>{children}</span>- <span className="hidden min-w-0 xl:block">+ <span className="hidden min-w-0 wide:block"><span className={cn("block truncate text-sm font-medium", isActive ? "text-fg" : "text-fg-2 group-hover:text-fg")}>{label}</span>@@ -93,6 +94,7 @@ function RailLink({ to, label, sub, end, children }: { to: string; label: stringexport function Rail() {const t = useT();+ const sidebarPlaylists = useAppearance((s) => s.sidebarPlaylists);const playlists = useLibrary((s) => s.playlists);const favorites = useLibrary((s) => s.favorites);const createPlaylist = useLibrary((s) => s.createPlaylist);@@ -100,11 +102,11 @@ export function Rail() {const [creating, setCreating] = useState(false);return (- <aside className="island hidden w-[78px] shrink-0 md:flex xl:w-[256px]">+ <aside className="island hidden w-[78px] shrink-0 md:flex wide:w-[256px]"><div className="island-core flex w-full flex-col overflow-hidden">- <div className="flex h-16 items-center justify-center xl:justify-start xl:px-4">- <LogoMark className="size-8 text-accent-text xl:hidden" />- <span className="hidden xl:block">+ <div className="flex h-16 items-center justify-center wide:justify-start wide:px-4">+ <LogoMark className="size-8 text-accent-text wide:hidden" />+ <span className="hidden wide:block"><Logo /></span></div>@@ -118,7 +120,7 @@ export function Rail() {title={t.nav[key]}className={({ isActive }) =>cn(- "flex h-11 items-center justify-center gap-3 rounded-full transition-colors duration-200 xl:justify-start xl:px-4",+ "flex h-11 items-center justify-center gap-3 rounded-full transition-colors duration-200 wide:justify-start wide:px-4",isActive ? "bg-surface-4 text-fg" : "text-fg-2 hover:bg-surface-3 hover:text-fg",)}@@ -126,7 +128,7 @@ export function Rail() {{({ isActive }) => (<><Icon size={22} weight={isActive ? "fill" : "regular"} />- <span className="hidden text-sm font-medium xl:inline">{t.nav[key]}</span>+ <span className="hidden text-sm font-medium wide:inline">{t.nav[key]}</span></>)}</NavLink>@@ -136,13 +138,13 @@ export function Rail() {<div className="mx-4 my-3 h-px bg-line" /><div className="flex items-center justify-between px-4 pb-1">- <span className="hidden text-xs font-medium text-fg-3 xl:block">{t.nav.yourCollection}</span>+ <span className="hidden text-xs font-medium text-fg-3 wide:block">{t.nav.yourCollection}</span><buttontype="button"onClick={() => setCreating(true)}aria-label={t.nav.newPlaylist}title={t.nav.newPlaylist}- className="mx-auto grid size-8 place-items-center rounded-full text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg xl:mx-0"+ className="mx-auto grid size-8 place-items-center rounded-full text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg wide:mx-0"><PlusIcon size={18} /></button>@@ -159,7 +161,7 @@ export function Rail() {<ClockCounterClockwiseIcon size={20} /></span></RailLink>- {playlists.map((p) => (+ {sidebarPlaylists && playlists.map((p) => (<RailLink key={p.id} to={paths.playlist(p.id)} label={p.name} sub={t.common.tracks(p.tracks.length)}><Artwork src={p.tracks[0]?.thumb} className="size-full" iconSize={18} /></RailLink>diff --git a/web/src/components/SettingsDialog.tsx b/web/src/components/SettingsDialog.tsxindex 7c808f1..15f8fb4 100644--- a/web/src/components/SettingsDialog.tsx+++ b/web/src/components/SettingsDialog.tsx@@ -9,11 +9,12 @@ import {} from "@phosphor-icons/react";import { useEffect, useRef, useState, type ReactNode } from "react";import { LANGUAGES, useI18n, useT, type Lang } from "../i18n";-import type { Channel } from "../lib/api";+import { capabilities, type Channel } from "../lib/api";import { cn } from "../lib/format";import { useSystem } from "../stores/system";import { useUi } from "../stores/ui";import { BackupSection } from "./BackupSection";+import { AccentPicker, LayoutSection } from "./CustomizeSection";import { Modal } from "./Modal";function Segmented<T extends string>({@@ -136,6 +137,7 @@ export function SettingsDialog() {["light", <><SunIcon size={15} /> {t.settings.light}</>],]}/>+ <AccentPicker /></section><section className="flex flex-col gap-2">@@ -150,8 +152,11 @@ export function SettingsDialog() {/></section>+ <LayoutSection />+<BackupSection />+ {capabilities.engineSettings && (<section className="flex flex-col gap-3"><h3 className="text-xs font-medium text-fg-3">{t.settings.engine}</h3>@@ -237,6 +242,7 @@ export function SettingsDialog() {</ul>)}</section>+ )}</div></Modal>);diff --git a/web/src/components/TitleBar.tsx b/web/src/components/TitleBar.tsxindex 943de85..3c8a726 100644--- a/web/src/components/TitleBar.tsx+++ b/web/src/components/TitleBar.tsx@@ -1,9 +1,12 @@+import { desktop } from "../lib/desktop";+import { cn } from "../lib/format";import { selectCurrent, usePlayer } from "../player/player";import { Equalizer, LogoMark } from "./Brand";/**- * Title bar for the desktop app. The window is frameless; Windows draws its native buttons over the- * right end (the "titlebar area" env variables tell us how much room they take).+ * Title bar for the desktop app. The window is frameless; Windows and Linux draw their native buttons over the+ * right end (the "titlebar area" env variables tell us how much room they take), macOS its traffic lights+ * over the left end.*/export function TitleBar() {const track = usePlayer(selectCurrent);@@ -11,7 +14,7 @@ export function TitleBar() {return (<div- className="app-drag flex shrink-0 items-center gap-2.5 pl-3.5 select-none"+ className={cn("app-drag flex shrink-0 items-center gap-2.5 select-none", desktop?.platform === "darwin" ? "pl-[84px]" : "pl-3.5")}style={{height: "env(titlebar-area-height, 40px)",paddingRight: "calc(100vw - env(titlebar-area-x, 0px) - env(titlebar-area-width, 100vw) + 12px)",diff --git a/web/src/components/TrackList.tsx b/web/src/components/TrackList.tsxindex 1a18a28..f3c2070 100644--- a/web/src/components/TrackList.tsx+++ b/web/src/components/TrackList.tsx@@ -4,6 +4,7 @@ import { useT } from "../i18n";import { cn, formatTime } from "../lib/format";import type { Track } from "../lib/types";import { selectCurrent, usePlayer } from "../player/player";+import { useAppearance } from "../stores/appearance";import { useLibrary } from "../stores/library";import { useUi } from "../stores/ui";import { Artwork } from "./Artwork";@@ -115,9 +116,11 @@ interface ListProps {header?: boolean;}-export function TrackList({ tracks, context, playlistId, showAlbum = true, header = true }: ListProps) {+export function TrackList({ tracks, context, playlistId, showAlbum: albumWanted = true, header = true }: ListProps) {const playList = usePlayer((s) => s.playList);const t = useT();+ // Pages ask for the album column where it makes sense; Settings can turn it off everywhere.+ const showAlbum = useAppearance((s) => s.albumColumn) && albumWanted;return (<div>{header && (diff --git a/web/src/components/TrackMenu.tsx b/web/src/components/TrackMenu.tsxindex 3b676ba..6fed9e3 100644--- a/web/src/components/TrackMenu.tsx+++ b/web/src/components/TrackMenu.tsx@@ -73,7 +73,7 @@ export function TrackMenu() {};const content = menu && (- <div role="menu" aria-label={t.trackMenu.actionsFor(menu.track.title)} className="flex flex-col">+ <div role="menu" aria-label={t.trackMenu.actionsFor(menu.track.title)} data-escape-closes className="flex flex-col"><Item icon={<PlayIcon size={18} />} onClick={run(() => usePlayer.getState().playTrack(menu.track))}>{t.trackMenu.playNow}</Item>diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 3d1657c..f4b8d83 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -164,6 +164,8 @@ export const en = {aTrack: "this track",browserCantPlay: "The browser couldn't play this format.",serverDown: "Can't reach the Musike server. Is it running?",+ streamFailed: "YouTube stopped serving this track. Try it again in a moment.",+ offline: "You're offline. Connect to the internet to play music.",httpError: (status: number) => `Error ${status}`,},@@ -245,6 +247,7 @@ export const en = {idleBody:"Search for a song, artist or album. For music videos and live performances, use the Videos tab. You can also paste a YouTube link.",exploreGenres: "Browse by genre",+ albums: "Albums",},batch: {@@ -299,6 +302,19 @@ export const en = {openFailed: "Couldn't open this artist",noHits: "No songs found",noHitsBody: "YouTube Music doesn't list hits for this artist.",+ albums: "Albums",+ singles: "Singles & EPs",+ },++ album: {+ fallbackName: "Album",+ openFailed: "Couldn't open this album",+ play: (title: string) => `Play ${title}`,+ shuffle: "Shuffle play",+ saveAsPlaylist: "Save as playlist",+ openPlaylist: "Open playlist",+ noTracks: "No playable tracks",+ noTracksBody: "YouTube Music doesn't offer this album's tracks here.",},settings: {@@ -338,6 +354,32 @@ export const en = {depMissingAfter: "and restart Musike.",},+ customize: {+ accent: "Accent color",+ customColor: "Custom color",+ colors: {+ volt: "Volt",+ mint: "Mint",+ aqua: "Aqua",+ sky: "Sky",+ violet: "Violet",+ pink: "Pink",+ coral: "Coral",+ amber: "Amber",+ },+ layout: "Layout",+ panel: "Now playing panel",+ panelBody: "Docked on the right on wide screens",+ sidebarPlaylists: "Playlists in the sidebar",+ compactSidebar: "Compact sidebar",+ compactSidebarBody: "Icons only, more room for content",+ albumColumn: "Album column in track lists",+ texture: "Background texture",+ home: "Home page",+ homeShortcuts: "Shortcuts",+ reset: "Reset to defaults",+ },+backup: {yourData: "Your data",body: "Take your playlists, favorites and history to another computer or to the desktop app: export a file here and import it into the other Musike.",@@ -358,7 +400,7 @@ export const en = {mergeBody: "Adds what's missing. Nothing is deleted; playlists with the same name get the new tracks.",replaceTitle: "Replace everything",replaceBody: "Deletes the current library and makes it exactly like the backup.",- applySettings: "Also apply theme, language and player preferences",+ applySettings: "Also apply appearance, language and player preferences",confirmReplace: 'This deletes your current playlists, favorites and history. Tap "Replace now" to confirm.',replace: "Replace",replaceNow: "Replace now",diff --git a/web/src/i18n/pt.ts b/web/src/i18n/pt.tsindex 25af8de..63673d7 100644--- a/web/src/i18n/pt.ts+++ b/web/src/i18n/pt.ts@@ -158,6 +158,8 @@ export const pt: Messages = {aTrack: "esta faixa",browserCantPlay: "O navegador não conseguiu reproduzir este formato.",serverDown: "Servidor do Musike inacessível. Ele está rodando?",+ streamFailed: "O YouTube parou de entregar esta faixa. Tente de novo daqui a pouco.",+ offline: "Você está sem internet. Conecte-se para ouvir música.",httpError: (status) => `Erro ${status}`,},@@ -239,6 +241,7 @@ export const pt: Messages = {idleBody:"Busque por música, artista ou álbum. Para clipes e ao vivo, use a aba Vídeos. Também dá para colar um link do YouTube.",exploreGenres: "Explorar por gênero",+ albums: "Álbuns",},batch: {@@ -293,6 +296,19 @@ export const pt: Messages = {openFailed: "Não deu para abrir este artista",noHits: "Nenhuma música encontrada",noHitsBody: "O YouTube Music não lista sucessos para este artista.",+ albums: "Álbuns",+ singles: "Singles e EPs",+ },++ album: {+ fallbackName: "Álbum",+ openFailed: "Não deu para abrir este álbum",+ play: (title) => `Tocar ${title}`,+ shuffle: "Tocar em ordem aleatória",+ saveAsPlaylist: "Salvar como playlist",+ openPlaylist: "Abrir playlist",+ noTracks: "Nenhuma faixa para tocar",+ noTracksBody: "O YouTube Music não oferece as faixas deste álbum aqui.",},settings: {@@ -332,6 +348,32 @@ export const pt: Messages = {depMissingAfter: "e reinicie o Musike.",},+ customize: {+ accent: "Cor de destaque",+ customColor: "Cor personalizada",+ colors: {+ volt: "Volt",+ mint: "Menta",+ aqua: "Água",+ sky: "Céu",+ violet: "Violeta",+ pink: "Rosa",+ coral: "Coral",+ amber: "Âmbar",+ },+ layout: "Layout",+ panel: "Painel Tocando agora",+ panelBody: "Fixo à direita em telas largas",+ sidebarPlaylists: "Playlists na barra lateral",+ compactSidebar: "Barra lateral compacta",+ compactSidebarBody: "Só ícones, mais espaço para o conteúdo",+ albumColumn: "Coluna de álbum nas listas",+ texture: "Textura de fundo",+ home: "Página inicial",+ homeShortcuts: "Atalhos",+ reset: "Restaurar padrão",+ },+backup: {yourData: "Seus dados",body: "Leve playlists, favoritas e histórico para outro computador ou para o app desktop: exporte um arquivo aqui e importe na outra instância do Musike.",@@ -352,7 +394,7 @@ export const pt: Messages = {mergeBody: "Adiciona o que falta. Nada é apagado; playlists com o mesmo nome ganham as faixas novas.",replaceTitle: "Substituir tudo",replaceBody: "Apaga a biblioteca atual e deixa exatamente como no backup.",- applySettings: "Aplicar também tema, idioma e preferências do player",+ applySettings: "Aplicar também aparência, idioma e preferências do player",confirmReplace: 'Isso apaga suas playlists, favoritas e histórico atuais. Toque em "Substituir agora" para confirmar.',replace: "Substituir",replaceNow: "Substituir agora",diff --git a/web/src/lib/accent.ts b/web/src/lib/accent.tsnew file mode 100644index 0000000..b605470--- /dev/null+++ b/web/src/lib/accent.ts@@ -0,0 +1,62 @@+/**+ * Builds the accent colour variables for any colour the user picks.+ * The pick fills buttons as-is; the text versions are lightened (dark theme) or darkened (light theme)+ * until they read well on the theme's surfaces (WCAG AA, 4.5:1).+ */++type Rgb = [number, number, number];++const DARK_SURFACE: Rgb = [0x18, 0x1a, 0x20]; // --surface-2, dark theme+const LIGHT_SURFACE: Rgb = [0xf2, 0xf3, 0xf6]; // --surface-2, light theme+const WHITE: Rgb = [255, 255, 255];+const BLACK: Rgb = [0, 0, 0];++export const DEFAULT_ACCENT = "#c3ec52";++export const isHex = (v: unknown): v is string => typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v);++const toRgb = (hex: string): Rgb => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as Rgb;+const toHex = (c: Rgb) => `#${c.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;++function luminance([r, g, b]: Rgb): number {+ const lin = (v: number) => {+ const s = v / 255;+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);+}++const contrast = (a: Rgb, b: Rgb) => {+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number];+ return (hi + 0.05) / (lo + 0.05);+};++const mix = (a: Rgb, b: Rgb, t: number): Rgb => [0, 1, 2].map((i) => a[i]! + (b[i]! - a[i]!) * t) as Rgb;++/** Moves `color` toward `target` just enough to reach `ratio` against `surface`. */+function readable(color: Rgb, target: Rgb, surface: Rgb, ratio = 4.5): Rgb {+ for (let t = 0; t <= 1; t += 0.04) {+ const c = mix(color, target, t);+ if (contrast(c, surface) >= ratio) return c;+ }+ return target;+}++/** Black or white, whichever reads better on `hex` (the check mark on a swatch, text on accent buttons). */+export function inkFor(hex: string): string {+ const base = toRgb(hex);+ return contrast(base, BLACK) >= contrast(base, WHITE) ? "#0b0c0f" : "#ffffff";+}++/** CSS that overrides the theme's accent variables. Selectors outrank styles.css whatever the load order. */+export function accentCss(hex: string): string {+ const base = toRgb(hex);+ const ink = inkFor(hex);+ const darkText = readable(base, WHITE, DARK_SURFACE);+ const lightText = readable(base, BLACK, LIGHT_SURFACE);+ const rgb = (c: Rgb) => c.map(Math.round).join(" ");+ return (+ `html:root,html[data-theme="dark"]{--accent:${hex};--accent-ink:${ink};--accent-text:${toHex(darkText)};--accent-soft:rgb(${rgb(base)} / 0.13)}` ++ `html[data-theme="light"]{--accent:${hex};--accent-ink:${ink};--accent-text:${toHex(lightText)};--accent-soft:rgb(${rgb(lightText)} / 0.12)}`+ );+}diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 81b7230..5531a79 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -1,48 +1,19 @@import { getLang, getT } from "../i18n";-import type { ArtistPage, Genre, GenreArtist, GenrePage, Library, Playlist, Track } from "./types";+import {+ ApiError,+ type Channel,+ type ErrorCode,+ type ImportResult,+ type MusikeApi,+ type Prepared,+ type SystemInfo,+ type SystemJob,+ type SystemMedia,+} from "./apiTypes";+import type { AlbumCard, AlbumPage, ArtistPage, Genre, GenreArtist, GenrePage, Library, Playlist, Track } from "./types";-export type ErrorCode = "tool_missing" | "maybe_outdated" | "bot_check";--export class ApiError extends Error {- constructor(public status: number, message: string, public code?: ErrorCode) {- super(message);- }-}--export type Channel = "stable" | "nightly";--export interface ImportResult {- playlistsAdded: number;- playlistsMerged: number;- tracksAdded: number;- favoritesAdded: number;-}--export interface SystemJob {- kind: "update" | "install";- channel: Channel;- status: "running" | "done" | "error";- startedAt: number;- finishedAt?: number;- from: string | null;- to: string | null;- message: string;- log: string[];-}--export interface SystemInfo {- ytdlp: {- path: string | null;- version: string | null;- channel: Channel;- latest: Record<Channel, string | null>;- updateAvailable: boolean;- };- deno: string | null;- ffmpeg: string | null;- canInstall: boolean;- job: SystemJob | null;-}+// The HTTP backend: the Musike server (web app, desktop app). The Android build swaps this module for native/api.ts.+export * from "./apiTypes";/** The server answers errors (and YouTube Music answers names, like genres) in the app's language. */const LANG_HEADER = "x-musike-lang";@@ -64,7 +35,7 @@ async function request<T>(path: string, init?: RequestInit & { json?: unknown })return body as T;}-export const api = {+export const api: MusikeApi = {search: (q: string, type: "song" | "video", signal?: AbortSignal) =>request<{ tracks: Track[] }>(`/api/search?q=${encodeURIComponent(q)}&type=${type}`, { signal }).then((r) => r.tracks),suggest: (q: string, signal?: AbortSignal) =>@@ -75,13 +46,16 @@ export const api = {genreArtists: (id: string, offset: number) =>request<{ artists: GenreArtist[]; hasMore: boolean }>(`/api/genres/${encodeURIComponent(id)}/artists?offset=${offset}`),artist: (id: string, signal?: AbortSignal) => request<ArtistPage>(`/api/artists/${encodeURIComponent(id)}`, { signal }),+ album: (id: string, signal?: AbortSignal) => request<AlbumPage>(`/api/albums/${encodeURIComponent(id)}`, { signal }),+ searchAlbums: (q: string, signal?: AbortSignal) =>+ request<{ albums: AlbumCard[] }>(`/api/search/albums?q=${encodeURIComponent(q)}`, { signal }).then((r) => r.albums),/** The music video matching a song, or null when YouTube has none. */videoFor: (t: Track) =>request<{ track: Track | null }>(`/api/video-for/${t.id}?${new URLSearchParams({ title: t.title, artist: t.artist, duration: String(t.duration || "") })}`,).then((r) => r.track),prepare: (id: string, signal?: AbortSignal) =>- request<{ id: string; title: string; duration: number; hasSdVideo: boolean }>(`/api/prepare/${id}`, {+ request<Prepared>(`/api/prepare/${id}`, {method: "POST",signal,}),@@ -107,9 +81,26 @@ export const api = {updateYtdlp: (channel: Channel) => request<SystemJob>("/api/system/ytdlp", { method: "POST", json: { channel } }),};-export const streamUrl = (id: string, kind: "audio" | "video", quality: "sd" | "hd") =>+/** What a media element plays for a track: here, the server's stream proxy. The Android backend resolves it on the phone. */+export const streamSource = (id: string, kind: "audio" | "video", quality: "sd" | "hd"): string | Promise<string> =>kind === "audio" ? `/api/stream/${id}/audio` : `/api/stream/${id}/video?q=${quality}`;+/** Saves a text file the way this platform does it: a browser download (the desktop app shows "Save as"). */+export async function saveFile(name: string, text: string) {+ const url = URL.createObjectURL(new Blob([text], { type: "application/json" }));+ const a = Object.assign(document.createElement("a"), { href: url, download: name });+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 10_000);+}++/** Only the Android app needs its own bridge to the system's media controls. */+export const systemMedia: SystemMedia | null = null;++/** What this build can do. The Android build has no video yet, no yt-dlp to manage, and retries expired streams. */+export const capabilities = { video: true, engineSettings: true, retryOnError: false };+/** Media elements hide the HTTP error body; fetch it to show the real reason. */export async function explainStreamError(url: string): Promise<{ message: string; code?: ErrorCode }> {const t = getT();diff --git a/web/src/lib/apiTypes.ts b/web/src/lib/apiTypes.tsnew file mode 100644index 0000000..8a5d5d1--- /dev/null+++ b/web/src/lib/apiTypes.ts@@ -0,0 +1,96 @@+import type { AlbumCard, AlbumPage, ArtistPage, Genre, GenreArtist, GenrePage, Library, Playlist, Track } from "./types";++/**+ * What the app needs from a backend. The web app and the desktop app talk to the Musike server over HTTP+ * (lib/api.ts); the Android app does the same work on the phone (native/api.ts). The build picks one.+ */++export type ErrorCode = "tool_missing" | "maybe_outdated" | "bot_check";++export class ApiError extends Error {+ constructor(public status: number, message: string, public code?: ErrorCode) {+ super(message);+ }+}++export type Channel = "stable" | "nightly";++export interface ImportResult {+ playlistsAdded: number;+ playlistsMerged: number;+ tracksAdded: number;+ favoritesAdded: number;+}++export interface SystemJob {+ kind: "update" | "install";+ channel: Channel;+ status: "running" | "done" | "error";+ startedAt: number;+ finishedAt?: number;+ from: string | null;+ to: string | null;+ message: string;+ log: string[];+}++export interface SystemInfo {+ ytdlp: {+ path: string | null;+ version: string | null;+ channel: Channel;+ latest: Record<Channel, string | null>;+ updateAvailable: boolean;+ };+ deno: string | null;+ ffmpeg: string | null;+ canInstall: boolean;+ job: SystemJob | null;+}++export interface Prepared {+ id: string;+ title: string;+ duration: number;+ hasSdVideo: boolean;+}++/**+ * The operating system's media controls (notification, lock screen, headphone buttons) when the browser's+ * Media Session can't reach them: the Android app. Absent elsewhere.+ */+export interface SystemMedia {+ setTrack(track: { title: string; artist: string; album: string; artwork: string }): void;+ setState(state: { playing: boolean; position: number; duration: number }): void;+ onAction(handler: (action: "play" | "pause" | "next" | "previous" | "seek", position?: number) => void): void;+}++export interface MusikeApi {+ search(q: string, type: "song" | "video", signal?: AbortSignal): Promise<Track[]>;+ suggest(q: string, signal?: AbortSignal): Promise<string[]>;+ radio(id: string): Promise<Track[]>;+ genres(): Promise<Genre[]>;+ genre(id: string, signal?: AbortSignal): Promise<GenrePage>;+ genreArtists(id: string, offset: number): Promise<{ artists: GenreArtist[]; hasMore: boolean }>;+ artist(id: string, signal?: AbortSignal): Promise<ArtistPage>;+ album(id: string, signal?: AbortSignal): Promise<AlbumPage>;+ searchAlbums(q: string, signal?: AbortSignal): Promise<AlbumCard[]>;+ /** The music video matching a song, or null when YouTube has none. */+ videoFor(t: Track): Promise<Track | null>;+ prepare(id: string, signal?: AbortSignal): Promise<Prepared>;++ library(): Promise<Library>;+ addFavorite(t: Track): Promise<{ favorites: Track[] }>;+ addFavorites(tracks: Track[]): Promise<{ favorites: Track[] }>;+ removeFavorite(id: string): Promise<{ favorites: Track[] }>;+ pushHistory(t: Track): Promise<{ history: Track[] }>;+ createPlaylist(name: string, tracks?: Track[]): Promise<Playlist>;+ renamePlaylist(id: string, name: string): Promise<Playlist>;+ deletePlaylist(id: string): Promise<void>;+ addToPlaylist(id: string, t: Track | Track[]): Promise<Playlist>;+ removeFromPlaylist(id: string, trackId: string): Promise<Playlist>;+ importLibrary(backup: unknown, mode: "merge" | "replace"): Promise<ImportResult>;++ system(): Promise<SystemInfo>;+ updateYtdlp(channel: Channel): Promise<SystemJob>;+}diff --git a/web/src/lib/backup.ts b/web/src/lib/backup.tsindex b67a8b0..1690ad5 100644--- a/web/src/lib/backup.ts+++ b/web/src/lib/backup.ts@@ -1,8 +1,9 @@import { getLang, getT, isLang, useI18n } from "../i18n";import { usePlayer } from "../player/player";+import { cleanAppearance, currentAppearance, useAppearance, type Appearance } from "../stores/appearance";import { useLibrary } from "../stores/library";import { useUi } from "../stores/ui";-import { api, type ImportResult } from "./api";+import { api, saveFile, type ImportResult } from "./api";import type { Library } from "./types";/**@@ -18,6 +19,7 @@ export interface Backup {settings?: {theme?: "dark" | "light";lang?: string;+ appearance?: Partial<Appearance>;preferVideo?: boolean;quality?: "sd" | "hd";autoRadio?: boolean;@@ -37,6 +39,7 @@ export async function createBackup(): Promise<Backup> {settings: {theme: useUi.getState().theme,lang: getLang(),+ appearance: currentAppearance(),preferVideo: p.preferVideo,quality: p.quality,autoRadio: p.autoRadio,@@ -45,17 +48,9 @@ export async function createBackup(): Promise<Backup> {};}-/** Saves the backup as a file (browsers download it; the desktop app shows a "Save as" dialog). */-export function downloadBackup(backup: Backup) {- const blob = new Blob([JSON.stringify(backup, null, 2)], { type: "application/json" });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = `musike-backup-${backup.exportedAt.slice(0, 10)}.musike.json`;- document.body.appendChild(a);- a.click();- a.remove();- setTimeout(() => URL.revokeObjectURL(url), 10_000);+/** Saves the backup as a file: a download in browsers, "Save as" on desktop, the share sheet on Android. */+export function downloadBackup(backup: Backup): Promise<void> {+ return saveFile(`musike-backup-${backup.exportedAt.slice(0, 10)}.musike.json`, JSON.stringify(backup, null, 2));}export async function readBackup(file: File): Promise<Backup> {@@ -91,6 +86,7 @@ export async function restoreBackup(backup: Backup, mode: "merge" | "replace", aconst player = usePlayer.getState();if (s.theme === "dark" || s.theme === "light") useUi.getState().setTheme(s.theme);if (isLang(s.lang)) useI18n.getState().setLang(s.lang);+ if (s.appearance && typeof s.appearance === "object") useAppearance.getState().set(cleanAppearance(s.appearance));if (typeof s.autoRadio === "boolean") player.setAutoRadio(s.autoRadio);if (typeof s.volume === "number") player.setVolume(s.volume);if (s.quality === "sd" || s.quality === "hd") player.setQuality(s.quality);diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.tsindex e07d5aa..b1c8e02 100644--- a/web/src/lib/routes.ts+++ b/web/src/lib/routes.ts@@ -5,6 +5,7 @@ export const paths = {searchList: "/search/list",genre: (id: string) => `/search/genre/${encodeURIComponent(id)}`,artist: (id: string) => `/search/artist/${id}`,+ album: (id: string) => `/search/album/${id}`,library: "/library",favorites: "/favorites",history: "/history",diff --git a/web/src/lib/types.ts b/web/src/lib/types.tsindex 46f7a6a..547fd9a 100644--- a/web/src/lib/types.ts+++ b/web/src/lib/types.ts@@ -47,10 +47,36 @@ export interface GenrePage {tracks: Track[];}+/** An album or single as a cover in a list. */+export interface AlbumCard {+ id: string;+ title: string;+ /** Empty on an artist's own page. */+ artist: string;+ year: string;+ thumb: string;+ art: string;+}+export interface ArtistPage {id: string;name: string;description: string;banner: string;tracks: Track[];+ albums: AlbumCard[];+ singles: AlbumCard[];+}++export interface AlbumPage {+ id: string;+ title: string;+ artist: string;+ artistId: string | null;+ /** YouTube Music's own lines, already in the app language: "Album • 1991", "13 songs • 49 minutes". */+ kind: string;+ info: string;+ thumb: string;+ art: string;+ tracks: Track[];}diff --git a/web/src/native/android.ts b/web/src/native/android.tsnew file mode 100644index 0000000..15eb944--- /dev/null+++ b/web/src/native/android.ts@@ -0,0 +1,26 @@+import { App } from "@capacitor/app";+import { Capacitor, SystemBars, SystemBarsStyle } from "@capacitor/core";++// How the app fits into Android itself: the Back button and the system bars.+if (Capacitor.isNativePlatform()) {+ // Back closes what's on top (a dialog, a menu), then goes back through pages, then sends the app to the+ // background, where the music keeps playing.+ void App.addListener("backButton", () => {+ const overlay = [...document.querySelectorAll("[data-escape-closes]")].some((el) => el.getClientRects().length > 0);+ if (overlay) {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ return;+ }+ const idx = (window.history.state as { idx?: number } | null)?.idx ?? 0;+ if (idx > 0) window.history.back();+ else void App.minimizeApp();+ });++ // Status and navigation bar icons stay readable in both themes.+ const syncBars = () => {+ const light = document.documentElement.dataset.theme === "light";+ void SystemBars.setStyle({ style: light ? SystemBarsStyle.Light : SystemBarsStyle.Dark });+ };+ syncBars();+ new MutationObserver(syncBars).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });+}diff --git a/web/src/native/api.ts b/web/src/native/api.tsnew file mode 100644index 0000000..6912e73--- /dev/null+++ b/web/src/native/api.ts@@ -0,0 +1,132 @@+import { Directory, Encoding, Filesystem } from "@capacitor/filesystem";+import { Share } from "@capacitor/share";+import {+ album as albumPage,+ ALBUM_ID,+ artist as artistPage,+ ARTIST_ID,+ GENRE_ID,+ genre as genrePage,+ genreArtists,+ genres,+ searchAlbums,+} from "../../../server/src/browse";+import { msg, tr, type MsgKey } from "../../../server/src/i18n";+import * as library from "../../../server/src/library";+import { findVideoFor, radio, search, suggestions } from "../../../server/src/search";+import { HttpError, VIDEO_ID } from "../../../server/src/types";+import { getLang, getT } from "../i18n";+import { ApiError, type MusikeApi, type SystemInfo } from "../lib/apiTypes";+import "./android";+import { media } from "./media";+import { nativeStorage } from "./storage";+import { forgetUrl, resolveAudio } from "./streams";++// The Android backend: the Musike server's own code (search, genres, artists, albums, library), running on the+// phone instead of behind HTTP. The build swaps lib/api.ts for this module (see vite.config.ts).+export * from "../lib/apiTypes";++library.useLibraryStorage(nativeStorage);++const fail = (status: number, key: MsgKey) => new ApiError(status, tr(getLang(), msg(key)));++/** Runs a server function and turns its errors into what the app expects, in the app's language. */+async function call<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");+ try {+ const result = await fn();+ // The work can't be cancelled midway, but a caller that gave up must not get the result.+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");+ return result;+ } catch (e) {+ if (e instanceof HttpError) throw new ApiError(e.status, tr(getLang(), e.text), e.code);+ if (e instanceof ApiError || (e as Error).name === "AbortError") throw e;+ throw new ApiError(500, (e as Error).message || getT().player.serverDown);+ }+}++const tracks = (list: unknown[]) => list.slice(0, 500).map(library.sanitizeTrack);++const SYSTEM: SystemInfo = {+ ytdlp: { path: "built-in", version: null, channel: "stable", latest: { stable: null, nightly: null }, updateAvailable: false },+ deno: "built-in",+ ffmpeg: null,+ canInstall: false,+ job: null,+};++export const api: MusikeApi = {+ search: (q, type, signal) =>+ call(async () => {+ if (!q.trim()) throw fail(400, "emptyQuery");+ return search(q.trim().slice(0, 200), type, getLang());+ }, signal),+ suggest: (q, signal) => call(() => suggestions(q.trim().slice(0, 100), getLang()).catch(() => []), signal),+ radio: (id) => call(() => radio(id)),+ genres: () => call(() => genres(getLang())),+ genre: (id, signal) =>+ call(async () => {+ if (!GENRE_ID.test(id)) throw fail(400, "invalidGenre");+ return genrePage(id, getLang());+ }, signal),+ genreArtists: (id, offset) => call(() => genreArtists(id, offset, getLang())),+ artist: (id, signal) =>+ call(async () => {+ if (!ARTIST_ID.test(id)) throw fail(400, "invalidArtist");+ return artistPage(id, getLang());+ }, signal),+ album: (id, signal) =>+ call(async () => {+ if (!ALBUM_ID.test(id)) throw fail(400, "invalidAlbum");+ return albumPage(id, getLang());+ }, signal),+ searchAlbums: (q, signal) => call(() => searchAlbums(q.trim().slice(0, 200), getLang()), signal),+ videoFor: (t) => call(() => findVideoFor(t.id, t.title, t.artist, t.duration)),+ prepare: (id, signal) =>+ call(async () => {+ if (!VIDEO_ID.test(id)) throw fail(400, "invalidVideoId");+ const r = await resolveAudio(id);+ return { id, title: r.title, duration: r.duration, hasSdVideo: false };+ }, signal),++ library: () => call(() => library.getLibrary()),+ addFavorite: (t) => call(async () => ({ favorites: await library.addFavorite(library.sanitizeTrack(t)) })),+ addFavorites: (list) => call(async () => ({ favorites: await library.addFavorites(tracks(list)) })),+ removeFavorite: (id) => call(async () => ({ favorites: await library.removeFavorite(id) })),+ pushHistory: (t) => call(async () => ({ history: await library.pushHistory(library.sanitizeTrack(t)) })),+ createPlaylist: (name, list = []) => call(() => library.createPlaylist(name, tracks(list))),+ renamePlaylist: (id, name) => call(() => library.renamePlaylist(id, name)),+ deletePlaylist: (id) => call(() => library.deletePlaylist(id)),+ addToPlaylist: (id, t) => call(() => library.addToPlaylist(id, Array.isArray(t) ? tracks(t) : library.sanitizeTrack(t))),+ removeFromPlaylist: (id, trackId) => call(() => library.removeFromPlaylist(id, trackId)),+ importLibrary: (backup, mode) =>+ call(async () => {+ const b = (backup ?? {}) as { format?: unknown; version?: unknown; library?: unknown };+ if (b.format !== "musike-backup") throw fail(400, "notBackup");+ if (typeof b.version !== "number" || b.version > 1) throw fail(400, "newerBackup");+ return library.importLibrary(b.library, mode);+ }),++ system: async () => SYSTEM,+ updateYtdlp: async () => {+ throw new ApiError(400, "yt-dlp isn't used on this device.");+ },+};++/** On the phone, the media element plays YouTube's stream directly: resolved here, no proxy needed. */+export const streamSource = (id: string): Promise<string> => resolveAudio(id).then((r) => r.url);++export async function explainStreamError(url: string): Promise<{ message: string }> {+ forgetUrl(url);+ return { message: navigator.onLine ? getT().player.streamFailed : getT().player.offline };+}++/** Backups are shared through Android's share sheet (save to Files, Drive, send to the computer…). */+export async function saveFile(name: string, text: string) {+ const { uri } = await Filesystem.writeFile({ path: name, data: text, directory: Directory.Cache, encoding: Encoding.UTF8 });+ await Share.share({ title: name, files: [uri] });+}++export const systemMedia = media;++export const capabilities = { video: false, engineSettings: false, retryOnError: true };diff --git a/web/src/native/http.ts b/web/src/native/http.tsnew file mode 100644index 0000000..6387c94--- /dev/null+++ b/web/src/native/http.ts@@ -0,0 +1,56 @@+import { CapacitorHttp } from "@capacitor/core";++/**+ * fetch() for youtubei.js in the Android app. A WebView's own fetch can't talk to YouTube's API: it is cross-origin,+ * and the browser adds an Origin header that YouTube rejects. Requests go through Android's HTTP stack instead+ * (Capacitor's native HTTP), with exactly the headers youtubei.js set.+ */++export interface RawRequest {+ url: string;+ method: string;+ headers: Record<string, string>;+ body?: string;+}++export interface RawResponse {+ status: number;+ headers: Record<string, string>;+ body: string;+}++export type Transport = (req: RawRequest) => Promise<RawResponse>;++const capacitorTransport: Transport = async (req) => {+ const res = await CapacitorHttp.request({+ url: req.url,+ method: req.method,+ headers: req.headers,+ data: req.body,+ responseType: "text",+ });+ const body = typeof res.data === "string" ? res.data : JSON.stringify(res.data);+ return { status: res.status, headers: res.headers ?? {}, body };+};++export function makeFetch(transport: Transport): typeof fetch {+ return async (input, init) => {+ const request = input instanceof Request ? input : null;+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;+ // A standalone Headers keeps every header youtubei.js set (a Request would drop some, like User-Agent).+ const headers: Record<string, string> = {};+ new Headers(init?.headers ?? request?.headers ?? undefined).forEach((value, key) => {+ headers[key] = value;+ });+ const raw = init?.body ?? undefined;+ const body = raw == null ? undefined : typeof raw === "string" ? raw : await new Response(raw).text();+ const res = await transport({ url, method: init?.method ?? request?.method ?? "GET", headers, body });+ // Statuses without a body (204, 304) can't be given one.+ const bodyless = res.status === 204 || res.status === 304 || (res.status >= 100 && res.status < 200);+ const response = new Response(bodyless ? null : res.body, { status: res.status, headers: res.headers });+ Object.defineProperty(response, "url", { value: url });+ return response;+ };+}++export const nativeFetch = makeFetch(capacitorTransport);diff --git a/web/src/native/media.ts b/web/src/native/media.tsnew file mode 100644index 0000000..de9a8de--- /dev/null+++ b/web/src/native/media.ts@@ -0,0 +1,45 @@+import { registerPlugin, type PluginListenerHandle } from "@capacitor/core";+import type { SystemMedia } from "../lib/apiTypes";++/**+ * Bridge to the app's Android side (MusikePlaybackPlugin.java): a foreground service with a media session,+ * so music keeps playing with the screen off and the notification, lock screen and headphone buttons work.+ */+interface PlaybackPlugin {+ update(options: {+ title?: string;+ artist?: string;+ album?: string;+ artwork?: string;+ playing?: boolean;+ position?: number;+ duration?: number;+ }): Promise<void>;+ addListener(event: "action", fn: (e: { action: string; position?: number }) => void): Promise<PluginListenerHandle>;+}++const noop = async () => {};+const Playback = registerPlugin<PlaybackPlugin>("MusikePlayback", {+ // In a desktop browser (development), there is nothing to drive.+ web: () => ({ update: noop, addListener: async () => ({ remove: noop }) }),+});++// The system advances the position on its own while playing; only real changes need sending.+let last = { playing: false, position: 0, at: 0 };++export const media: SystemMedia = {+ setTrack(track) {+ last = { playing: last.playing, position: 0, at: Date.now() };+ void Playback.update({ ...track, position: 0 });+ },+ setState({ playing, position, duration }) {+ const now = Date.now();+ const expected = last.playing ? last.position + (now - last.at) / 1000 : last.position;+ if (playing === last.playing && Math.abs(position - expected) < 2 && now - last.at < 15_000) return;+ last = { playing, position, at: now };+ void Playback.update({ playing, position, duration: Number.isFinite(duration) ? duration : 0 });+ },+ onAction(handler) {+ void Playback.addListener("action", (e) => handler(e.action as Parameters<typeof handler>[0], e.position));+ },+};diff --git a/web/src/native/shims/config.ts b/web/src/native/shims/config.tsnew file mode 100644index 0000000..3844a89--- /dev/null+++ b/web/src/native/shims/config.ts@@ -0,0 +1,22 @@+// Stands in for server/src/config.ts in the Android build: only the YouTube Music settings matter on a phone.+import { Capacitor } from "@capacitor/core";+import { makeFetch, nativeFetch, type Transport } from "../http";++/** The phone's region ("pt-BR" → "BR"), so search results and genres match where the user is. */+function region(): string {+ for (const tag of navigator.languages ?? [navigator.language]) {+ const r = tag?.split("-")[1];+ if (r && /^[A-Z]{2}$/i.test(r)) return r.toUpperCase();+ }+ return "US";+}++// Development only: a desktop browser running this build can't use native HTTP, so a test harness may provide+// a stand-in transport (a local proxy that does the same job).+const devTransport = (globalThis as { __musikeTransport?: Transport }).__musikeTransport;++export const config = {+ lang: "en",+ location: region(),+ fetch: Capacitor.isNativePlatform() ? nativeFetch : devTransport ? makeFetch(devTransport) : undefined,+};diff --git a/web/src/native/shims/ytdlp.ts b/web/src/native/shims/ytdlp.tsnew file mode 100644index 0000000..83e989a--- /dev/null+++ b/web/src/native/shims/ytdlp.ts@@ -0,0 +1,6 @@+// Stands in for server/src/ytdlp.ts in the Android build. There is no yt-dlp on a phone: search goes through+// YouTube Music only, and streams are resolved by native/streams.ts.++export async function ytdlpSearch(_query: string): Promise<never> {+ throw new Error("Search is unavailable right now. Try again in a moment.");+}diff --git a/web/src/native/storage.ts b/web/src/native/storage.tsnew file mode 100644index 0000000..5a261b9--- /dev/null+++ b/web/src/native/storage.ts@@ -0,0 +1,29 @@+import { Directory, Encoding, Filesystem } from "@capacitor/filesystem";+import type { LibraryStorage } from "../../../server/src/library";++const FILE = "library.json";+const TMP = "library.tmp.json";+const where = { directory: Directory.Data, encoding: Encoding.UTF8 } as const;++async function readText(path: string): Promise<string | null> {+ try {+ const { data } = await Filesystem.readFile({ path, ...where });+ return typeof data === "string" ? data : await data.text();+ } catch {+ return null;+ }+}++/**+ * The library in the app's private storage. Each save goes to a temp file first and then replaces the real one,+ * so a crash mid-write can't leave a half-written library; if it happens between the two steps, the temp file+ * is the newest complete copy.+ */+export const nativeStorage: LibraryStorage = {+ read: async () => (await readText(FILE)) ?? (await readText(TMP)),+ write: async (json) => {+ await Filesystem.writeFile({ path: TMP, data: json, ...where });+ await Filesystem.deleteFile({ path: FILE, directory: Directory.Data }).catch(() => {});+ await Filesystem.rename({ from: TMP, to: FILE, directory: Directory.Data, toDirectory: Directory.Data });+ },+};diff --git a/web/src/native/streams.ts b/web/src/native/streams.tsnew file mode 100644index 0000000..99b49aa--- /dev/null+++ b/web/src/native/streams.ts@@ -0,0 +1,105 @@+import { msg, tr } from "../../../server/src/i18n";+import { text, withClient } from "../../../server/src/search";+import { getLang } from "../i18n";+import { ApiError } from "../lib/apiTypes";++/**+ * Resolves a track's audio on the phone, the job yt-dlp does on the server.+ *+ * YouTube only serves the first megabyte of a stream to most clients unless the request carries a proof-of-origin+ * token. A few clients don't need one; VISIONOS (the Apple Vision Pro app) is the one yt-dlp itself relies on, and+ * its URLs need no deciphering either. When YouTube changes that, the list of clients to try can be updated+ * remotely (mobile/streaming.json in the repository) without shipping a new app.+ */++const DEFAULT_CLIENTS = ["VISIONOS"];+const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";+const CLIENTS_KEY = "musike:stream-clients";++interface Resolved {+ url: string;+ title: string;+ duration: number;+ expiresAt: number;+}++const cache = new Map<string, Resolved>();+const inflight = new Map<string, Promise<Resolved>>();++const validClients = (v: unknown): string[] | null =>+ Array.isArray(v) && v.length > 0 && v.every((c) => typeof c === "string" && /^[A-Z_]{2,30}$/.test(c)) ? (v as string[]) : null;++function storedClients(): string[] {+ try {+ return validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? DEFAULT_CLIENTS;+ } catch {+ return DEFAULT_CLIENTS;+ }+}++let clients = storedClients();++/** Picks up a newer client list in the background; the stored one (or the default) is used meanwhile. */+async function refreshClients() {+ try {+ const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });+ const remote = validClients(((await res.json()) as { clients?: unknown }).clients);+ if (!remote) return;+ clients = remote;+ localStorage.setItem(CLIENTS_KEY, JSON.stringify(remote));+ } catch {+ // offline or no config yet: keep what we have+ }+}+void refreshClients();++async function resolve(id: string): Promise<Resolved> {+ let reason = "";+ for (const client of clients) {+ try {+ const info: any = await withClient((yt) => yt.getBasicInfo(id, { client: client as never }), getLang());+ const status = info.playability_status;+ if (status?.status && status.status !== "OK") {+ reason = text(status.reason) || reason;+ continue;+ }+ const formats: any[] = [...(info.streaming_data?.adaptive_formats ?? []), ...(info.streaming_data?.formats ?? [])].filter(+ (f) => f.has_audio && !f.has_video && typeof f.url === "string",+ );+ // AAC (m4a) first: every Android WebView plays it. Highest bitrate within the same kind.+ const best = formats.sort(+ (a, b) => Number(b.mime_type?.startsWith("audio/mp4")) - Number(a.mime_type?.startsWith("audio/mp4")) || (b.bitrate ?? 0) - (a.bitrate ?? 0),+ )[0];+ if (!best) continue;+ const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;+ const resolved: Resolved = {+ url: best.url,+ title: info.basic_info?.title ?? "",+ duration: info.basic_info?.duration ?? 0,+ expiresAt: expire || Date.now() + 3 * 3600_000,+ };+ cache.set(id, resolved);+ return resolved;+ } catch (e) {+ reason = (e as Error).message || reason;+ }+ }+ throw new ApiError(404, reason || tr(getLang(), msg("noAudio")));+}++/** A track's stream, from cache while its URL is still good for a minute or more. */+export function resolveAudio(id: string): Promise<Resolved> {+ const hit = cache.get(id);+ if (hit && hit.expiresAt - Date.now() > 60_000) return Promise.resolve(hit);+ let job = inflight.get(id);+ if (!job) {+ job = resolve(id).finally(() => inflight.delete(id));+ inflight.set(id, job);+ }+ return job;+}++/** Forgets the stream behind a URL that stopped working, so the next try resolves a fresh one. */+export function forgetUrl(url: string) {+ for (const [id, r] of cache) if (r.url === url) cache.delete(id);+}diff --git a/web/src/player/player.ts b/web/src/player/player.tsindex efd4474..a73057f 100644--- a/web/src/player/player.ts+++ b/web/src/player/player.ts@@ -1,6 +1,6 @@import { create } from "zustand";import { getT, useT } from "../i18n";-import { api, explainStreamError, streamUrl } from "../lib/api";+import { api, capabilities, explainStreamError, streamSource, systemMedia, type ApiError, type ErrorCode } from "../lib/api";import { shuffled } from "../lib/format";import type { Track } from "../lib/types";import { useLibrary } from "../stores/library";@@ -136,7 +136,7 @@ const needsClipLookup = (track: Track, preferVideo: boolean) =>export const usePlayer = create<PlayerState>((set, get) => {const kindFor = (track: Track): Kind =>- get().preferVideo && (track.kind === "video" || !!clipFor.get(track.id)) ? "video" : "audio";+ capabilities.video && get().preferVideo && (track.kind === "video" || !!clipFor.get(track.id)) ? "video" : "audio";/** The YouTube id to stream: the song itself, or its music video in Video mode. */const mediaIdFor = (track: Track, kind: Kind) =>kind === "video" && track.kind !== "video" ? clipFor.get(track.id)! : track.id;@@ -200,8 +200,20 @@ export const usePlayer = create<PlayerState>((set, get) => {});media.volume = s.volume;media.muted = s.muted;- media.src = streamUrl(mediaIdFor(track, kind), kind, s.quality);- if (autoplay) play(media);+ const start = (src: string) => {+ media.src = src;+ if (autoplay) play(media);+ };+ // The server's proxy URL is known right away; on Android the stream is first resolved on the phone.+ const source = streamSource(mediaIdFor(track, kind), kind, s.quality);+ if (typeof source === "string") start(source);+ else {+ const mine = token;+ source.then(+ (src) => mine === token && start(src),+ (err: ApiError) => mine === token && report(err.message, err.code),+ );+ }setMetadata(track);}@@ -254,25 +266,39 @@ export const usePlayer = create<PlayerState>((set, get) => {set({ status: "paused", position: 0 });}+ /** Shows why a track can't play, then moves on (unless every track would fail the same way). */+ function report(message: string, code?: ErrorCode) {+ const mine = token;+ set({ status: "error", statusText: { error: message } });+ const track = get().queue[get().index];+ // Tool problems hit every track: offer the fix instead of skipping through the whole queue.+ const toolProblem = code === "tool_missing" || code === "maybe_outdated";+ const t = getT();+ toast(+ t.player.cantPlay(track?.title ?? t.player.aTrack, message),+ "error",+ toolProblem ? { label: code === "tool_missing" ? t.common.install : t.common.update, run: openSettings } : undefined,+ );+ if (code !== "tool_missing" && get().index < get().queue.length - 1) {+ setTimeout(() => mine === token && get().next(), 2500);+ }+ }++ // A stream URL that expired mid-song gets one fresh try from the same spot before giving up.+ let retriedToken = -1;+function onError(media: HTMLMediaElement) {const mine = token;const url = media.currentSrc || media.src;+ if (capabilities.retryOnError && retriedToken !== mine) {+ const at = media.currentTime || get().position;+ load(get().index, { startAt: at, autoplay: true });+ retriedToken = token;+ return;+ }set({ status: "error" });explainStreamError(url).then(({ message, code }) => {- if (mine !== token) return;- set({ statusText: { error: message } });- const track = get().queue[get().index];- // Tool problems hit every track: offer the fix instead of skipping through the whole queue.- const toolProblem = code === "tool_missing" || code === "maybe_outdated";- const t = getT();- toast(- t.player.cantPlay(track?.title ?? t.player.aTrack, message),- "error",- toolProblem ? { label: code === "tool_missing" ? t.common.install : t.common.update, run: openSettings } : undefined,- );- if (code !== "tool_missing" && get().index < get().queue.length - 1) {- setTimeout(() => mine === token && get().next(), 2500);- }+ if (mine === token) report(message, code);});}@@ -310,6 +336,7 @@ export const usePlayer = create<PlayerState>((set, get) => {media.addEventListener("timeupdate", () => {if (!isActive() || pendingSeek > 0) return;if (Math.abs(media.currentTime - get().position) >= 0.2) set({ position: media.currentTime });+ syncSystemMedia(); // throttled on the other side});media.addEventListener("progress", () => {if (!isActive() || !media.buffered.length) return;@@ -351,7 +378,8 @@ export const usePlayer = create<PlayerState>((set, get) => {muted: saved.muted ?? false,shuffle: saved.shuffle ?? false,repeat: saved.repeat ?? "off",- preferVideo: saved.preferVideo ?? false,+ // Builds without video (Android) always play audio, whatever a backup or an old session says.+ preferVideo: capabilities.video && (saved.preferVideo ?? false),quality: saved.quality ?? "sd",autoRadio: saved.autoRadio ?? true,@@ -513,6 +541,7 @@ export const usePlayer = create<PlayerState>((set, get) => {},setPreferVideo: (on) => {+ if (on && !capabilities.video) return;set({ preferVideo: on });reloadIfKindChanged();},@@ -563,6 +592,7 @@ document.addEventListener("visibilitychange", () => document.visibilityState ===// Media Session: lock-screen, headset and notification controls.function setMetadata(track: Track) {+ systemMedia?.setTrack({ title: track.title, artist: track.artist, album: track.album ?? "", artwork: track.art || track.thumb });if (!("mediaSession" in navigator)) return;navigator.mediaSession.metadata = new MediaMetadata({title: track.title,@@ -578,15 +608,25 @@ function setMetadata(track: Track) {});}+/** The phone's notification and lock screen. A track that is loading is about to play, so it counts as playing:+ * reporting a pause between tracks would let Android stop the app in the background. */+function syncSystemMedia() {+ if (!systemMedia) return;+ const { status, position, duration } = usePlayer.getState();+ systemMedia.setState({ playing: status === "playing" || status === "loading", position, duration });+}+function syncPlaybackState() {+ syncSystemMedia();if (!("mediaSession" in navigator)) return;navigator.mediaSession.playbackState = usePlayer.getState().status === "playing" ? "playing" : "paused";syncPositionState();}function syncPositionState() {- if (!("mediaSession" in navigator) || !navigator.mediaSession.setPositionState) return;+ syncSystemMedia();const { duration, position } = usePlayer.getState();+ if (!("mediaSession" in navigator) || !navigator.mediaSession.setPositionState) return;if (!Number.isFinite(duration) || duration <= 0) return;try {navigator.mediaSession.setPositionState({ duration, position: Math.min(position, duration), playbackRate: 1 });@@ -595,6 +635,17 @@ function syncPositionState() {}}+if (systemMedia) {+ const p = () => usePlayer.getState();+ systemMedia.onAction((action, position) => {+ if (action === "play" && p().status !== "playing") p().toggle();+ else if (action === "pause" && p().status === "playing") p().toggle();+ else if (action === "next") p().next();+ else if (action === "previous") p().prev();+ else if (action === "seek" && position != null) p().seek(position);+ });+}+if ("mediaSession" in navigator) {const ms = navigator.mediaSession;const p = () => usePlayer.getState();diff --git a/web/src/stores/appearance.ts b/web/src/stores/appearance.tsnew file mode 100644index 0000000..75b7f57--- /dev/null+++ b/web/src/stores/appearance.ts@@ -0,0 +1,113 @@+import { create } from "zustand";+import { accentCss, DEFAULT_ACCENT, isHex } from "../lib/accent";++/** How the app looks and what it shows, per device. The Now Playing panel lives in the UI store (it has a button too). */+export interface Appearance {+ accent: string;+ sidebarPlaylists: boolean;+ compactSidebar: boolean;+ albumColumn: boolean;+ texture: boolean;+ homeShortcuts: boolean;+ homeRecent: boolean;+ homeFavorites: boolean;+}++export const DEFAULT_APPEARANCE: Appearance = {+ accent: DEFAULT_ACCENT,+ sidebarPlaylists: true,+ compactSidebar: false,+ albumColumn: true,+ texture: true,+ homeShortcuts: true,+ homeRecent: true,+ homeFavorites: true,+};++/** Ready-made accents. "volt" is Musike's own. */+export const ACCENTS = [+ { id: "volt", color: DEFAULT_ACCENT },+ { id: "mint", color: "#34d399" },+ { id: "aqua", color: "#22d3ee" },+ { id: "sky", color: "#60a5fa" },+ { id: "violet", color: "#a78bfa" },+ { id: "pink", color: "#f472b6" },+ { id: "coral", color: "#fb7c5c" },+ { id: "amber", color: "#fbbf24" },+] as const;++const KEY = "musike:appearance";+// The accent CSS itself, so index.html can apply it before the app loads (no flash of the default colour).+const CSS_KEY = "musike:accent-css";++/** Keeps only known keys with the right types: the value may come from an old version or a backup file. */+export function cleanAppearance(input: unknown): Appearance {+ const v = (input && typeof input === "object" ? input : {}) as Record<string, unknown>;+ const out: Appearance = { ...DEFAULT_APPEARANCE };+ if (isHex(v.accent)) out.accent = v.accent.toLowerCase();+ for (const k of Object.keys(DEFAULT_APPEARANCE) as (keyof Appearance)[]) {+ if (k !== "accent" && typeof v[k] === "boolean") (out[k] as boolean) = v[k];+ }+ return out;+}++function read(): Appearance {+ try {+ return cleanAppearance(JSON.parse(localStorage.getItem(KEY) ?? "{}"));+ } catch {+ return { ...DEFAULT_APPEARANCE };+ }+}++/** Applies what CSS needs: the accent colours and two switches read by stylesheets (compact rail, texture). */+function apply(a: Appearance) {+ const root = document.documentElement;+ const custom = a.accent !== DEFAULT_ACCENT;+ let style = document.getElementById("musike-accent");+ if (custom) {+ style ??= Object.assign(document.createElement("style"), { id: "musike-accent" });+ style.textContent = accentCss(a.accent);+ document.head.appendChild(style);+ } else {+ style?.remove();+ }+ if (a.compactSidebar) root.dataset.rail = "compact";+ else delete root.dataset.rail;+ if (a.texture) delete root.dataset.texture;+ else root.dataset.texture = "off";+ try {+ localStorage.setItem(KEY, JSON.stringify(a));+ if (custom) localStorage.setItem(CSS_KEY, accentCss(a.accent));+ else localStorage.removeItem(CSS_KEY);+ } catch {+ /* private mode */+ }+}++interface AppearanceState extends Appearance {+ set: (patch: Partial<Appearance>) => void;+ reset: () => void;+}++const initial = read();+apply(initial);++export const useAppearance = create<AppearanceState>((set, get) => ({+ ...initial,+ set: (patch) => {+ const { set: _s, reset: _r, ...current } = get();+ const next = cleanAppearance({ ...current, ...patch });+ apply(next);+ set(next);+ },+ reset: () => {+ apply(DEFAULT_APPEARANCE);+ set({ ...DEFAULT_APPEARANCE });+ },+}));++/** The current preferences without the store's functions (for backups). */+export function currentAppearance(): Appearance {+ const { set: _s, reset: _r, ...a } = useAppearance.getState();+ return a;+}diff --git a/web/src/stores/ui.ts b/web/src/stores/ui.tsindex ad2e340..8a6ec57 100644--- a/web/src/stores/ui.ts+++ b/web/src/stores/ui.ts@@ -42,6 +42,8 @@ interface UiState {toggleTheme: () => void;openPanel: (tab: PanelTab) => void;togglePanel: (tab: PanelTab) => void;+ /** Settings switch for the docked Now Playing panel on wide screens. */+ setPanelDocked: (open: boolean) => void;closePanel: () => void;toast: (message: string, tone?: Toast["tone"], action?: ToastAction) => void;dismissToast: (id: number) => void;@@ -108,6 +110,14 @@ export const useUi = create<UiState>((set, get) => ({set({ panelOpen: open, panelTab: tab });},closePanel: () => set({ drawerOpen: false }),+ setPanelDocked: (open) => {+ try {+ localStorage.setItem("musike:panel", open ? "open" : "closed");+ } catch {+ /* private mode */+ }+ set({ panelOpen: open });+ },toast: (message, tone = "info", action) => {const id = ++toastSeq;diff --git a/web/src/styles.css b/web/src/styles.cssindex b504f71..25f7cec 100644--- a/web/src/styles.css+++ b/web/src/styles.css@@ -1,6 +1,14 @@@import "tailwindcss";@custom-variant light (&:where([data-theme="light"], [data-theme="light"] *));+/* The wide (labelled) rail, from 1280px up unless the user chose a compact sidebar in Settings. */+@custom-variant wide {+ @media (width >= 80rem) {+ &:where(html:not([data-rail="compact"]) *) {+ @slot;+ }+ }+}/* Theme tokens. Dark is the default; see docs/design-system.md */:root,@@ -175,6 +183,9 @@[data-theme="light"] .grain::after {opacity: 0.025;}+[data-texture="off"] .grain::after {+ display: none;+}/* Living brand mark: the equalizer that marks the playing track. */@keyframes eq {diff --git a/web/src/views/Album.tsx b/web/src/views/Album.tsxnew file mode 100644index 0000000..1dd3a82--- /dev/null+++ b/web/src/views/Album.tsx@@ -0,0 +1,140 @@+import { ArrowRightIcon, MusicNotesIcon, PauseIcon, PlayIcon, PlaylistIcon, ShuffleIcon, WarningCircleIcon } from "@phosphor-icons/react";+import { useState } from "react";+import { Link, useLocation, useParams } from "react-router";+import { Artwork } from "../components/Artwork";+import { IconButton, PlayDisc } from "../components/IconButton";+import { BackButton, EmptyState, PageHeader } from "../components/Page";+import { SelectableTrackList } from "../components/Selection";+import { TrackListSkeleton } from "../components/TrackList";+import { useRemote } from "../hooks/useRemote";+import { useI18n, useT } from "../i18n";+import { api } from "../lib/api";+import { shuffled } from "../lib/format";+import { paths } from "../lib/routes";+import type { AlbumPage } from "../lib/types";+import { usePlayer } from "../player/player";+import { useLibrary } from "../stores/library";++/** An album, its tracks in their original order: play it whole, shuffle it, save it or pick from it. */+export default function Album() {+ const { id = "" } = useParams();+ const location = useLocation();+ const lang = useI18n((s) => s.lang);+ const t = useT();+ const page = useRemote<AlbumPage>(`album:${lang}:${id}`, (signal) => api.album(id, signal));+ const playList = usePlayer((s) => s.playList);+ const toggle = usePlayer((s) => s.toggle);+ const queue = usePlayer((s) => s.queue);+ const status = usePlayer((s) => s.status);+ const createPlaylist = useLibrary((s) => s.createPlaylist);+ const [saved, setSaved] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ const album = page.status === "ok" ? page.data : null;+ const tracks = album?.tracks ?? [];+ const title = album?.title || (location.state as { name?: string } | null)?.name || t.album.fallbackName;+ // The queue holds exactly this album: the big button pauses and resumes instead of starting over.+ const isThisPlaying = tracks.length > 0 && queue.length === tracks.length && queue.every((q, i) => q.id === tracks[i]?.id);+ const playing = isThisPlaying && (status === "playing" || status === "loading");++ const save = async () => {+ if (!album) return;+ setSaving(true);+ const p = await createPlaylist(album.artist ? `${album.title} · ${album.artist}` : album.title, tracks);+ setSaving(false);+ if (p) setSaved(p.id);+ };++ return (+ <div className="pb-8">+ <PageHeader title={title} actions={<BackButton fallback={paths.search} />} />++ <div className="relative">+ <div aria-hidden="true" className="pointer-events-none absolute inset-x-0 -top-20 h-72 bg-linear-to-b from-accent-soft to-transparent" />+ <div className="relative flex flex-col items-center gap-5 px-4 pt-2 pb-6 md:flex-row md:items-end md:gap-6 md:px-6 md:pt-6">+ {album ? (+ <Artwork+ src={album.art}+ fallback={album.thumb}+ iconSize={64}+ className="size-44 shrink-0 rounded-[18px] shadow-[0_24px_60px_rgb(0_0_0/0.4)] md:size-52"+ />+ ) : (+ <span className="skeleton size-44 shrink-0 rounded-[18px] md:size-52" />+ )}+ <div className="flex min-w-0 flex-col items-center gap-2 text-center md:items-start md:text-left">+ {album?.kind && <span className="text-xs font-medium text-fg-2">{album.kind}</span>}+ <h1 className="max-w-full text-[28px] leading-[1.1] font-bold tracking-tight break-words md:text-5xl">{title}</h1>+ {album?.artist &&+ (album.artistId ? (+ <Link to={paths.artist(album.artistId)} state={{ name: album.artist }} className="font-medium hover:underline">+ {album.artist}+ </Link>+ ) : (+ <span className="font-medium">{album.artist}</span>+ ))}+ {album?.info && <p className="font-mono text-[13px] text-fg-2">{album.info}</p>}+ </div>+ </div>+ </div>++ {album && tracks.length > 0 && (+ <div className="flex items-center gap-2 px-4 pb-4 md:px-6">+ <PlayDisc+ label={playing ? t.common.pause : t.album.play(album.title)}+ px={56}+ onClick={() => (isThisPlaying ? toggle() : playList(tracks, 0))}+ >+ {playing ? <PauseIcon size={24} weight="fill" /> : <PlayIcon size={24} weight="fill" />}+ </PlayDisc>+ <IconButton label={t.album.shuffle} size="lg" onClick={() => playList(shuffled(tracks), 0)}>+ <ShuffleIcon size={24} />+ </IconButton>+ {saved ? (+ <Link+ to={paths.playlist(saved)}+ className="ml-1 flex h-11 items-center gap-2 rounded-full bg-accent-soft px-4 text-sm font-medium text-accent-text"+ >+ {t.album.openPlaylist} <ArrowRightIcon size={16} />+ </Link>+ ) : (+ <button+ type="button"+ disabled={saving}+ onClick={() => void save()}+ className="ml-1 flex h-11 items-center gap-2 rounded-full bg-surface-3 px-4 text-sm font-medium transition-transform hover:bg-surface-4 active:scale-[0.97] disabled:opacity-60"+ >+ <PlaylistIcon size={18} /> {t.album.saveAsPlaylist}+ </button>+ )}+ </div>+ )}++ {page.status === "loading" && <TrackListSkeleton />}++ {page.status === "error" && (+ <EmptyState+ icon={<WarningCircleIcon size={28} />}+ title={t.album.openFailed}+ body={page.message}+ action={+ <button+ type="button"+ onClick={page.retry}+ className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm font-medium hover:bg-surface-4"+ >+ {t.common.retry}+ </button>+ }+ />+ )}++ {album &&+ (tracks.length ? (+ <SelectableTrackList key={id} tracks={tracks} numbered />+ ) : (+ <EmptyState icon={<MusicNotesIcon size={28} />} title={t.album.noTracks} body={t.album.noTracksBody} />+ ))}+ </div>+ );+}diff --git a/web/src/views/Artist.tsx b/web/src/views/Artist.tsxindex 0eb1de7..3442003 100644--- a/web/src/views/Artist.tsx+++ b/web/src/views/Artist.tsx@@ -1,6 +1,7 @@import { MusicNotesIcon, WarningCircleIcon } from "@phosphor-icons/react";import { useState } from "react";import { useLocation, useParams } from "react-router";+import { AlbumRow } from "../components/AlbumTiles";import { Artwork } from "../components/Artwork";import { BackButton, EmptyState, PageHeader } from "../components/Page";import { SelectableTrackList } from "../components/Selection";@@ -52,6 +53,9 @@ export default function Artist() {</button>)}+ {page.status === "ok" && page.data.albums.length > 0 && <AlbumRow title={t.artist.albums} albums={page.data.albums} />}+ {page.status === "ok" && page.data.singles.length > 0 && <AlbumRow title={t.artist.singles} albums={page.data.singles} />}+<h2 className="px-4 pt-6 pb-1 text-xl font-semibold tracking-tight md:px-6">{t.artist.hits}</h2>{page.status === "loading" && <TrackListSkeleton />}diff --git a/web/src/views/Home.tsx b/web/src/views/Home.tsxindex c0684bf..e5f1d78 100644--- a/web/src/views/Home.tsx+++ b/web/src/views/Home.tsx@@ -9,6 +9,7 @@ import { useT } from "../i18n";import { paths } from "../lib/routes";import type { Track } from "../lib/types";import { usePlayer } from "../player/player";+import { useAppearance } from "../stores/appearance";import { useLibrary } from "../stores/library";function Shortcut({ to, label, tracks, cover }: { to: string; label: string; tracks: Track[]; cover: ReactNode }) {@@ -55,6 +56,7 @@ export default function Home() {const playList = usePlayer((s) => s.playList);const navigate = useNavigate();const t = useT();+ const show = useAppearance();const empty = status === "ready" && !favorites.length && !playlists.length && !history.length;return (@@ -88,7 +90,7 @@ export default function Home() {{!empty && status === "ready" && (<div className="flex flex-col gap-10">- <div className="grid grid-cols-2 gap-2 px-4 md:px-6 lg:grid-cols-3 2xl:grid-cols-4">+ {show.homeShortcuts && <div className="grid grid-cols-2 gap-2 px-4 md:px-6 lg:grid-cols-3 2xl:grid-cols-4"><Shortcutto={paths.favorites}label={t.nav.favorites}@@ -118,9 +120,9 @@ export default function Home() {cover={<Artwork src={p.tracks[0]?.thumb} className="size-full" />}/>))}- </div>+ </div>}- {history.length > 0 && (+ {show.homeRecent && history.length > 0 && (<Sectiontitle={t.nav.recentlyPlayed}action={@@ -137,7 +139,7 @@ export default function Home() {</Section>)}- {favorites.length > 0 && (+ {show.homeFavorites && favorites.length > 0 && (<Sectiontitle={t.home.yourFavorites}action={diff --git a/web/src/views/Search.tsx b/web/src/views/Search.tsxindex f9c5028..f6891cd 100644--- a/web/src/views/Search.tsx+++ b/web/src/views/Search.tsx@@ -11,6 +11,7 @@ import {} from "@phosphor-icons/react";import { useEffect, useRef, useState } from "react";import { Link, useSearchParams } from "react-router";+import { AlbumGrid } from "../components/AlbumTiles";import { Artwork } from "../components/Artwork";import { GenrePanel } from "../components/GenrePanel";import { EmptyState, PageHeader } from "../components/Page";@@ -20,7 +21,7 @@ import { api } from "../lib/api";import { useT } from "../i18n";import { cn } from "../lib/format";import { paths } from "../lib/routes";-import type { Track } from "../lib/types";+import type { AlbumCard, Track } from "../lib/types";import { usePlayer } from "../player/player";import { parseList } from "./BatchSearch";@@ -54,7 +55,8 @@ function videoIdFromUrl(text: string): string | null {}}-type Kind = "song" | "video";+type Kind = "song" | "video" | "album";+const KIND_PARAM: Record<Kind, string | null> = { song: null, video: "videos", album: "albums" };// The genre panel stays open when coming back from a genre page.let genresOpenMemo = false;@@ -62,10 +64,11 @@ let genresOpenMemo = false;export default function Search() {const [params, setParams] = useSearchParams();const q = params.get("q") ?? "";- const kind: Kind = params.get("type") === "videos" ? "video" : "song";+ const kind: Kind = params.get("type") === "videos" ? "video" : params.get("type") === "albums" ? "album" : "song";const t = useT();const [text, setText] = useState(q);const [results, setResults] = useState<Track[] | null>(null);+ const [albums, setAlbums] = useState<AlbumCard[] | null>(null);const [state, setState] = useState<"idle" | "loading" | "ok" | "error">("idle");const [error, setError] = useState("");const [suggestions, setSuggestions] = useState<string[]>([]);@@ -89,7 +92,8 @@ export default function Search() {const setQuery = (next: string, nextKind = kind) => {const p = new URLSearchParams();if (next.trim()) p.set("q", next.trim());- if (nextKind === "video") p.set("type", "videos");+ const type = KIND_PARAM[nextKind];+ if (type) p.set("type", type);setParams(p, { replace: true });};@@ -106,15 +110,18 @@ export default function Search() {useEffect(() => {if (!q) {setResults(null);+ setAlbums(null);setState("idle");return;}const ctrl = new AbortController();setState("loading");- api- .search(q, kind, ctrl.signal)- .then((tracks) => {- setResults(tracks);+ const found: Promise<number> =+ kind === "album"+ ? api.searchAlbums(q, ctrl.signal).then((list) => (setAlbums(list), setResults(null), list.length))+ : api.search(q, kind, ctrl.signal).then((list) => (setResults(list), setAlbums(null), list.length));+ found+ .then(() => {setState("ok");const next = [q, ...readRecent().filter((r) => r.toLowerCase() !== q.toLowerCase())].slice(0, 8);saveRecent(next);@@ -271,6 +278,7 @@ export default function Search() {<div role="tablist" aria-label={t.search.resultType} className="flex gap-2">{tab("song", t.search.songs)}{tab("video", t.search.videos)}+ {tab("album", t.search.albums)}</div><span className="flex-1" /><div className="flex items-center gap-1">@@ -348,6 +356,12 @@ export default function Search() {/>)}+ {!linkId && state === "ok" && albums && (albums.length ? (+ <AlbumGrid albums={albums} />+ ) : (+ <EmptyState icon={<MagnifyingGlassIcon size={28} />} title={t.search.nothingFound} body={t.search.nothingFoundBody(q, t.search.songs)} />+ ))}+{!linkId && state === "ok" && results && results.length === 0 && (<EmptyStateicon={<MagnifyingGlassIcon size={28} />}diff --git a/web/tsconfig.json b/web/tsconfig.jsonindex 28c0ffe..b5c70cc 100644--- a/web/tsconfig.json+++ b/web/tsconfig.json@@ -1,7 +1,11 @@{"compilerOptions": {"target": "ES2023",- "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "lib": [+ "ES2023",+ "DOM",+ "DOM.Iterable"+ ],"module": "ESNext","moduleResolution": "Bundler","jsx": "react-jsx",@@ -11,7 +15,16 @@"skipLibCheck": true,"noEmit": true,"isolatedModules": true,- "types": ["vite/client", "vite-plugin-pwa/client"]+ "types": [+ "vite/client",+ "vite-plugin-pwa/client"+ ]},- "include": ["src", "vite.config.ts"]+ "include": [+ "src",+ "vite.config.ts"+ ],+ "exclude": [+ "src/native"+ ]}diff --git a/web/tsconfig.native.json b/web/tsconfig.native.jsonnew file mode 100644index 0000000..42fe28c--- /dev/null+++ b/web/tsconfig.native.json@@ -0,0 +1,12 @@+{+ // The Android backend (src/native) runs the server's own modules in the app, so it is checked with Node's types+ // available (the server code mentions them even where the Android build swaps those modules out).+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "types": ["vite/client", "vite-plugin-pwa/client", "node"],+ "noUnusedLocals": false,+ "noUnusedParameters": false+ },+ "include": ["src"],+ "exclude": []+}diff --git a/web/vite.config.ts b/web/vite.config.tsindex 6b134b0..bd19855 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -1,55 +1,100 @@import { readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";import tailwindcss from "@tailwindcss/vite";import react from "@vitejs/plugin-react";-import { defineConfig } from "vite";+import { defineConfig, type Plugin } from "vite";import { VitePWA } from "vite-plugin-pwa";const { version } = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string };+const here = path.dirname(fileURLToPath(import.meta.url));+const src = (...p: string[]) => path.join(here, "src", ...p);+const server = (...p: string[]) => path.join(here, "..", "server", "src", ...p);+const same = (a: string, b: string) => path.normalize(a).toLowerCase() === path.normalize(b).toLowerCase();-export default defineConfig({- define: { __APP_VERSION__: JSON.stringify(version) },- plugins: [- react(),- tailwindcss(),- VitePWA({- registerType: "autoUpdate",- includeAssets: ["favicon.svg", "apple-touch-icon.png"],- manifest: {- name: "Musike",- short_name: "Musike",- description: "Your music, uninterrupted.",- lang: "en",- theme_color: "#0B0C0F",- background_color: "#0B0C0F",- display: "standalone",- start_url: "/",- icons: [- { src: "icon-192.png", sizes: "192x192", type: "image/png" },- { src: "icon-512.png", sizes: "512x512", type: "image/png" },- { src: "icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },- ],- },- workbox: {- navigateFallbackDenylist: [/^\/api\//],- runtimeCaching: [- {- // Artwork only. Streams and API responses are never cached by the service worker.- urlPattern: ({ url }) => /(^|\.)ytimg\.com$|googleusercontent\.com$|ggpht\.com$/.test(url.hostname),- handler: "CacheFirst",- options: {- cacheName: "artwork",- expiration: { maxEntries: 600, maxAgeSeconds: 60 * 60 * 24 * 30 },- cacheableResponse: { statuses: [0, 200] },+/**+ * The Android build (`vite build --mode native`): the same app, with the backend swapped. lib/api.ts (HTTP to the+ * Musike server) becomes native/api.ts (the server's own code, running in the app), and the two server modules that+ * only make sense on a computer (paths/environment, yt-dlp) are replaced by small stand-ins.+ */+function nativeBackend(): Plugin {+ const swaps: [from: string, to: string][] = [+ [src("lib", "api.ts"), src("native", "api.ts")],+ [server("config.ts"), src("native", "shims", "config.ts")],+ [server("ytdlp.ts"), src("native", "shims", "ytdlp.ts")],+ ];+ return {+ name: "musike-native-backend",+ enforce: "pre",+ async resolveId(source, importer, options) {+ // No service worker inside the app: it would only risk serving an old version after an update.+ if (source === "virtual:pwa-register") return "\0musike-no-pwa";+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });+ if (!resolved) return null;+ const id = resolved.id.split("?")[0]!;+ for (const [from, to] of swaps) {+ // The replacement may import the original (native/api.ts re-exports lib/apiTypes, not lib/api).+ if (same(id, from) && !(importer && same(importer, to))) return to;+ }+ return null;+ },+ load(id) {+ if (id === "\0musike-no-pwa") return "export const registerSW = () => () => {};";+ return null;+ },+ };+}++export default defineConfig(({ mode }) => {+ const native = mode === "native";+ return {+ define: { __APP_VERSION__: JSON.stringify(version) },+ build: native ? { outDir: "dist-native", emptyOutDir: true } : undefined,+ plugins: [+ react(),+ tailwindcss(),+ native+ ? nativeBackend()+ : VitePWA({+ registerType: "autoUpdate",+ includeAssets: ["favicon.svg", "apple-touch-icon.png"],+ manifest: {+ name: "Musike",+ short_name: "Musike",+ description: "Your music, uninterrupted.",+ lang: "en",+ theme_color: "#0B0C0F",+ background_color: "#0B0C0F",+ display: "standalone",+ start_url: "/",+ icons: [+ { src: "icon-192.png", sizes: "192x192", type: "image/png" },+ { src: "icon-512.png", sizes: "512x512", type: "image/png" },+ { src: "icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },+ ],+ },+ workbox: {+ navigateFallbackDenylist: [/^\/api\//],+ runtimeCaching: [+ {+ // Artwork only. Streams and API responses are never cached by the service worker.+ urlPattern: ({ url }) => /(^|\.)ytimg\.com$|googleusercontent\.com$|ggpht\.com$/.test(url.hostname),+ handler: "CacheFirst",+ options: {+ cacheName: "artwork",+ expiration: { maxEntries: 600, maxAgeSeconds: 60 * 60 * 24 * 30 },+ cacheableResponse: { statuses: [0, 200] },+ },+ },+ ],},- },- ],- },- }),- ],- server: {- proxy: { "/api": "http://127.0.0.1:4180" },- },- preview: {- proxy: { "/api": "http://127.0.0.1:4180" },- },+ }),+ ],+ server: {+ proxy: native ? undefined : { "/api": "http://127.0.0.1:4180" },+ },+ preview: {+ proxy: native ? undefined : { "/api": "http://127.0.0.1:4180" },+ },+ };});