### Install and run the frontend dev server Source: https://github.com/ahnafnafee/songmirror/blob/main/frontend/README.md Install dependencies with pnpm and start the Vite dev server. Requires the FastAPI backend running on port 8080 (or set OMNI_BACKEND to a different backend). ```bash pnpm install --frozen-lockfile pnpm dev ``` -------------------------------- ### Install spotDL and ffmpeg Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Commands to install spotDL and ffmpeg, required for the local download mirror. Use uv tool install or pipx for spotDL, and winget or spotdl --download-ffmpeg for ffmpeg. ```bash uv tool install spotdl # isolated CLI; or: pipx install spotdl # ffmpeg required: winget install ffmpeg (or: spotdl --download-ffmpeg) ``` -------------------------------- ### Clone and start with Docker Compose Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Use for a durable installation. Clones the repository, pulls the image, starts the service, and shows status. Configuration is stored in ./data and downloads in ./downloads unless DOWNLOAD_DIR is set in .env. ```bash git clone https://github.com/ahnafnafee/songmirror.git cd songmirror docker compose pull docker compose up -d docker compose ps ``` -------------------------------- ### Start SongMirror with Docker Compose Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Pulls the published image and starts the container in the background. The web UI is available at http://:8888. Use 'docker compose logs -f' to watch the container's output. ```bash docker compose up -d # pull the published image + start in the background # open http://:8888 and connect your services + create syncs in the browser docker compose logs -f # watch it work ``` -------------------------------- ### Headless CLI setup and dry run Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Sets up the environment and runs a dry run that prints every add/remove it would perform without applying changes. ```bash uv sync cp .env.example .env # fill in credentials uv run main.py # dry run — prints every add/remove it *would* do uv run main.py --execute # apply for real ``` -------------------------------- ### GET /api/settings Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Reads the current sync options. ```APIDOC ## GET /api/settings ### Description Reads the current sync options. ### Method GET ### Endpoint /api/settings ### Response #### Success Response (200) - **settings** (object) - The current sync options. #### Response Example { "settings": { "interval": 3600, "execute": true } } ``` -------------------------------- ### Run without Docker using uv Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Runs SongMirror directly with uv and uvicorn, without Docker. Requires uv (Python 3.13+). For the local download mirror, also install spotdl via `uv tool install spotdl` and have ffmpeg on PATH. ```bash uv sync uv run uvicorn songmirror.web:app --host 0.0.0.0 --port 8080 # then open http://127.0.0.1:8080 ``` -------------------------------- ### Clone and run with Docker Compose Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Clones the repository and starts SongMirror with Docker Compose, pulling the published image and running syncs on schedule. Open http://localhost:8888 after startup. No .env file is needed; configuration is done in the UI and saved under ./data. ```bash git clone https://github.com/ahnafnafee/songmirror.git cd songmirror docker compose up -d ``` -------------------------------- ### Disposable smoke test Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Runs a temporary container without persistent volumes. Use only for testing; for real installations use the Compose setup. ```bash docker run --rm -p 8888:8080 ghcr.io/ahnafnafee/songmirror:latest ``` -------------------------------- ### GET /oauth/{id}/callback Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md OAuth redirect landing page for Spotify authentication. ```APIDOC ## GET /oauth/{id}/callback ### Description OAuth redirect landing page for Spotify authentication. ### Method GET ### Endpoint /oauth/{id}/callback ### Parameters #### Path Parameters - **id** (string) - Required - The OAuth provider identifier (e.g., 'spotify'). ``` -------------------------------- ### Verify ytmusicapi OAuth API Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Run this command to inspect the installed ytmusicapi device-OAuth API before implementing the connector. Confirm the code/token method names (e.g., get_code, token_from_code) before writing the connector. ```bash uv run python -c "from ytmusicapi.auth.oauth import OAuthCredentials; help(OAuthCredentials)" ``` -------------------------------- ### Local mirror directory layout Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Shows the Jellyfin-ready folder structure created by the local download mirror. Each synced playlist gets a folder with an auto-generated .m3u8 playlist, cover.jpg, and tagged audio files organized by album artist and album. ```text / / .m3u8 # auto-(re)generated; Jellyfin imports it as a playlist cover.jpg # the source playlist cover, highest resolution / / Artists - Title.mp3 # tagged + cover art embedded ``` -------------------------------- ### Run public GHCR image directly Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Runs the published SongMirror image from GHCR without cloning the repository. The container is disposable; use `docker stop songmirror` to remove it and its configuration. For a durable installation, use Docker Compose instead. ```bash docker run --rm -d --name songmirror -p 127.0.0.1:8888:8080 ghcr.io/ahnafnafee/songmirror:latest ``` -------------------------------- ### GET / Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Serves the dashboard page with status, last pass information, and quick actions. This is a server-rendered HTML page. ```APIDOC ## GET / ### Description Serves the dashboard page with status, last pass information, and quick actions. This is a server-rendered HTML page. ### Method GET ### Endpoint / ``` -------------------------------- ### POST /api/transfers Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Starts a one-off transfer job. ```APIDOC ## POST /api/transfers ### Description Starts a one-off transfer job. ### Method POST ### Endpoint /api/transfers ### Request Body - **source** (string) - Required - The source provider identifier. - **dest** (string) - Required - The destination provider identifier. - **playlist_id** (string) - Required - The playlist ID to transfer. ### Request Example { "source": "spotify", "dest": "youtube", "playlist_id": "playlist_id" } ``` -------------------------------- ### GET /events Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Server-Sent Events (SSE) live event stream for real-time updates. ```APIDOC ## GET /events ### Description Server-Sent Events (SSE) live event stream for real-time updates. ### Method GET ### Endpoint /events ``` -------------------------------- ### Verify provenance with gh attestation Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Verifies the GitHub artifact attestation for the image. Requires GitHub CLI installed and authenticated to GHCR. ```bash gh attestation verify \ oci://ghcr.io/ahnafnafee/songmirror:latest \ --repo ahnafnafee/songmirror \ --signer-workflow ahnafnafee/songmirror/.github/workflows/docker-publish.yml ``` -------------------------------- ### GET /api/accounts Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Returns a list of connectors along with their connection status (ConnStatus). ```APIDOC ## GET /api/accounts ### Description Returns a list of connectors along with their connection status (ConnStatus). ### Method GET ### Endpoint /api/accounts ### Response #### Success Response (200) - **connectors** (array) - List of connectors with their status. #### Response Example { "connectors": [ { "id": "spotify", "status": "connected" } ] } ``` -------------------------------- ### GET /api/playlists?provider= Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Browses playlists from a specific provider. ```APIDOC ## GET /api/playlists?provider= ### Description Browses playlists from a specific provider. ### Method GET ### Endpoint /api/playlists ### Parameters #### Query Parameters - **provider** (string) - Required - The provider identifier (e.g., 'spotify', 'youtube'). ### Response #### Success Response (200) - **playlists** (array) - List of playlists from the provider. #### Response Example { "playlists": [ { "id": "playlist_id", "name": "My Playlist" } ] } ``` -------------------------------- ### GET /api/links Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Reads the current pairing links. ```APIDOC ## GET /api/links ### Description Reads the current pairing links. ### Method GET ### Endpoint /api/links ### Response #### Success Response (200) - **links** (array) - List of pairing links. #### Response Example { "links": [ { "id": "link_id", "source": "spotify", "dest": "youtube" } ] } ``` -------------------------------- ### GET /api/transfers/{id} Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Gets the status of a transfer job and its conflict queue. ```APIDOC ## GET /api/transfers/{id} ### Description Gets the status of a transfer job and its conflict queue. ### Method GET ### Endpoint /api/transfers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The transfer job identifier. ### Response #### Success Response (200) - **status** (string) - The current status of the job. - **conflicts** (array) - List of conflicts in the queue. #### Response Example { "status": "running", "conflicts": [ { "track": "Song Name", "status": "not_found" } ] } ``` -------------------------------- ### Get rootlist revision (spclient) - Step 6b Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Fetches the rootlist for the user to obtain the current revision, which is required for the subsequent change operation (6c). Replace USER_ID with the user's ID. ```bash # 6b. get the rootlist revision (need it for 6c) curl 'https://spclient.wg.spotify.com/playlist/v2/user/USER_ID/rootlist' \ -H 'Authorization: Bearer {{bearer}}' \ -H 'Accept: application/json' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0' ``` -------------------------------- ### GET /api/sync/status Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Returns the current sync status, including whether a sync is running, the next run time, and the last summary. ```APIDOC ## GET /api/sync/status ### Description Returns the current sync status, including whether a sync is running, the next run time, and the last summary. ### Method GET ### Endpoint /api/sync/status ### Response #### Success Response (200) - **running** (boolean) - Whether a sync is currently running. - **next_run** (string) - The next scheduled run time. - **last_summary** (object) - The summary of the last sync pass. #### Response Example { "running": false, "next_run": "2026-07-12T12:00:00Z", "last_summary": { "added": 10, "removed": 2 } } ``` -------------------------------- ### GET /playlist/v2/user/{user_id}/rootlist Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Retrieves the rootlist revision for the user. This revision is required to add the new playlist to the library. ```APIDOC ## [GET] /playlist/v2/user/{user_id}/rootlist ### Description Retrieves the rootlist revision for the user. This revision is required to add the new playlist to the library. ### Method GET ### Endpoint https://spclient.wg.spotify.com/playlist/v2/user/{user_id}/rootlist ### Parameters #### Path Parameters - **user_id** (string) - Required - The user's Spotify ID. ### Response #### Success Response (200) - **revision** (string) - The current revision of the rootlist. #### Response Example { "revision": "REVISION_FROM_6b" } ``` -------------------------------- ### GET /v1/tracks Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Batch lookup of up to 50 tracks by ISRC or track ID. Requires an extended-quota app token; dev-mode apps receive 403. ```APIDOC ## [GET] /v1/tracks ### Description Batch lookup of up to 50 tracks by ISRC or track ID. Requires an extended-quota app token; dev-mode apps receive 403. ### Method GET ### Endpoint https://api.spotify.com/v1/tracks ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of track IDs or ISRCs (up to 50) #### Headers - **Authorization** (string) - Required - Bearer token from the token endpoint ### Request Example ``` curl 'https://api.spotify.com/v1/tracks?ids=6pHtgTMzsmP6ccN2ocv7XN,72Q62UFNdzIQj04Y4bwKv3' \ -H 'Authorization: Bearer APP_TOKEN' ``` ### Response #### Success Response (200) - **external_ids.isrc** (string) - The ISRC code for each track #### Response Example ``` {"tracks": [{"external_ids": {"isrc": "USUM71703861"}}]} ``` #### Error Responses - **403 Forbidden** - Dev-mode app token or OAuth user token used - **429 Too Many Requests** - Rate limit exceeded; check `Retry-After` header ``` -------------------------------- ### GET /api/server-time Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Fetches the current server time from Spotify's open.spotify.com endpoint. This is the first step in the TOTP handshake to mint a Bearer token. ```APIDOC ## GET /api/server-time ### Description Fetches the current server time from Spotify's open.spotify.com endpoint. This is the first step in the TOTP handshake to mint a Bearer token. ### Method GET ### Endpoint https://open.spotify.com/api/server-time ### Parameters #### Headers - **User-Agent** (string) - Required - A common User-Agent string (e.g., `Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0`) - **Cookie** (string) - Required - `sp_dc={{sp_dc}}` ### Response #### Success Response (200) - **serverTime** (number) - The current server time in Unix epoch seconds. #### Response Example ```json {"serverTime": 1721000000} ``` ``` -------------------------------- ### Get client token for spclient calls Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md POST to clienttoken.spotify.com to obtain a client token. The response contains a granted_token.token value that must be sent as the `client-token:` header on spclient calls. Uses {{appver}} placeholder for the app version. ```bash curl 'https://clienttoken.spotify.com/v1/clienttoken' -X POST \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0' \ --data-raw '{"client_data":{"client_version":"{{appver}}","client_id":"d8a5ed958d274c2e8ee717e6a4b0971d","js_sdk_data":{"device_brand":"unknown","device_model":"unknown","os":"windows","os_version":"NT 10.0","device_id":"00000000000000000000000000000000","device_type":"computer"}}}' # -> .granted_token.token (send as the `client-token:` header on spclient calls) ``` -------------------------------- ### GET /v1/tracks/{id} Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Single track lookup by ISRC or track ID. Works with dev-mode app tokens but is rate-limited to ~300 calls per 24 hours. ```APIDOC ## [GET] /v1/tracks/{id} ### Description Single track lookup by ISRC or track ID. Works with dev-mode app tokens but is rate-limited to ~300 calls per 24 hours. ### Method GET ### Endpoint https://api.spotify.com/v1/tracks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Track ID or ISRC #### Headers - **Authorization** (string) - Required - Bearer token from the token endpoint ### Request Example ``` curl 'https://api.spotify.com/v1/tracks/6pHtgTMzsmP6ccN2ocv7XN' -H 'Authorization: Bearer APP_TOKEN' ``` ### Response #### Success Response (200) - **external_ids.isrc** (string) - The ISRC code for the track #### Response Example ``` {"external_ids": {"isrc": "USUM71703861"}} ``` #### Error Responses - **429 Too Many Requests** - Rate limit exceeded; check `Retry-After` header ``` -------------------------------- ### GET /api/token Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Mints a Bearer token using two time-based TOTP codes computed from a rotating secret. This is the second step of the handshake and requires a pre-request script to compute the TOTP code. ```APIDOC ## GET /api/token ### Description Mints a Bearer token using two time-based TOTP codes computed from a rotating secret. This is the second step of the handshake and requires a pre-request script to compute the TOTP code. ### Method GET ### Endpoint https://open.spotify.com/api/token?reason=init&productType=web-player&totp={{totp}}&totpServer={{totp}}&totpVer=61 ### Parameters #### Query Parameters - **reason** (string) - Required - Set to `init` - **productType** (string) - Required - Set to `web-player` - **totp** (string) - Required - The TOTP code computed from the secret - **totpServer** (string) - Required - The TOTP code computed from the server time (can be the same as `totp` if clock is within ~15s) - **totpVer** (string) - Required - The TOTP secret version (currently `61`) #### Headers - **User-Agent** (string) - Required - A common User-Agent string (e.g., `Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0`) - **Cookie** (string) - Required - `sp_dc={{sp_dc}}` ### Response #### Success Response (200) - **accessToken** (string) - The Bearer token - **accessTokenExpirationTimestampMs** (number) - Expiration timestamp in milliseconds - **isAnonymous** (boolean) - Whether the token is anonymous #### Response Example ```json {"accessToken":"BQ...","accessTokenExpirationTimestampMs":...,"isAnonymous":false} ``` ``` -------------------------------- ### Run test suite and build frontend Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-09-18-lastfm-source-and-local-flac-mirror.md Commands to run the test suite and build the frontend as required by the provider gates. ```bash .venv/Scripts/python.exe -m pytest tests/ -q ``` ```bash pnpm -C frontend build ``` -------------------------------- ### Implement targets.build_one in targets/__init__.py Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase2.md Constructs a single provider by id from the registry, returning None if unknown or unconfigured. Add "build_one" to __all__ after implementation. ```python def build_one(provider_id, opts, sp=None): """Construct a single provider by id (None if unknown/unconfigured).""" builder = _REGISTRY.get(provider_id) return builder(opts, sp) if builder else None ``` -------------------------------- ### Frontend validation and build commands Source: https://github.com/ahnafnafee/songmirror/blob/main/frontend/README.md Run linting, i18n checks, production build, and end-to-end tests. The e2e tests intercept backend requests and run against the production bundle; they do not connect to music services or modify real playlists. ```bash pnpm lint pnpm i18n:check pnpm build pnpm test:e2e ``` -------------------------------- ### Build from checked-out source Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Builds the image from the local source instead of pulling from GHCR. Requires SONGMIRROR_IMAGE to be unset. ```bash docker compose up -d --build ``` -------------------------------- ### Roll back to previous digest Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Recreates the service using a previously working digest set in .env and follows logs. Note that rolling back does not roll back ./data. ```bash docker compose up -d --pull always --force-recreate docker compose logs -f ``` -------------------------------- ### POST /api/sync/run Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Runs a sync pass now. The `execute` query parameter controls whether the pass is executed or just simulated. ```APIDOC ## POST /api/sync/run ### Description Runs a sync pass now. The `execute` query parameter controls whether the pass is executed or just simulated. ### Method POST ### Endpoint /api/sync/run ### Parameters #### Query Parameters - **execute** (integer) - Optional - Set to 1 to execute the pass, 0 to simulate. Default is 0. ### Request Example POST /api/sync/run?execute=1 ``` -------------------------------- ### Configure Spotify OAuth via .env Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Sets the browser-visible base URL and Spotify OAuth credentials for the legacy developer-app fallback. Required when using OAuth behind Docker or a reverse proxy. Register the exact callback URI in the Spotify app dashboard. ```dotenv SPOTIFY_AUTH_MODE=oauth SPOTIFY_CLIENT_ID=your-client-id SPOTIFY_CLIENT_SECRET=your-client-secret SONGMIRROR_PUBLIC_URL=https://music.example.com ``` -------------------------------- ### Minimal FastAPI app factory with health check Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Initial implementation of create_app() that returns a FastAPI instance with a /health route returning {"ok": true}. This makes the failing test pass. ```python from fastapi import FastAPI def create_app() -> FastAPI: app = FastAPI(title="Omni Playlist Sync") @app.get("/health") def health(): return {"ok": True} return app app = create_app() ``` -------------------------------- ### Headless CLI useful flags Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Shows common CLI flags for filtering playlists, looping, limiting removals, and configuring sync mode/source/authorities/providers. ```bash uv run main.py --execute --playlists "Aurora,Chill" # only these pairs uv run main.py --execute --loop --interval 15m # run forever uv run main.py --execute --max-removals 100 # one-off larger cleanup uv run main.py --execute --sync-mode group --sync-source spotify \ --authorities spotify,apple --providers spotify,apple,tidal,ytmusic ``` -------------------------------- ### Follow newest default-branch image Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Pulls the latest image and follows logs. Use to stay on the newest default-branch build. ```bash docker compose up -d --pull always docker compose logs -f ``` -------------------------------- ### Implementation: Event dataclass, set_sink, and _emit in logs.py Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Adds the Event dataclass, a module-level sink, set_sink, and _emit helper. A broken sink must never break a sync; exceptions are swallowed. ```python import time as _time from dataclasses import dataclass @dataclass(frozen=True) class Event: ts: float; kind: str; tag: str; message: str; data: dict | None = None _sink = None def set_sink(fn): global _sink _sink = fn def _emit(kind, message, tag): fn = _sink if fn is not None: try: fn(Event(_time.time(), kind, tag or "", message, None)) except Exception: pass # a broken sink must never break a sync ``` -------------------------------- ### PUT /api/settings Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Updates the sync options. ```APIDOC ## PUT /api/settings ### Description Updates the sync options. ### Method PUT ### Endpoint /api/settings ### Request Body - **interval** (integer) - Optional - The sync interval in seconds. - **execute** (boolean) - Optional - Whether to execute the sync. ### Request Example { "interval": 3600, "execute": true } ``` -------------------------------- ### File playlist into library (spclient) - Step 6c Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Adds the newly created playlist to the user's library rootlist using the baseRevision obtained in step 6b. The playlist URI from step 6a is used in the add item. Replace REVISION_FROM_6b and spotify:playlist:NEW with actual values. ```bash # 6c. file the new playlist into the library (addFirst) curl 'https://spclient.wg.spotify.com/playlist/v2/user/USER_ID/rootlist/changes' -X POST \ -H 'Authorization: Bearer {{bearer}}' \ -H 'Content-Type: application/json;charset=UTF-8' \ -H 'Accept: application/json' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0' \ --data-raw '{"baseRevision":"REVISION_FROM_6b","deltas":[{"ops":[{"kind":2,"add":{"items":[{"uri":"spotify:playlist:NEW"}],"addFirst":true}}]}],"wantResultingRevisions":false,"wantSyncResult":false,"nonces":[]}' ``` -------------------------------- ### Recreate service with pinned digest Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Recreates the service using the digest set in .env. Do not use with --build because a local build needs a taggable image name. ```bash docker compose up -d --pull always --force-recreate ``` -------------------------------- ### Create a playlist (spclient) - Step 6a: create orphaned playlist Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Creates a new playlist via spclient. The response contains a URI like "spotify:playlist:NEW" that is used in subsequent steps. Requires a valid bearer token. ```bash # 6a. create — returns {"uri":"spotify:playlist:NEW"} curl 'https://spclient.wg.spotify.com/playlist/v2/playlist' -X POST \ -H 'Authorization: Bearer {{bearer}}' \ -H 'Content-Type: application/json;charset=UTF-8' \ -H 'Accept: application/json' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0' \ --data-raw '{"ops":[{"kind":6,"updateListAttributes":{"newAttributes":{"values":{"name":"My New Playlist","formatAttributes":[],"pictureSize":[]},"noValue":[]}}}]}' ``` -------------------------------- ### Headless CLI loop command Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Runs the headless CLI loop for non-web users, as an alternative to the web GUI. ```bash python -m omni_sync --loop ``` -------------------------------- ### 项目目录结构 Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/i18n/README.zh.md 展示 SongMirror 项目的顶层目录布局,包括 engine、services、web 和 frontend 目录及其职责。 ```text songmirror/ engine/ # provider-agnostic sync core (no web deps): runner, matching, targets/, spotify, downloads, archive services/ # stateful services over the engine: accounts/ connectors, syncs, sync_service, transfers, playlists, settings web/ # FastAPI app: thin HTTP/SSE over services/ (routers/) frontend/ # React + Vite SPA (built and served by the API in production) ``` -------------------------------- ### POST /api/accounts/{id}/connect Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Begins the connection flow for a specific account connector, which may involve redirect, device, or paste methods. ```APIDOC ## POST /api/accounts/{id}/connect ### Description Begins the connection flow for a specific account connector, which may involve redirect, device, or paste methods. ### Method POST ### Endpoint /api/accounts/{id}/connect ### Parameters #### Path Parameters - **id** (string) - Required - The account connector identifier. ``` -------------------------------- ### Test settings store clobber regression and roundtrip Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Failing tests for SettingsStore: verifies saved credentials survive a dotenv reload with override, and that save/load roundtrips values. Run with `uv run pytest test_settings.py -v` after implementing settings.py. ```python import os from dotenv import load_dotenv from omni_sync.settings import SettingsStore def test_saved_credential_survives_dotenv_reload(tmp_path): store = SettingsStore(dir=tmp_path) store.save({"APPLE_BEARER_TOKEN": "NEW"}) # simulate a stale hand-edited file existing elsewhere; engine loads the MANAGED file load_dotenv(store.env_path, override=True) assert os.environ["APPLE_BEARER_TOKEN"] == "NEW" def test_roundtrip(tmp_path): store = SettingsStore(dir=tmp_path) store.save({"SYNC_INTERVAL": "30m", "SPOTIFY_CLIENT_ID": "abc"}) assert store.load()["SYNC_INTERVAL"] == "30m" ``` -------------------------------- ### Inspect tag for multi-platform digest Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Shows the multi-platform digest for the latest tag. Use the digest from the output for repeatable deployments. ```bash docker buildx imagetools inspect ghcr.io/ahnafnafee/songmirror:latest ``` -------------------------------- ### React component using useTranslation and t() Source: https://github.com/ahnafnafee/songmirror/blob/main/frontend/README.md Subscribe to translations in every component that renders translated text. Use complete English sentences as keys so translators can reorder variables. ```tsx import { t, useTranslation } from '@/i18n' function Greeting({ name }: { name: string }) { useTranslation() return

{t('Hello, {{name}}', { name })}

} ``` -------------------------------- ### Dockerfile CMD for uvicorn Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Sets the container command to run the FastAPI app with uvicorn, binding to all interfaces on port 8080 for LAN access. ```dockerfile uvicorn omni_sync.web:app --host 0.0.0.0 --port 8080 ``` -------------------------------- ### Mint app token and query /tracks for ISRC Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Use an EXTENDED-QUOTA app's client credentials to mint an app token (no cookie/TOTP), then batch-query up to 50 track IDs in one call. A dev-mode app returns 403 on the batch endpoint; single-track queries work on dev-mode apps but cap around 300 calls/24h. ```bash # 2a. mint an app token (no cookie/TOTP) — use an EXTENDED-QUOTA app's creds curl -s -X POST 'https://accounts.spotify.com/api/token' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET' # -> {"access_token":"BQ...","expires_in":3600} ``` ```bash # 2b. BATCH, up to 50 ids in ONE call (needs an extended-quota app; a dev-mode app 403s here) curl 'https://api.spotify.com/v1/tracks?ids=6pHtgTMzsmP6ccN2ocv7XN,72Q62UFNdzIQj04Y4bwKv3' \ -H 'Authorization: Bearer APP_TOKEN' ``` ```bash # single track (works on dev-mode apps too, but caps ~300 calls/24h) curl 'https://api.spotify.com/v1/tracks/6pHtgTMzsmP6ccN2ocv7XN' -H 'Authorization: Bearer APP_TOKEN' ``` -------------------------------- ### Query song archive with sqlite3 Source: https://github.com/ahnafnafee/songmirror/blob/main/README.md Query the song_cache.db SQLite file to list the most recently seen songs, ordered by first_seen descending. Useful for inspecting the archive of tracks that only grows over time. ```bash sqlite3 song_cache.db "SELECT name, artist, album, first_seen FROM songs ORDER BY first_seen DESC LIMIT 20" ``` -------------------------------- ### Test Apple connector status and token submission Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Failing test for Apple connector: verifies unconfigured status and that submitting tokens stores them and returns connected state. Uses monkeypatch to skip network validation. ```python from omni_sync.settings import SettingsStore from omni_sync.accounts import CONNECTORS def test_apple_status_unconfigured(tmp_path): store = SettingsStore(dir=tmp_path) c = CONNECTORS["apple"](store) assert c.status().state == "unconfigured" def test_apple_submit_stores_tokens(tmp_path, monkeypatch): store = SettingsStore(dir=tmp_path) c = CONNECTORS["apple"](store) monkeypatch.setattr(c, "_validate", lambda: True) # skip network st = c.submit({"APPLE_BEARER_TOKEN": "b", "APPLE_USER_TOKEN": "u"}) assert st.state == "connected" and store.get("APPLE_USER_TOKEN") == "u" ``` -------------------------------- ### Pre-request Script for TOTP computation Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Computes the TOTP code for the token mint. Uses secret version 61. Sets {{totp}} collection variable. Must be run before the token request. ```javascript // Spotify TOTP, secret version 61 (newest) const secret = ',7/*F("rLJ2oxaKL^f+E1xvP@N'; let keyStr = ""; for (let i = 0; i < secret.length; i++) keyStr += (secret.charCodeAt(i) ^ (i % 33 + 9)).toString(); const counter = Math.floor(Math.floor(Date.now() / 1000) / 30); const counterHex = counter.toString(16).padStart(16, '0'); const hmacHex = CryptoJS.HmacSHA1(CryptoJS.enc.Hex.parse(counterHex), CryptoJS.enc.Utf8.parse(keyStr)).toString(CryptoJS.enc.Hex); const offset = parseInt(hmacHex.slice(-1), 16); const code = parseInt(hmacHex.substr(offset * 2, 8), 16) & 0x7fffffff; pm.collectionVariables.set("totp", (code % 1000000).toString().padStart(6, '0')); ``` -------------------------------- ### POST /api/accounts/{id}/config Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Saves application credentials for a specific account connector. ```APIDOC ## POST /api/accounts/{id}/config ### Description Saves application credentials for a specific account connector. ### Method POST ### Endpoint /api/accounts/{id}/config ### Parameters #### Path Parameters - **id** (string) - Required - The account connector identifier. #### Request Body - **client_id** (string) - Required - The client ID for the connector. - **client_secret** (string) - Required - The client secret for the connector. ### Request Example { "client_id": "your_client_id", "client_secret": "your_client_secret" } ``` -------------------------------- ### POST /playlist/v2/playlist Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Creates a new playlist. The response contains the URI of the newly created playlist, which is used in subsequent steps to add it to the library. ```APIDOC ## [POST] /playlist/v2/playlist ### Description Creates a new playlist. The response contains the URI of the newly created playlist, which is used in subsequent steps to add it to the library. ### Method POST ### Endpoint https://spclient.wg.spotify.com/playlist/v2/playlist ### Parameters #### Request Body - **ops** (array) - Required - List of operations. - **kind** (integer) - Required - Operation kind (6 for update attributes). - **updateListAttributes** (object) - Required - Attributes to update. - **newAttributes** (object) - Required - New attribute values. - **values** (object) - Required - Attribute values. - **name** (string) - Required - Playlist name. - **formatAttributes** (array) - Required - Format attributes. - **pictureSize** (array) - Required - Picture size. - **noValue** (array) - Required - No value. ### Request Example { "ops": [ { "kind": 6, "updateListAttributes": { "newAttributes": { "values": { "name": "My New Playlist", "formatAttributes": [], "pictureSize": [] }, "noValue": [] } } } ] } ### Response #### Success Response (200) - **uri** (string) - The URI of the created playlist. #### Response Example { "uri": "spotify:playlist:NEW" } ``` -------------------------------- ### Test: sink receives typed events and noop sink Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Failing test for the new logs sink. Verifies that set_sink receives typed events with kind and tag, and that setting sink to None is a noop. ```python from omni_sync import logs def test_sink_receives_typed_events(): seen = [] logs.set_sink(seen.append) try: logs.log_add("X - Y", tag="apple") logs.log_remove("A - B", tag="yt") finally: logs.set_sink(None) kinds = [(e.kind, e.tag) for e in seen] assert ("add", "apple") in kinds and ("remove", "yt") in kinds def test_sink_none_is_noop(): logs.set_sink(None) logs.log_note("hi") # must not raise ``` -------------------------------- ### Implement EventBus with loop-safe publish Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Provides a thread-safe EventBus that bridges worker threads to the asyncio loop via call_soon_threadsafe. Maintains a ring buffer of recent events and supports subscribe/unsubscribe, with attach_to_logs() registering a sink that publishes. ```python import asyncio from collections import deque from .logs import Event, set_sink class EventBus: def __init__(self, ring: int = 500): self._loop = None self._subs: set[asyncio.Queue] = set() self._ring: deque[Event] = deque(maxlen=ring) def bind_loop(self, loop): self._loop = loop def subscribe(self) -> asyncio.Queue: q: asyncio.Queue = asyncio.Queue(); self._subs.add(q); return q def unsubscribe(self, q): self._subs.discard(q) def recent(self): return list(self._ring) def publish(self, e: Event): # Called from arbitrary worker threads; asyncio.Queue is not thread-safe. if self._loop is None: return self._loop.call_soon_threadsafe(self._deliver, e) def _deliver(self, e: Event): self._ring.append(e) for q in self._subs: try: q.put_nowait(e) except asyncio.QueueFull: pass def attach_to_logs(self): set_sink(self.publish) ``` -------------------------------- ### Test health endpoint with FastAPI TestClient Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Failing test for the /health endpoint. Expects status 200 and JSON body {"ok": true}. ```python from fastapi.testclient import TestClient from omni_sync.web import create_app def test_health(): client = TestClient(create_app()) r = client.get("/health") assert r.status_code == 200 and r.json() == {"ok": True} ``` -------------------------------- ### Test for SyncService serialization and coalescing Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase1.md Failing test that verifies overlapping run_now calls are coalesced, ensuring only one pass executes at a time. Uses a fake run_pass that sleeps to simulate concurrent calls. ```python import asyncio from omni_sync.sync_service import SyncService def test_run_now_serializes(monkeypatch, tmp_path): calls = [] async def scenario(): import omni_sync.sync_service as m async def fake_pass(opts): calls.append("start"); await asyncio.sleep(0.05); calls.append("end") monkeypatch.setattr(m, "_run_pass_async", fake_pass) from omni_sync.settings import SettingsStore from omni_sync.events import EventBus bus = EventBus(); bus.bind_loop(asyncio.get_running_loop()) svc = SyncService(SettingsStore(dir=tmp_path), bus) await asyncio.gather(svc.run_now(False), svc.run_now(False)) asyncio.run(scenario()) # second overlapping call coalesced → not start,start,end,end assert calls == ["start", "end"] ``` -------------------------------- ### Failing test for targets.build_one Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/plans/2026-07-13-web-gui-phase2.md Test that build_one returns None for an unknown provider. Used as the first step of Task 1 to drive implementation. ```python from omni_sync import targets from omni_sync.config import parse_args def test_build_one_unknown_returns_none(): assert targets.build_one("nope", parse_args([])) is None ``` -------------------------------- ### POST /api/sync/schedule Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Pauses, resumes, or changes the sync interval. ```APIDOC ## POST /api/sync/schedule ### Description Pauses, resumes, or changes the sync interval. ### Method POST ### Endpoint /api/sync/schedule ### Request Body - **action** (string) - Required - The action to perform: 'pause', 'resume', or 'interval'. - **interval** (integer) - Optional - The new interval in seconds (required if action is 'interval'). ### Request Example { "action": "interval", "interval": 3600 } ``` -------------------------------- ### Pull and inspect image directly Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/docker-image.md Pulls the image and inspects it without Compose. Useful for direct access. ```bash docker pull ghcr.io/ahnafnafee/songmirror:latest docker image inspect ghcr.io/ahnafnafee/songmirror:latest ``` -------------------------------- ### POST /pathfinder/v2/query — fetchPlaylistContents Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Reads the contents of a Spotify playlist. Returns track metadata including the track `uid` needed for removals. This endpoint does not return ISRC. ```APIDOC ## [POST] /pathfinder/v2/query ### Description Reads the contents of a Spotify playlist. Returns track metadata including the track `uid` needed for removals. This endpoint does not return ISRC. ### Method POST ### Endpoint https://api-partner.spotify.com/pathfinder/v2/query ### Parameters #### Request Body - **variables** (object) - Required - Contains the query variables. - **uri** (string) - Required - The Spotify playlist URI (e.g., `spotify:playlist:PLAYLIST_ID`). - **offset** (integer) - Required - The offset for pagination. - **limit** (integer) - Required - The maximum number of items to return. - **operationName** (string) - Required - The operation name, set to `fetchPlaylistContents`. - **extensions** (object) - Required - Contains the persisted query information. - **persistedQuery** (object) - Required - The persisted query details. - **version** (integer) - Required - The version, set to `1`. - **sha256Hash** (string) - Required - The SHA256 hash of the persisted query. ### Request Example ```json { "variables": { "uri": "spotify:playlist:PLAYLIST_ID", "offset": 0, "limit": 100 }, "operationName": "fetchPlaylistContents", "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "a65e12194ed5fc443a1cdebed5fabe33ca5b07b987185d63c72483867ad13cb4" } } } ``` ### Response #### Success Response (200) - Returns the playlist contents including track metadata and `uid` for each track. #### Response Example (Not provided in source) ``` -------------------------------- ### 1a. Server time (no auth) - curl Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Fetches server time from Spotify's open.spotify.com endpoint. No authentication required. Returns JSON with serverTime. ```bash curl 'https://open.spotify.com/api/server-time' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0' \ -H 'Cookie: sp_dc={{sp_dc}}' # -> {"serverTime": 1721000000} ``` -------------------------------- ### PassSummary structure for unified sync results Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/design/2026-07-12-web-gui-architecture.md Defines the PassSummary dictionary shape to unify aggregates across one-way, N-way, and refresh_local sync paths. The N-way path must accumulate per-peer stats from each reconcile call. ```python PassSummary = { pass_id, mode, started, duration_s, execute, ok, error, per_target: [ {name, added, removed, missing, held, deferred, created, skipped} ] } ``` -------------------------------- ### Common User-Agent header value Source: https://github.com/ahnafnafee/songmirror/blob/main/docs/spotify-web-postman.md Required on every call to avoid Spotify's edge 403 for default python-requests or bare-curl user agents. ```text Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/152.0 ```