diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..ddd7723 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,95 @@ +name: Bug report +description: Something in Flow is broken or behaves unexpectedly +title: "[Bug]: " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to report this. Please fill in as much as you can. + For security problems, do not use this form. See the security policy instead. + - type: textarea + id: what-happened + attributes: + label: What happened? + description: Describe the problem and what you expected to happen instead. + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: The exact commands or clicks that trigger the problem. + placeholder: | + 1. Run `flow -pl "..."` + 2. ... + validations: + required: true + - type: dropdown + id: interface + attributes: + label: Interface + description: Where did you see the problem? + options: + - flow (interactive shell or flags) + - flow-tui + - flow-web + - flow-min + - A plugin + - Not sure + validations: + required: true + - type: dropdown + id: mode + attributes: + label: Mode + options: + - Online + - Offline + - Both + - Not sure + validations: + required: true + - type: input + id: version + attributes: + label: Flow version + description: For example `0.8.4`. Run `pip show flow-twinx`, or give the commit if you run from source. + validations: + required: true + - type: input + id: os + attributes: + label: Operating system + placeholder: e.g. Arch Linux, Ubuntu 24.04, macOS 15 + validations: + required: true + - type: input + id: python + attributes: + label: Python version + description: Output of `python --version`. + validations: + required: true + - type: textarea + id: check + attributes: + label: Output of `flow --check` + render: shell + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs or screenshots + description: Run `config dev true` inside Flow to get more detail. Paste any error output here. + render: shell + - type: checkboxes + id: confirm + attributes: + label: Before submitting + options: + - label: I searched the existing issues and did not find this one. + required: true + - label: This is not a security vulnerability. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..847eb38 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/flow-twinx/flow/security/policy + about: Please report security problems privately, not in a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..bdd1d34 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,45 @@ +name: Feature request +description: Suggest an idea or an improvement for Flow +title: "[Feature]: " +labels: ["enhancement"] +body: + - type: textarea + id: problem + attributes: + label: What problem are you trying to solve? + description: Describe what you want to do and what gets in the way today. + validations: + required: true + - type: textarea + id: solution + attributes: + label: What would you like to see? + description: Describe the change you have in mind. Sketches of commands, flags or screens are welcome. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives you considered + description: Other ways to solve it, including a plugin or a script around `flow-min`. + - type: dropdown + id: interface + attributes: + label: Which interface is this for? + multiple: true + options: + - flow (interactive shell or flags) + - flow-tui + - flow-web + - flow-min + - Plugin API + - All of them + - type: checkboxes + id: confirm + attributes: + label: Before submitting + options: + - label: I searched the existing issues and did not find this request. + required: true + - label: I would be willing to help build this. + required: false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6211d4b --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,15 @@ +## What does this change? + + + +## How was it tested? + + + +## Checklist + +- [ ] `uv run pytest` passes +- [ ] I added or updated tests for this change +- [ ] I updated the docs in `docs/` if behaviour, commands, flags or file formats changed +- [ ] The change respects the module boundaries (backend owns logic; front ends stay thin) +- [ ] Nothing here touches the real `~/.flow/` from tests diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..95c0982 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,67 @@ +name: CI + +on: + push: + branches: [beta, main] + pull_request: + +jobs: + test: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.12.x" + enable-cache: true + cache-dependency-glob: "uv.lock" + + - name: Install system deps (Linux) + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y \ + vlc \ + libgirepository-2.0-dev \ + libcairo2-dev \ + gobject-introspection \ + libdbus-1-dev \ + libportaudio2 + + - name: Install VLC (macOS) + if: runner.os == 'macOS' + run: | + brew install --cask vlc + echo "VLC_PLUGIN_PATH=/Applications/VLC.app/Contents/MacOS/plugins" >> "$GITHUB_ENV" + + - name: Install VLC (Windows, portable) + if: runner.os == 'Windows' + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $vlcZip = "$env:RUNNER_TEMP\vlc.zip" + $vlcDir = "$env:RUNNER_TEMP\vlc" + curl.exe -L --fail --retry 3 -o $vlcZip "https://get.videolan.org/vlc/3.0.21/win64/vlc-3.0.21-win64.zip" + New-Item -ItemType Directory -Force -Path $vlcDir | Out-Null + tar.exe -xf $vlcZip -C $vlcDir + $vlcRoot = (Get-ChildItem $vlcDir -Directory | Select-Object -First 1).FullName + "PYTHON_VLC_LIB_PATH=$vlcRoot\libvlc.dll" | Out-File -FilePath $env:GITHUB_ENV -Append + "VLC_PLUGIN_PATH=$vlcRoot\plugins" | Out-File -FilePath $env:GITHUB_ENV -Append + + - name: Sync project + run: uv sync --group dev + + - name: Smoke test (libvlc, a real Instance, entry-point imports) + run: | + uv run python -c "import vlc; vlc.Instance('--no-video --quiet'); print('libvlc:', vlc.libvlc_get_version())" + uv run python -c "import cli.main, minimal.main, tui.main, web.main; print('all entry points import ok')" + + - name: Run tests + run: uv run pytest -q \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ab2f000 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,96 @@ +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + build: + name: build (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + spec: packaging/flow.linux.spec + artifact: flow-linux + binary: dist/flow + - os: macos-latest + spec: packaging/flow.macos.spec + artifact: flow-macos + binary: dist/flow + - os: windows-latest + spec: packaging/flow.windows.spec + artifact: flow-windows.exe + binary: dist/flow.exe + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.12.x" + enable-cache: true + cache-dependency-glob: "uv.lock" + + - name: Install system deps (Linux) + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y \ + vlc \ + libgirepository-2.0-dev \ + libcairo2-dev \ + gobject-introspection \ + libdbus-1-dev \ + libportaudio2 + + - name: Install VLC (macOS) + if: runner.os == 'macOS' + run: | + brew install --cask vlc + echo "VLC_PLUGIN_PATH=/Applications/VLC.app/Contents/MacOS/plugins" >> "$GITHUB_ENV" + + - name: Install VLC (Windows, portable) + if: runner.os == 'Windows' + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $vlcZip = "$env:RUNNER_TEMP\vlc.zip" + $vlcDir = "$env:RUNNER_TEMP\vlc" + curl.exe -L --fail --retry 3 -o $vlcZip "https://get.videolan.org/vlc/3.0.21/win64/vlc-3.0.21-win64.zip" + New-Item -ItemType Directory -Force -Path $vlcDir | Out-Null + tar.exe -xf $vlcZip -C $vlcDir + $vlcRoot = (Get-ChildItem $vlcDir -Directory | Select-Object -First 1).FullName + "PYTHON_VLC_LIB_PATH=$vlcRoot\libvlc.dll" | Out-File -FilePath $env:GITHUB_ENV -Append + "VLC_PLUGIN_PATH=$vlcRoot\plugins" | Out-File -FilePath $env:GITHUB_ENV -Append + + - name: Sync project + run: uv sync --group dev + + - name: Build onefile binary + run: uv run pyinstaller --noconfirm --clean ${{ matrix.spec }} + + - name: Smoke test the binary + run: | + ${{ matrix.binary }} --check + ${{ matrix.binary }} --status + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: ${{ matrix.binary }} + + - name: Stage release asset with OS-specific name + run: cp "${{ matrix.binary }}" "dist/${{ matrix.artifact }}" + + - name: Attach to GitHub Release + uses: softprops/action-gh-release@v2 + with: + files: dist/${{ matrix.artifact }} + overwrite_files: true \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a13b00d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to Flow are recorded here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project +follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.8.4] + +Current release. Earlier history was not recorded in this file. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..9447ea3 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +twinzler@proton.me. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..012fdb1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,121 @@ +# Contributing to Flow + +Thanks for wanting to help. Bug reports, fixes, documentation improvements and +new ideas are all welcome. By taking part you agree to follow the +[Code of Conduct](CODE_OF_CONDUCT.md). + +## Ways to contribute + +- **Report a bug** using the [bug report form](https://github.com/flow-twinx/flow/issues/new/choose). Include the output of `flow --check`. +- **Suggest a feature** using the feature request form. Describe the problem first, then the change you have in mind. +- **Fix something or add a feature** by opening a pull request (see below). +- **Improve the docs.** Typos, unclear steps and missing examples all count. +- **Write a plugin.** Plugins live in their own repositories; see the [plugin developer guide](docs/dev/plugins.md). + +Found a security problem? Do not open a public issue. Follow +[SECURITY.md](SECURITY.md) instead. + +## Development setup + +You need Python 3.14+, [uv](https://docs.astral.sh/uv/) and +[VLC](https://www.videolan.org/vlc/) (ffmpeg is optional, for non-webm +downloads). + +```bash +git clone https://github.com/flow-twinx/flow.git +cd flow +uv sync # install dependencies +uv run flow --check # verify the environment +``` + +Try your changes locally: + +```bash +uv run flow # interactive shell +uv run flow-tui # TUI +uv run flow-web # web GUI at http://127.0.0.1:5000 +uv run flow-min status # plain CLI +``` + +Running `config dev true` inside Flow prints more diagnostic information while +you work. + +## Running the tests + +```bash +uv run pytest # everything +uv run pytest tests/test_daemon_rpc.py -v # one file +uv run pytest -q -k registry # by keyword +``` + +The tests set a scratch `HOME` in `tests/conftest.py` before importing the +backend, so they never touch your real `~/.flow/`. Keep it that way: never +assume the real home directory in a test, and remember that subprocesses such +as `flow daemon` inherit the scratch `HOME`. + +Add or update tests for any bug fix or behaviour change. + +## Project layout + +| Path | Purpose | +| ----------- | -------------------------------------------------------------------- | +| `backend/` | Core logic and the source of truth, split into `Online/` and `Offline/` modes | +| `cli/` | The `flow` interactive shell and one-shot flags | +| `minimal/` | `flow-min`, the plain non-interactive CLI | +| `tui/` | The Textual full-screen interface | +| `web/` | The Flask web GUI and its templates | +| `docs/` | User and developer documentation | +| `tests/` | The pytest suite | + +Start with the [architecture overview](docs/dev/index.md). + +## Guidelines + +**Respect the module boundaries.** +- `backend/` owns the logic. `cli/`, `tui/`, `web/` and `minimal/` are thin front ends over it. +- Keep the Online/Offline split intact. Modes do not hand off to each other mid-command. +- `minimal/` imports `backend.*`, and nothing in `backend/` imports `minimal`. + +**Take care with shared state.** Several Flow processes can run at once and +coordinate through files under `~/.flow/`. Before changing anything that +touches the player registry, the SQLite databases, atomic writes or the daemon +socket, read the relevant module in `backend/` and the +[storage](docs/dev/storage.md) and [control](docs/dev/control.md) docs. Keep +the seek mechanism as it is: the control flags write a delta to +`~/.flow/seek.txt` before signalling the player. + +**Keep the `flow-min` output contract.** New `minimal/` commands wrap backend +calls in `out.quiet()` and print only through `out.emit` and `out.fail`, so +standard output stays exactly one line or one JSON document. Details are in +[docs/dev/minimal.md](docs/dev/minimal.md). + +**Mind the plugin boundary.** Plugins never import Flow internals. Anything +they can do goes through the typed API in `backend/rpc.py`, and the daemon +validates every call. Do not widen `PLUGIN_SAFE_KEYS` or the `raw_cli` +capability without a clear reason. + +**Keep changes focused.** +- Follow the style of the surrounding code and prefer small, targeted edits over rewrites. +- Comments are kept to a minimum: give functions and classes a short one-line docstring instead of inline comments. +- The repository has no linter or type-checker configured. Do not add new tooling as part of an unrelated change. + +**Update the docs.** The files in `docs/` are the reference for how Flow works. +If your change alters behaviour, a command, a flag or a file format, update the +matching page in the same pull request. + +## Submitting a pull request + +1. Fork the repository and create a branch from the default branch. +2. Make your change in small, logical commits with clear messages. +3. Run `uv run pytest` and make sure it passes. +4. Open a pull request and fill in the template. Say what changed and why, and link any related issue. +5. Respond to review comments. Maintainers may ask for changes before merging. + +For anything large, such as a new subsystem or a change to the storage or +control protocol, open an issue first so the approach can be agreed before you +spend time on it. + +## License + +By contributing, you agree that your contributions will be licensed under the +[MIT License](LICENSE). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3ecc8ba --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Twinx015 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 5b2e0bb..100b92e 100644 --- a/README.md +++ b/README.md @@ -1,99 +1,221 @@
- Flow Logo + +
+███████╗██╗      ██████╗ ██╗    ██╗
+██╔════╝██║     ██╔═══██╗██║    ██║
+█████╗  ██║     ██║   ██║██║ █╗ ██║
+██╔══╝  ██║     ██║   ██║██║███╗██║
+██║     ███████╗╚██████╔╝╚███╔███╔╝
+╚═╝     ╚══════╝ ╚═════╝  ╚══╝╚══╝
+  

Flow

-

A modern terminal based music player with TUI and web support also.

+

A modern terminal music player with online streaming, an offline library, a TUI and a web GUI.

+ +

+ License: MIT + Python 3.14+ + Platform: Linux, macOS +

+ +

+ Installation · + Quick start · + Documentation · + Plugins · + Contributing +

--- ## Overview -Flow is a terminal music player with online streaming and offline library modes. +Flow is a terminal music player with two modes. **Online mode** streams from +YouTube (through `yt-dlp` and VLC) and JioSaavn. **Offline mode** plays the +songs you have already downloaded. Flow checks your connection on startup and +picks the right mode for you; `switch` flips it whenever you like. -Flow detects your connection and picks automatically: **online mode** -streams from YouTube (via `yt-dlp` and `python-vlc`) and JioSaavn, **offline -mode**. All state — -downloads, likes, playlists, settings — lives in one folder and is shared -between the CLI shell, the Textual TUI, and the web GUI. +Everything Flow stores (downloads, likes, playlists, history, settings) lives +in a single folder, `~/.flow/`, and is shared by every interface. Like a song +in the TUI and it is liked in the web GUI and the shell too. ---- +▶ **[Watch the demo](demo.mp4)** ## Features -- **Dual-mode** — automatic offline/online detection with manual `switch` -- **Online mode** — YouTube search/stream, radio mixes, JioSaavn (`savan`) -- **Offline mode** — local library with search, liked songs, and tab completion -- **Downloads** — save tracks from YouTube (`-d`), formats: webm/opus/m4a/mp3 -- **Repeat & shuffle** — `-r [n]` loops, `-s` randomizes -- **Playlists** — create, edit, merge, dedupe, reorder, export/import `.m3u` -- **Like/unlike** — favorites in `~/.flow/library.db`, auto-download on like -- **Play history** — per-song play counts in both modes, an online play log, `flow summary` on the CLI and a **History** panel in the web GUI -- **Background play** — play in the background and go back to your shell -- **Visualizer** — audio-reactive spectrum bars (or synced lyrics) while playing -- **Lyrics** — synced lines from [LRCLIB](https://lrclib.net) (YouTube Music as fallback): the `lyrics` display mode prints them in the terminal, the web GUI's lyrics button (`l`) scrolls them with the track -- **Rename** — correct a misspelt title once (`rename` in the CLI, `R` in the TUI, the ⋮ menu in the web GUI) and every surface, including lyrics search, shows the new name -- **Play by tag** — every download stores a one-word language and the credited artist, trimmed out of the video's metadata: `lang punjabi` plays your punjabi songs, `artist karan` every Karan Aujla one (`tags` to see what you have, `tags scan`/`tags apply` to tag the back catalogue) -- **Three interfaces** — interactive CLI shell, full-screen [TUI](docs/user/interface.md), and a [web GUI](docs/user/interface.md) on port 5000 -- **Scriptable** — `flow-min` runs the same commands with no colour, spinner or prompt: one plain line (or one `--json` document) per command, documented exit codes, safe in pipes, over ssh and for agents -- **Plugins** — community plugins run in isolated processes +**Playback** + +- Automatic online/offline detection with a manual `switch` +- YouTube search and streaming, radio mixes and JioSaavn (`savan`) +- Offline library with search, tab completion and liked songs +- Repeat (`-r [n]`), shuffle (`-s`) and background play (`-bg`) +- Audio-reactive spectrum visualizer, or synced lyrics, while a track plays + +**Library** + +- Downloads from YouTube (`-d`) as webm, opus, m4a or mp3 +- Playlists: create, edit, merge, dedupe, reorder, and export or import `.m3u` +- Like and unlike, with optional auto-download on like +- Play counts in both modes, `flow summary` in the CLI and a History panel in the web GUI +- Rename a misspelt title once and every surface, lyrics search included, uses the new name +- Play by tag: `lang punjabi` or `artist karan` plays matching songs from your library + +**Lyrics** + +- Synced lines from [LRCLIB](https://lrclib.net), with YouTube Music as a fallback +- Printed in the terminal in `lyrics` display mode, or scrolled with the track in the web GUI + +**Interfaces** + +- An interactive CLI shell, a full-screen TUI and a local web GUI +- `flow-min`, a plain non-interactive CLI for scripts, ssh and agents (see below) + +**Extensible** + +- Community plugins that run as isolated processes and talk to Flow through a typed, host-validated API + +## Interfaces + +| Command | What it is | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `flow` | Interactive shell with commands, tab completion and one-shot playback flags | +| `flow-tui` | Full-screen [Textual](https://textual.textualize.io) UI with a track list and Now Playing panel | +| `flow-web` | Local web GUI served on `127.0.0.1`, on the first free port from 5000 to 5005 | +| `flow-min` | Plain output, no colour, spinner or prompt: one line or one `--json` document per command, documented exit codes, safe in pipes | + +All four share the same library and settings, and playback control works +across them: `flow-min next` skips a track started from the shell, the TUI or +the web GUI. See [Interfaces](docs/user/interface.md) for how to use the TUI +and web GUI. ## Requirements -- Python 3.14+ -- [VLC](https://www.videolan.org/vlc/) (for `python-vlc` audio playback) -- ffmpeg (optional, only for non-webm download formats) +- **Linux or macOS.** Flow uses Unix-only APIs, so on Windows run it under WSL. +- **Python 3.14+** +- **[VLC](https://www.videolan.org/vlc/)**, used through `python-vlc` for all audio playback +- **ffmpeg** (optional), only needed to download in a format other than webm +- **git** (optional), only needed to install plugins ## Installation +From PyPI: + +```bash +pip install flow-twinx +flow +``` + +From source, with [uv](https://docs.astral.sh/uv/): + ```bash -git clone https://github.com/Twinx015/Flow.git -cd Flow +git clone https://github.com/flow-twinx/flow.git +cd flow uv sync # or: pip install . uv run flow ``` -Or from PyPI: +Check that your environment is ready: ```bash -pip install flow-twinx -flow +flow --check ``` -Verify with `flow --check`. See [Installation](docs/user/installation.md) -for details. +This prints a pass/fail table for ffmpeg, VLC, yt-dlp and the other core +dependencies. There is no setup step: Flow creates `~/.flow/` on demand. More +detail is in [Installation](docs/user/installation.md). ## Quick start ```bash -flow -pl "never gonna give you up" # stream from YouTube (foreground) -flow -pl "never gonna give you up" -bg # ...in the background -flow -sh "daft punk" # search, show results -flow --play-off "my song" # play from the local library (auto-bg) -flow --radio-off # shuffle-loop the whole library (auto-bg) -flow # interactive shell (type `help`) -flow-tui # full-screen TUI -flow-web # web GUI → http://127.0.0.1:5000 -flow-min status --json # plain non-interactive: one JSON document +flow -pl "never gonna give you up" # stream from YouTube (foreground) +flow -pl "never gonna give you up" -bg # ...in the background +flow -sh "daft punk" # search and show results +flow --play-off "my song" # play from the local library +flow --radio-off # shuffle-loop the whole library +flow # interactive shell (type `help`) +flow-tui # full-screen TUI +flow-web # web GUI at http://127.0.0.1:5000 +flow-min status --json # one JSON document, script-friendly ``` -Playback control works across interfaces from any terminal: +`-pl` and `-sh` are built-in shortcuts for `play` and `search`. You can add +your own with the `short` command (see [Command line](docs/user/command-line.md)). + +Playback control works across interfaces, from any terminal: ```bash flow --status # show the current track flow --pause # play/pause the running player flow --next # skip -flow --seek 30 # seek 30s forward +flow --seek 30 # seek 30 seconds forward ``` +Inside the shell, `help` lists every command and `help -i` explains them in +detail. The full reference is in [Command line](docs/user/command-line.md). + +## Plugins + +Plugins are small programs installed from git repositories. They run in their +own processes and use only the `flow_api` module, which Flow provides, to read +the current track, control playback and change a safe set of settings. + +```bash +flow plugins list # browse available plugins +flow install # install by name +flow install owner/repo # install from GitHub +flow run # run in the background (-t for foreground) +flow plugin kill # stop a running plugin +``` + +Read the [user guide](docs/user/plugins.md) to use plugins, or the +[developer guide](docs/dev/plugins.md) to write one. + ## Documentation -- **User guide** — [docs/user/](docs/user/index.md): commands and flags, - TUI/web usage, configuration and storage, plugins -- **Developer guide** — [docs/dev/](docs/dev/index.md): architecture, mode - internals, storage schemas, control protocol, interfaces +- **[User guide](docs/user/index.md)**: commands and flags, TUI and web usage, configuration and storage, plugins +- **[Developer guide](docs/dev/index.md)**: architecture, online and offline internals, storage schemas, the control protocol, interfaces + +## Development + +```bash +uv sync # install dependencies +uv run flow --check # verify the environment +uv run pytest # run the test suite +``` + +The tests run against a scratch `HOME`, so they never touch your real +`~/.flow/`. The backend in `backend/` owns all logic; the `cli/`, `tui/`, +`web/` and `minimal/` packages are thin front ends over it. Read +[CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request. + +## Contributing + +Bug reports, feature ideas and pull requests are welcome. Please read the +[contributing guide](CONTRIBUTING.md) and the +[code of conduct](CODE_OF_CONDUCT.md) first. To report a security issue, follow +[SECURITY.md](SECURITY.md) rather than opening a public issue. + +## Disclaimer + +Flow is a personal-use tool. It is not affiliated with or endorsed by YouTube, +JioSaavn, VLC or any other service it connects to. You are responsible for +following the terms of service of those services and the copyright laws that +apply to you when you stream or download content. + +## Acknowledgements + +Flow is built on the work of many open-source projects, including +[yt-dlp](https://github.com/yt-dlp/yt-dlp), [VLC](https://www.videolan.org/vlc/) +and [python-vlc](https://github.com/oaubert/python-vlc), +[Textual](https://github.com/Textualize/textual), +[Flask](https://flask.palletsprojects.com), +[ytmusicapi](https://github.com/sigma67/ytmusicapi) and +[questionary](https://github.com/tmbo/questionary). Synced lyrics come from +[LRCLIB](https://lrclib.net). ## License -Use however you want, just mention me for inspiration. +Flow is released under the [MIT License](LICENSE). You can use, modify and +share it freely, as long as the copyright notice stays with it. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..fe8a2a7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,58 @@ +# Security Policy + +## Supported versions + +Only the latest release of Flow receives security fixes. Please update to the +newest version before reporting a problem. + +## Reporting a vulnerability + +Please do not report security vulnerabilities in public issues, pull requests +or discussions. + +Report them privately by either: + +- using the **Report a vulnerability** button on the repository's **Security** + tab, if it is available, or +- emailing **twinzler@proton.me** with the subject line `Flow security report`. + +Please include: + +- a description of the issue and its impact +- the Flow version, operating system and Python version +- steps to reproduce, or a proof of concept +- any suggested fix, if you have one + +You can expect an acknowledgement within a few days. After that we will work +with you to confirm the issue, prepare a fix and agree a time to disclose it. +We are happy to credit you in the release notes unless you prefer to stay +anonymous. + +## Scope + +Flow is a local, single-user application. Reports are most useful when they +concern: + +- the plugin system: escaping the process isolation, bypassing the + capability checks in the daemon (`raw_cli`, `PLUGIN_SAFE_KEYS`), or reaching + data a plugin was not granted +- the daemon's local socket (`~/.flow/flow.sock`) and its permissions +- the local web GUI and its control API +- unsafe handling of files, paths or data under `~/.flow/` +- unsafe handling of untrusted input such as playlist imports, metadata from + online sources or downloaded filenames + +The following are out of scope: + +- vulnerabilities in third-party plugins. Report those to the plugin's author. +- vulnerabilities in dependencies such as yt-dlp, VLC or Flask. Report those + upstream, though we would appreciate a heads-up if Flow needs a version bump. +- issues that need an attacker to already have full control of your account + or machine +- questions about the content or licensing of music you stream or download + +## A note on plugins + +Plugins are third-party code. Flow runs them in separate processes and limits +what they can do through a typed, host-validated API, but you should still +only install plugins from authors you trust. diff --git a/backend/Offline/commands.py b/backend/Offline/commands.py index 29a5b1c..a1da3bd 100644 --- a/backend/Offline/commands.py +++ b/backend/Offline/commands.py @@ -1,18 +1,17 @@ -import errno -import fcntl import os import pathlib import random import signal import sys -import termios -import threading import time from backend import ( config, help_detail, + ipc, + keys, library, + platform, playlist, plist_cli, shortcuts, @@ -38,12 +37,15 @@ def _fork_bg(label): config.kill_stored() + if not platform.can_fork(): + i(f"{label} (background playback is unavailable on this OS)") + return True pid = os.fork() if pid > 0: config.save_pid(pid) i(f"{label} in background (PID: {pid})") return False - player.setup_nav_signals() + player._install_controls() devnull = os.open(os.devnull, os.O_RDWR) os.dup2(devnull, 0) os.dup2(devnull, 1) @@ -106,7 +108,7 @@ def _radio_sigquit(sig, frame): "rename": "Rename a downloaded song (alias: re)", "lang": "Play songs by language tag | lang | -s shuffle", "artist": "Play songs by artist | artist | -s shuffle", - "tags": "Library tags | tags | tags scan (preview) | tags apply", + "tags": "Library tags | tags (editor) | tags list/add/remove/rename/delete", "playlist": "Manage playlists | create add remove list play rename move dup merge sort clear dedupe info export import (-m for multi add/remove) (alias: plist)", "switch": "Switch to Online mode (checks connection)", "help": "Show this help message", @@ -144,7 +146,10 @@ def complete(self, text, state): words = library.get_tag_counts()[index] options = sorted(w for w, _ in words if w.startswith(text.lower())) elif parts[0] == "tags": - options = [a for a in ("scan", "apply", "all") if a.startswith(text)] + options = [ + a for a in ("list", "add", "remove", "rename", "delete") + if a.startswith(text) + ] else: options = [] self.matches = options @@ -930,8 +935,10 @@ def artist_track(extra, args): def list_tags(): """What the library can be played by right now.""" langs, artists = library.get_tag_counts() - if not langs and not artists: - e("No tags yet - run: tags scan") + custom = library.all_song_tags() + if not langs and not artists and not custom: + e("No tags yet") + m(" Try: tags add (bare `tags` opens the editor)") return if langs: m("\nLanguages:") @@ -941,110 +948,457 @@ def list_tags(): m("\nArtists:") for word, count in artists: m(f" {word} ({count})") + if custom: + m("\nTags:") + for word, count in custom: + m(f" {word} ({count})") -PREVIEW_FILE = config.DOWNLOAD_DIR.parent / "tags-preview.tsv" +def edit_tags(): + """Interactive tag editor: language, artist and free-form tags.""" + from ..ui import pick + try: + import questionary # noqa: F401 - presence check + except ImportError: + questionary = None + if questionary is None: + e("Tag editor needs questionary; the plain forms still work:") + m(" tags list | tags add | tags remove ") + m(" tags rename | tags delete ") + return + kind, used = pick( + "What do you want to edit?", + [ + ("Language tags", "language"), + ("Artist tags", "artist"), + ("Free-form tags", "custom"), + ], + instruction="(↑↓ navigate, Enter to select)", + mode="offline", + ) + if not used or kind is None: + return + if kind == "custom": + _edit_custom() + else: + label = "Language" if kind == "language" else "Artist" + _edit_field(kind, label) -def _preview_targets(force): - rows = [] - for video_id, entry in library.load().items(): - if not entry.get("downloaded"): - continue - if force or not (entry.get("language") or "").strip(): - rows.append((video_id, entry.get("title") or video_id)) - return rows +def _edit_field(field, label): + """Whole-tag and per-song editing for the language/artist column.""" + from ..ui import pick, questionary_style -def scan_tags(extra): - """`tags scan` writes the tags YouTube reports to a file; nothing is saved.""" - from ..Online import youtube - from ..tags import tags_from_info + actions = [ + (f"Set {label} value on songs", "set"), + (f"Rename a {label} value everywhere", "rename"), + (f"Delete {label} value(s) everywhere", "delete"), + (f"Clear {label} value(s) on songs", "clear"), + ] + action, used = pick( + f"{label} tags - what do you want to do?", + actions, + instruction="(↑↓ navigate, Enter to select)", + mode="offline", + ) + if not used or action is None: + return + style = questionary_style("offline") + if action == "set": + ids = _pick_songs(f"Which songs get this {label.lower()}?") + if ids is None: + return + if not ids: + m(" No songs picked") + return + value = _ask_text(f"{label} value (empty clears it):", style) + if value is None: + m(" Cancelled") + return + value = value.strip() + done = 0 + for vid in ids: + if library.set_song_field(vid, field, value): + done += 1 + m(f" {label.lower()} set on {done} song(s)") + elif action == "rename": + _edit_field_rename(field, label, style) + elif action == "delete": + _edit_field_delete(field, label, style) + else: + _edit_field_clear(field, label, style) - force = any(x in ("-a", "--all", "all") for x in extra) - targets = _preview_targets(force) - if not targets: - m(" Every downloaded song already has a language tag") - return - - lines = ["# video_id\tlanguage\tartist\ttitle"] - failed = [] - for pos, (video_id, title) in enumerate(targets, 1): - print(f"\r{P} [{pos}/{len(targets)}] {title[:46]:48}{R}", end="", flush=True) - info = youtube.fetch_info(video_id) - if not info: - failed.append(title) - continue - found = tags_from_info(info) - lines.append( - "\t".join( - [ - video_id, - found.get("language") or "", - (found.get("artist") or "").replace("\t", " "), - title.replace("\t", " "), - ] - ) - ) - print("\r" + " " * 66 + "\r", end="") - - PREVIEW_FILE.parent.mkdir(parents=True, exist_ok=True) - PREVIEW_FILE.write_text("\n".join(lines) + "\n") - i(f" Preview written: {PREVIEW_FILE}") - i(f" {len(lines) - 1} song(s), {len(failed)} failed") - m(" Nothing was saved. Review the file, then run: tags apply") - - -def apply_tags(extra): - """`tags apply` writes the reviewed preview into library.db.""" - path = pathlib.Path(next((x for x in extra if not x.startswith("-")), PREVIEW_FILE)) - if not path.exists(): - e(f" No preview at {path} - run: tags scan") - return - saved_langs = 0 - saved_artists = 0 - missing = 0 - for line in path.read_text().splitlines(): - if not line.strip() or line.startswith("#"): - continue - parts = line.split("\t") - if len(parts) < 4: - continue - video_id, language, artist, title = parts[0], parts[1], parts[2], parts[3] - entry = library.get(video_id) - if entry is None: - missing += 1 - continue - meta = {} - if language and language != (entry.get("language") or ""): - meta["language"] = language - if artist and not (entry.get("artist") or "").strip(): - meta["artist"] = artist - if meta: - library.update_meta(video_id, meta) - saved_langs += "language" in meta - saved_artists += "artist" in meta - i( - f" Saved {saved_langs} language tag(s), filled {saved_artists} missing artist(s)" + +def _edit_field_rename(field, label, style): + from ..ui import pick + + words = library.get_tag_counts()[0 if field == "language" else 1] + if not words: + m(f" No {label.lower()} tags yet") + return + choice, used = pick( + f"Which {label.lower()} tag?", + [(f"{word} ({count})", word) for word, count in words], + instruction="(↑↓ navigate, Enter to select)", + mode="offline", + ) + if not used or choice is None: + return + new = _ask_text(f"New name for '{choice}':", style, default=choice) + if new is None or not new.strip(): + m(" Cancelled") + return + new = new.strip() + if new.lower() == choice.lower(): + m(f" Already named '{choice}'") + return + changed = library.rename_field_tag(field, choice, new) + m(f" Renamed {choice!r} -> {new!r} on {changed} song(s)") + + +def _edit_field_delete(field, label, style): + words = library.get_tag_counts()[0 if field == "language" else 1] + if not words: + m(f" No {label.lower()} tags yet") + return + picks = _pick_many_tags(f"Which {label.lower()} tags?", words) + if picks is None: + return + if not picks: + m(" No tags picked") + return + if not _ask_confirm( + f"Delete {len(picks)} {label.lower()} tag(s) from every song?", style + ): + m(" Cancelled") + return + total = 0 + for word in picks: + total += library.delete_field_tag(field, word) + m(f" Deleted {len(picks)} {label.lower()} tag(s) from {total} song(s)") + + +def _edit_field_clear(field, label, style): + ids = _pick_songs(f"Which songs clear their {label.lower()}?") + if ids is None: + return + if not ids: + m(" No songs picked") + return + if not _ask_confirm(f"Clear {label.lower()} from {len(ids)} song(s)?", style): + m(" Cancelled") + return + done = 0 + for vid in ids: + if library.set_song_field(vid, field, ""): + done += 1 + m(f" Cleared {label.lower()} from {done} song(s)") + + +def _edit_custom(): + """Interactive editing for the free-form tags.""" + from ..ui import pick, questionary_style + + actions = [ + ("Add a tag to songs", "add"), + ("Remove a tag from songs", "remove"), + ("Rename a tag everywhere", "rename"), + ("Delete tag(s) everywhere", "delete"), + ("Clear tags on songs", "clear"), + ] + action, used = pick( + "Free-form tags - what do you want to do?", + actions, + instruction="(↑↓ navigate, Enter to select)", + mode="offline", + ) + if not used or action is None: + return + style = questionary_style("offline") + if action == "add": + _edit_custom_add(style) + elif action == "remove": + _edit_custom_remove(style) + elif action == "rename": + _edit_custom_rename(style) + elif action == "delete": + _edit_custom_delete(style) + else: + _edit_custom_clear(style) + + +def _edit_custom_add(style): + """Add one tag to several checkbox-picked songs.""" + existing = library.all_song_tags() + if existing: + m(" existing tags: " + ", ".join(word for word, _ in existing)) + ids = _pick_songs("Which songs get the tag?") + if ids is None: + return + if not ids: + m(" No songs picked") + return + tag = _ask_text("Tag name:", style) + if tag is None: + m(" Cancelled") + return + tag = tag.strip() + if not tag: + m(" Empty tag - cancelled") + return + done = 0 + for vid in ids: + if library.set_song_tag(vid, tag, True): + done += 1 + m(f" Tagged {done} song(s) with '{tag}'") + + +def _edit_custom_remove(style): + """Pick several songs, then one tag to take off all of them.""" + from ..ui import pick + + ids = _pick_songs("Which songs lose the tag?") + if ids is None: + return + if not ids: + m(" No songs picked") + return + tags = set() + for vid in ids: + tags.update(library.song_tags(vid)) + if not tags: + m(" None of those songs have free-form tags") + return + choice, used = pick( + "Which tag?", [(t, t) for t in sorted(tags)], mode="offline" + ) + if not used or choice is None: + return + done = 0 + for vid in ids: + if choice in library.song_tags(vid): + library.set_song_tag(vid, choice, False) + done += 1 + m(f" Removed '{choice}' from {done} song(s)") + + +def _edit_custom_rename(style): + """Rename one tag everywhere; each tag needs its own new name.""" + from ..ui import pick + + words = library.all_song_tags() + if not words: + m(" No free-form tags yet") + return + choice, used = pick( + "Which tag?", + [(f"{word} ({count})", word) for word, count in words], + mode="offline", ) - if missing: - m(f" {missing} row(s) in the file are no longer in the library") - m(" Play with: lang | artist ") + if not used or choice is None: + return + new = _ask_text(f"New name for '{choice}':", style, default=choice) + if new is None or not new.strip(): + m(" Cancelled") + return + new = new.strip() + if new == choice: + m(f" Already named '{choice}'") + return + changed = library.rename_tag(choice, new) + m(f" Renamed {choice!r} -> {new!r} on {changed} song(s)") + + +def _edit_custom_delete(style): + """Checkbox-pick several tags and delete them all after one confirm.""" + words = library.all_song_tags() + if not words: + m(" No free-form tags yet") + return + picks = _pick_many_tags("Which tags?", words) + if picks is None: + return + if not picks: + m(" No tags picked") + return + if not _ask_confirm(f"Delete {len(picks)} tag(s) from every song?", style): + m(" Cancelled") + return + total = 0 + for word in picks: + total += library.delete_tag(word) + m(f" Deleted {len(picks)} tag(s) from {total} song(s)") + + +def _edit_custom_clear(style): + """Clear every free-form tag on several checkbox-picked songs.""" + ids = _pick_songs("Which songs lose all their tags?") + if ids is None: + return + if not ids: + m(" No songs picked") + return + if not _ask_confirm(f"Clear every tag on {len(ids)} song(s)?", style): + m(" Cancelled") + return + dropped = 0 + for vid in ids: + dropped += library.clear_song_tags(vid) + m(f" Cleared {dropped} tag(s) from {len(ids)} song(s)") + + +def _song_label(row): + parts = [row["title"]] + if row["artist"]: + parts.append(row["artist"]) + if row["language"]: + parts.append(f"({row['language']})") + if row["tags"]: + parts.append("[" + ", ".join(row["tags"]) + "]") + return " ".join(parts) + + +def _pick_songs(prompt): + """Checkbox-pick downloaded songs; [] when none picked, None on cancel.""" + rows = library.downloaded_rows() + if not rows: + m(" No downloaded songs to tag") + return None + from ..ui import pick_many + + choices = [(_song_label(r), r["video_id"]) for r in rows] + picked, used = pick_many(prompt, choices, mode="offline") + if not used: + return None + return picked or [] + + +def _pick_many_tags(prompt, words): + """Checkbox-pick tags; [] when none picked, None on cancel.""" + from ..ui import pick_many + + if not words: + return None + choices = [(f"{word} ({count})", word) for word, count in words] + picked, used = pick_many(prompt, choices, mode="offline") + if not used: + return None + return picked or [] + + +def _ask_text(prompt, style, default=""): + try: + import questionary + + return questionary.text(prompt, default=default, style=style).ask() + except KeyboardInterrupt, EOFError: + return None + + +def _ask_confirm(prompt, style): + try: + import questionary + + return questionary.confirm(prompt, style=style).ask() + except KeyboardInterrupt, EOFError: + return None + + +def tags_add_song(extra): + """`tags add ` puts a free-form tag on one downloaded song.""" + if len(extra) < 2: + e("Usage: tags add ") + return + path = _one_song(extra[0]) + if path is None: + e(" No downloaded song matching that name") + return + tag = " ".join(extra[1:]).strip() + if not tag: + e("Usage: tags add ") + return + if library.set_song_tag(path.stem, tag, True): + m(f" Tagged '{_truncate(path)}' with '{tag}'") + else: + e(" Could not tag that song") + + +def tags_remove_song(extra): + """`tags remove ` takes a free-form tag off one downloaded song.""" + if len(extra) < 2: + e("Usage: tags remove ") + return + path = _one_song(extra[0]) + if path is None: + e(" No downloaded song matching that name") + return + tag = " ".join(extra[1:]).strip() + if library.set_song_tag(path.stem, tag, False): + m(f" Removed '{tag}' from '{_truncate(path)}'") + + +def tags_rename(extra): + """`tags rename ` renames a free-form tag on every song.""" + if len(extra) < 2: + e("Usage: tags rename ") + return + old = extra[0] + new = " ".join(extra[1:]).strip() + changed = library.rename_tag(old, new) + if changed: + m(f" Renamed '{old}' -> '{new}' on {changed} song(s)") + else: + m(f" No song uses tag '{old}'") + + +def tags_delete(extra): + """`tags delete ` drops a free-form tag from every song.""" + if not extra: + e("Usage: tags delete ") + return + tag = " ".join(extra).strip() + changed = library.delete_tag(tag) + if changed: + m(f" Deleted tag '{tag}' from {changed} song(s)") + else: + m(f" No song uses tag '{tag}'") + + +def _one_song(query): + """Resolve a name/index to one downloaded song path, or None.""" + targets = _match_songs(query, prefer_library=True) + if not targets: + return None + if len(targets) > 1: + return _pick_target(targets, "tag") + return targets[0] def tags_cmd(extra, args): - """`tags` lists tags, `tags scan` previews fresh metadata, `tags apply` saves it.""" - action = extra[0].lower() if extra else "" + """`tags` opens the tag editor; `tags list|add|remove|rename|delete` are scriptable.""" + if not extra: + if sys.stdin.isatty(): + edit_tags() + else: + list_tags() + return + action = extra[0].lower() rest = extra[1:] - if action == "scan": - scan_tags(rest) - elif action == "apply": - apply_tags(rest) - elif not action: + if action == "list": list_tags() + elif action == "add": + tags_add_song(rest) + elif action == "remove": + tags_remove_song(rest) + elif action == "rename": + tags_rename(rest) + elif action == "delete": + tags_delete(rest) else: e(f"Unknown tags action: {action}") - m(" Try: tags | tags scan | tags apply") + m(" Try: tags | tags list | tags add ") + m(" tags remove | tags rename | tags delete ") def switch_mode(): @@ -1118,57 +1472,27 @@ def radio(extra, args): _radio_skip = False old_sigint = signal.signal(signal.SIGINT, _radio_sigint) - old_sigquit = signal.signal(signal.SIGQUIT, _radio_sigquit) - old_sigusr1 = signal.getsignal(signal.SIGUSR1) - - fd = sys.stdin.fileno() + old_sigquit = None + old_sigusr1 = None + ctl = sys.stdin.fileno() tty_fd = None - old_term = None - old_fd_flags = None - try: - tty_fd = os.open("/dev/tty", os.O_RDWR) - ctl = tty_fd - except OSError: - ctl = fd - try: - old_term = termios.tcgetattr(ctl) - new = termios.tcgetattr(ctl) - new[0] &= ~termios.IXON - new[6][termios.VQUIT] = 0x11 - new[6][termios.VSUSP] = 0 - termios.tcsetattr(ctl, termios.TCSADRAIN, new) - old_fd_flags = fcntl.fcntl(ctl, fcntl.F_GETFL) - fcntl.fcntl(ctl, fcntl.F_SETFL, old_fd_flags | os.O_NONBLOCK) - except termios.error, OSError: - pass - - def _radio_sigusr1(sig, frame): - player._sigusr1_toggle(sig, frame) - - signal.signal(signal.SIGUSR1, _radio_sigusr1) - signal.signal(signal.SIGTSTP, signal.SIG_IGN) player._radio_active = True - radio_stop = threading.Event() - - def _radio_input_reader(): + if not platform.is_windows(): + old_sigquit = signal.signal(signal.SIGQUIT, _radio_sigquit) + old_sigusr1 = signal.getsignal(signal.SIGUSR1) try: - while not radio_stop.is_set(): - try: - ch = os.read(ctl, 1) - except OSError as ex: - if ex.errno == errno.EAGAIN: - time.sleep(0.05) - continue - break - if not ch: - break - if ch == b"\x10": - os.kill(os.getpid(), signal.SIGUSR1) + tty_fd = os.open("/dev/tty", os.O_RDWR) + ctl = tty_fd except OSError: pass + signal.signal(signal.SIGTSTP, signal.SIG_IGN) - radio_reader = threading.Thread(target=_radio_input_reader, daemon=True) + def _radio_key(ch): + if ch == 0x10: + ipc.dispatch("pause") + + radio_reader = keys.RawReader(_radio_key, fd=ctl) radio_reader.start() flags = {"quit": lambda: _radio_quit, "skip": lambda: _radio_skip} @@ -1201,24 +1525,22 @@ def _radio_input_reader(): pass finally: player._radio_active = False - radio_stop.set() - if radio_reader.is_alive(): - radio_reader.join(timeout=0.2) - if old_term is not None: + radio_reader.stop() + if not platform.is_windows(): + if tty_fd is not None: + try: + os.close(tty_fd) + except OSError: + pass try: - if old_fd_flags is not None: - fcntl.fcntl(ctl, fcntl.F_SETFL, old_fd_flags) - termios.tcsetattr(ctl, termios.TCSADRAIN, old_term) - except termios.error, OSError: + signal.signal(signal.SIGQUIT, old_sigquit) + except (ValueError, OSError): pass - if tty_fd is not None: try: - os.close(tty_fd) - except OSError: + signal.signal(signal.SIGUSR1, old_sigusr1) + except (ValueError, OSError): pass signal.signal(signal.SIGINT, old_sigint) - signal.signal(signal.SIGQUIT, old_sigquit) - signal.signal(signal.SIGUSR1, old_sigusr1) def show_help(inf=False): diff --git a/backend/Offline/player.py b/backend/Offline/player.py index 96ab5e8..476f29a 100644 --- a/backend/Offline/player.py +++ b/backend/Offline/player.py @@ -1,18 +1,30 @@ import atexit -import curses -import errno -import fcntl import os import pathlib -import signal import sys -import termios import threading import time +from backend import ( + config, + history, + ipc, + keys, + library, + mpris, + platform, + rich_display, + status, + visualizer, +) + +platform.bootstrap_vlc() import vlc -from backend import config, history, library, mpris, status, visualizer +try: + import curses +except ImportError: + curses = None _truncate_title = config._truncate_title @@ -32,10 +44,8 @@ _paused = False _player = None -_original_term = None +_reader = None _radio_active = False -_stop_reader = threading.Event() -_reader_thread = None _next_req = False _prev_req = False @@ -84,110 +94,81 @@ def _clear_stale_pid(): atexit.register(_clear_stale_pid) -def _sigusr1_toggle(sig, frame): +def _sigusr1_toggle(): global _paused _paused = not _paused if _player: _player.pause() -def _sigusr2_next(sig, frame): +def _sigusr2_next(): global _next_req _next_req = True if _player: _player.stop() -def _sigusr3_prev(sig, frame): +def _sigusr3_prev(): global _prev_req _prev_req = True if _player: _player.stop() -def _sigusr4_stop(sig, frame): +def _sigusr4_stop(): global _stop_req _stop_req = True if _player: _player.stop() -def _seek_current(sig, frame): - delta_ms = config.read_seek() +def _seek_current(payload=None): + delta_ms = (payload or {}).get("delta") if payload else None + if delta_ms is None: + delta_ms = config.read_seek() config.clear_seek() if _player and delta_ms: cur = _player.get_time() if cur is not None and cur >= 0: - _player.set_time(max(0, int(cur) + delta_ms)) + _player.set_time(max(0, int(cur) + int(delta_ms))) -def setup_nav_signals(): - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - signal.signal(signal.SIGUSR2, _sigusr2_next) - signal.signal(config.SIG_PREV, _sigusr3_prev) - signal.signal(config.SIG_STOP_ALL, _sigusr4_stop) - signal.signal(config.SIG_SEEK_FWD, _seek_current) - signal.signal(config.SIG_SEEK_BWD, _seek_current) +def _dispatch_action(action, payload=None): + if action == "pause": + _sigusr1_toggle() + elif action == "next": + _sigusr2_next() + elif action == "prev": + _sigusr3_prev() + elif action == "stop_all": + _sigusr4_stop() + elif action in ("seek_fwd", "seek_bwd"): + _seek_current(payload) + + +def _install_controls(): + port = ipc.serve(_dispatch_action, kind="vlc") + config.save_pid(os.getpid(), ctl_port=port) def _setup_pause_input(): - global _original_term + global _reader if _radio_active: - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - setup_nav_signals() - return - fd = sys.stdin.fileno() - try: - _original_term = termios.tcgetattr(fd) - new = termios.tcgetattr(fd) - new[0] &= ~termios.IXON - new[6][termios.VSUSP] = 0 - termios.tcsetattr(fd, termios.TCSADRAIN, new) - except termios.error, OSError: - _original_term = None return - flags = fcntl.fcntl(fd, fcntl.F_GETFL) - fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - signal.signal(signal.SIGTSTP, signal.SIG_IGN) - setup_nav_signals() - _stop_reader.clear() - _reader_thread = threading.Thread(target=_input_reader, daemon=True) - _reader_thread.start() - - -def _input_reader(): - fd = sys.stdin.fileno() - try: - while not _stop_reader.is_set(): - try: - ch = os.read(fd, 1) - except OSError as ex: - if ex.errno == errno.EAGAIN: - time.sleep(0.05) - continue - break - if ch == b"\x10": - os.kill(os.getpid(), signal.SIGUSR1) - except OSError: - pass + _reader = keys.RawReader(_on_pause_key) + _reader.start() + + +def _on_pause_key(ch): + if ch == 0x10: + ipc.dispatch("pause") def _restore_pause_input(): - global _original_term, _reader_thread - _stop_reader.set() - if _reader_thread and _reader_thread.is_alive(): - _reader_thread.join(timeout=0.2) - _reader_thread = None - if _original_term is not None: - try: - fd = sys.stdin.fileno() - flags = fcntl.fcntl(fd, fcntl.F_GETFL) - fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK) - termios.tcsetattr(fd, termios.TCSADRAIN, _original_term) - except termios.error, OSError: - pass - _original_term = None + global _reader + if _reader is not None: + _reader.stop() + _reader = None def _flags_str(args): @@ -254,10 +235,15 @@ def _on_event(event): pass -def _display_loop(player, title=None, args=None, next_title=None, stop_check=None, duration=0): +def _display_loop( + player, title=None, args=None, next_title=None, stop_check=None, duration=0, + artist="", album="", +): global _paused display = config.Display - if display in ("bars", "progress") and not ( + if display == "bars" and (curses is None or not platform.is_linux()): + display = "none" + if display in ("bars", "progress", "rich") and not ( sys.stdin.isatty() and sys.stdout.isatty() ): display = "none" @@ -287,7 +273,8 @@ def _display_loop(player, title=None, args=None, next_title=None, stop_check=Non shuffle = bool(getattr(args, "shuffle", False)) repeat = bool(getattr(args, "repeat", False)) visualizer.set_status( - title, shuffle=shuffle, repeat=repeat, next_title=next_title + title, shuffle=shuffle, repeat=repeat, next_title=next_title, + artist=artist, album=album, ) if display == "bars": @@ -305,6 +292,12 @@ def _display_loop(player, title=None, args=None, next_title=None, stop_check=Non return paused_printed = False + rich_disp = None + if display == "rich": + rich_disp = rich_display.NowPlaying( + title or "", artist=artist, album=album, duration=duration + ) + rich_disp.start() try: while player.get_state() not in (vlc.State.Ended, vlc.State.Error): if stop_check and stop_check(): @@ -324,6 +317,11 @@ def _display_loop(player, title=None, args=None, next_title=None, stop_check=Non stdscr.refresh() except curses.error: pass + elif display == "rich": + if rich_disp: + rich_disp.update( + max(0.0, player.get_time() / 1000.0), paused=True + ) else: sys.stdout.write(f"\r {T}[Paused]{R} ") sys.stdout.flush() @@ -342,6 +340,9 @@ def _display_loop(player, title=None, args=None, next_title=None, stop_check=Non _tick_position(player, elapsed) if display == "bars": visualizer.draw() + elif display == "rich": + if rich_disp: + rich_disp.update(elapsed, _paused) elif display == "progress": config.render_progress(elapsed, duration) try: @@ -349,6 +350,8 @@ def _display_loop(player, title=None, args=None, next_title=None, stop_check=Non except OSError: pass finally: + if rich_disp is not None: + rich_disp.stop() if display == "bars": visualizer.stop() curses.nocbreak() @@ -395,6 +398,7 @@ def play_file(filepath, title, args=None, flags=None, next_title=None, nav=None) media = instance.media_new(str(filepath)) _player.set_media(media) _player.play() + _install_controls() _setup_pause_input() duration = 0 @@ -412,14 +416,6 @@ def play_file(filepath, title, args=None, flags=None, next_title=None, nav=None) status.update(title, duration, thumbnail=thumb) dur_min, dur_sec = divmod(int(duration), 60) flags_str = _flags_str(args) - if config.Display != "bars": - i(f"\nPlaying : {_truncate_title(title)}") - m( - f" [{dur_min}:{dur_sec:02d}] {flags_str}" - if flags_str - else f" [{dur_min}:{dur_sec:02d}]" - ) - video_id = filepath.stem artist = "" album = "" @@ -427,6 +423,17 @@ def play_file(filepath, title, args=None, flags=None, next_title=None, nav=None) if lib_entry: artist = lib_entry.get("artist") or "" album = lib_entry.get("album") or "" + if config.Display != "bars": + i(f"\nPlaying : {_truncate_title(title)}") + if artist: + m(f" {artist}") + if album: + m(f" {album}") + m( + f" [{dur_min}:{dur_sec:02d}] {flags_str}" + if flags_str + else f" [{dur_min}:{dur_sec:02d}]" + ) history.record_play( video_id, title, artist, mode="offline", duration=int(duration) ) @@ -464,6 +471,8 @@ def stop_check(): next_title=next_title, stop_check=stop_check, duration=duration, + artist=artist, + album=album, ) except KeyboardInterrupt: _player.stop() diff --git a/backend/Online/commands.py b/backend/Online/commands.py index 3db0a14..478e807 100644 --- a/backend/Online/commands.py +++ b/backend/Online/commands.py @@ -1,18 +1,18 @@ -import errno -import fcntl import os import pathlib import random import signal import sys -import termios import threading import time from backend import ( config, help_detail, + ipc, + keys, library, + platform, playlist, plist_cli, shortcuts, @@ -60,12 +60,15 @@ def _radio_sigquit(sig, frame): def _fork_bg(label): config.kill_stored() + if not platform.can_fork(): + i(f"{label} (background playback is unavailable on this OS)") + return True pid = os.fork() if pid > 0: config.save_pid(pid) i(f"{label} in background (PID: {pid})") return False - player.setup_nav_signals() + player._install_controls() devnull = os.open(os.devnull, os.O_RDWR) os.dup2(devnull, 0) os.dup2(devnull, 1) @@ -109,7 +112,7 @@ def _nav_delta(): "download": "Download audio from YouTube | -f (opus, m4a, mp3, webm)", "delete": "Delete a downloaded song (alias: dl-d)", "artist": "Play songs by artist | artist | -s shuffle", - "tags": "Library tags | tags | tags scan (preview) | tags apply", + "tags": "Library tags | tags (editor) | tags list/add/remove/rename/delete", "playlist": "Manage playlists | create add remove list play rename move dup merge sort clear dedupe info export import download (-m for multi add/remove)", "switch": "Switch to Offline mode", "help": "Show this help message", @@ -181,6 +184,11 @@ def run(cmd: str, extra: list[str], args): def _spinner(stop, label="Searching"): + from backend import rich_display + + if rich_display.active(): + rich_display.spinner_run(stop, label) + return chars = config.SPINNER i = 0 while not stop(): @@ -1151,57 +1159,27 @@ def radio(extra, args): return old_sigint = signal.signal(signal.SIGINT, _radio_sigint) - old_sigquit = signal.signal(signal.SIGQUIT, _radio_sigquit) - old_sigusr1 = signal.getsignal(signal.SIGUSR1) - - fd = sys.stdin.fileno() + old_sigquit = None + old_sigusr1 = None + ctl = sys.stdin.fileno() tty_fd = None - old_term = None - old_fd_flags = None - try: - tty_fd = os.open("/dev/tty", os.O_RDWR) - ctl = tty_fd - except OSError: - ctl = fd - try: - old_term = termios.tcgetattr(ctl) - new = termios.tcgetattr(ctl) - new[0] &= ~termios.IXON - new[6][termios.VQUIT] = 0x11 - new[6][termios.VSUSP] = 0 - termios.tcsetattr(ctl, termios.TCSADRAIN, new) - old_fd_flags = fcntl.fcntl(ctl, fcntl.F_GETFL) - fcntl.fcntl(ctl, fcntl.F_SETFL, old_fd_flags | os.O_NONBLOCK) - except termios.error, OSError: - pass - - def _radio_sigusr1(sig, frame): - player._sigusr1_toggle(sig, frame) - - signal.signal(signal.SIGUSR1, _radio_sigusr1) - signal.signal(signal.SIGTSTP, signal.SIG_IGN) player._radio_active = True - radio_stop = threading.Event() - - def _radio_input_reader(): + if not platform.is_windows(): + old_sigquit = signal.signal(signal.SIGQUIT, _radio_sigquit) + old_sigusr1 = signal.getsignal(signal.SIGUSR1) try: - while not radio_stop.is_set(): - try: - ch = os.read(ctl, 1) - except OSError as ex: - if ex.errno == errno.EAGAIN: - time.sleep(0.05) - continue - break - if not ch: - break - if ch == b"\x10": - os.kill(os.getpid(), signal.SIGUSR1) + tty_fd = os.open("/dev/tty", os.O_RDWR) + ctl = tty_fd except OSError: pass + signal.signal(signal.SIGTSTP, signal.SIG_IGN) + + def _radio_key(ch): + if ch == 0x10: + ipc.dispatch("pause") - radio_reader = threading.Thread(target=_radio_input_reader, daemon=True) + radio_reader = keys.RawReader(_radio_key, fd=ctl) radio_reader.start() flags = {"quit": lambda: _radio_quit, "skip": lambda: _radio_skip} @@ -1268,24 +1246,22 @@ def _radio_input_reader(): _radio_quit = True finally: player._radio_active = False - radio_stop.set() - if radio_reader.is_alive(): - radio_reader.join(timeout=0.2) - if old_term is not None: + radio_reader.stop() + if not platform.is_windows(): + if tty_fd is not None: + try: + os.close(tty_fd) + except OSError: + pass try: - if old_fd_flags is not None: - fcntl.fcntl(ctl, fcntl.F_SETFL, old_fd_flags) - termios.tcsetattr(ctl, termios.TCSADRAIN, old_term) - except termios.error, OSError: + signal.signal(signal.SIGQUIT, old_sigquit) + except (ValueError, OSError): pass - if tty_fd is not None: try: - os.close(tty_fd) - except OSError: + signal.signal(signal.SIGUSR1, old_sigusr1) + except (ValueError, OSError): pass signal.signal(signal.SIGINT, old_sigint) - signal.signal(signal.SIGQUIT, old_sigquit) - signal.signal(signal.SIGUSR1, old_sigusr1) def _resolve_fmt(args, extra=None): @@ -1374,183 +1350,6 @@ def _download_one(entry, fmt): i(f" Downloaded: {_truncate_title(title)}") -# def backfill_metadata(): -# ids = library.get_downloaded_ids() -# if not ids: -# e(" No downloaded songs in the library") -# return 1 -# import yt_dlp - -# i(f" Fetching metadata for {len(ids)} downloaded songs...") -# updated = 0 -# skipped = 0 -# failed = 0 -# for pos, video_id in enumerate(ids, 1): -# tag = f"[{pos}/{len(ids)}] {video_id}" -# existing = library.get(video_id) or {} -# if existing.get("artist") or existing.get("duration"): -# skipped += 1 -# continue -# try: -# with yt_dlp.YoutubeDL(youtube.ydl_opts_play) as ydl: -# info = ydl.extract_info( -# f"https://www.youtube.com/watch?v={video_id}", download=False -# ) -# except Exception as exc: -# failed += 1 -# m(f" {tag}: failed ({exc})") -# continue -# if not info: -# failed += 1 -# m(f" {tag}: no metadata returned") -# continue -# meta = library.meta_from_info(info) -# meta["title"] = info.get("title", "") -# library.update_meta(video_id, meta) # saves library.db right here -# updated += 1 -# label = meta.get("title") or video_id -# artist = meta.get("artist") or "" -# album = f" [{meta['album']}]" if meta.get("album") else "" -# dur = meta.get("duration") -# dur_s = f" ({dur // 60}:{dur % 60:02d})" if dur else "" -# i( -# f" {tag}: {_truncate_title(label)}{dur_s}{album}" -# + (f" — {artist}" if artist else "") -# ) -# tail = f" ({skipped} already done, {failed} failed)" if skipped or failed else "" -# print(f"\n{P}Backfilled metadata for {updated}/{len(ids)} songs{R}{tail}") -# return 0 - - -# def backfill_metadata(): -# files = sorted( -# f -# for f in config.DOWNLOAD_DIR.rglob("*") -# if f.is_file() and f.suffix.lower() in _AUDIO_EXTS -# ) -# if not files: -# m(" No downloaded songs found in ~/.flow/downloads") -# return 1 - -# import yt_dlp - -# i(f" Rebuilding library entries for {len(files)} downloaded file(s)...") -# updated = 0 -# skipped = 0 -# failed = 0 -# with yt_dlp.YoutubeDL(youtube.ydl_opts_play) as ydl: -# for pos, f in enumerate(files, 1): -# video_id = f.stem -# tag = f"[{pos}/{len(files)}] {video_id}" -# existing = library.get(video_id) or {} -# if ( -# existing.get("title") -# or existing.get("artist") -# or existing.get("duration") -# ): -# skipped += 1 -# continue -# try: -# info = ydl.extract_info( -# f"https://www.youtube.com/watch?v={video_id}", download=False -# ) -# except Exception as exc: -# failed += 1 -# m(f" {tag}: failed ({exc})") -# continue -# if not info: -# failed += 1 -# m(f" {tag}: no metadata returned") -# continue -# title = info.get("title") or "" -# meta = library.meta_from_info(info) -# library.track_download(video_id, str(f), title, meta) -# try: -# library.download_thumbnail(video_id) -# except Exception: -# pass -# updated += 1 -# label = _truncate_title(title) if title else video_id -# artist = meta.get("artist") or "" -# album = f" [{meta['album']}]" if meta.get("album") else "" -# dur = meta.get("duration") -# dur_s = f" ({dur // 60}:{dur % 60:02d})" if dur else "" -# i(f" {tag}: {label}{dur_s}{album}" + (f" — {artist}" if artist else "")) -# tail = f" ({skipped} already done, {failed} failed)" if skipped or failed else "" -# print(f"\n{P}Rebuilt metadata for {updated}/{len(files)} songs{R}{tail}") -# return 0 - - -def backfill_metadata(): - files = sorted( - f - for f in config.DOWNLOAD_DIR.rglob("*") - if f.is_file() and f.suffix.lower() in _AUDIO_EXTS - ) - if not files: - m(" No downloaded songs found in ~/.flow/downloads") - return 1 - - import yt_dlp - from Tile import parse_title - - i(f" Rebuilding library entries for {len(files)} downloaded file(s)...") - updated = 0 - skipped = 0 - failed = 0 - with yt_dlp.YoutubeDL(youtube.ydl_opts_play) as ydl: - for pos, f in enumerate(files, 1): - video_id = f.stem - tag = f"[{pos}/{len(files)}] {video_id}" - existing = library.get(video_id) or {} - if existing.get("title") and existing.get("artist"): - skipped += 1 - continue - try: - info = ydl.extract_info( - f"https://www.youtube.com/watch?v={video_id}", download=False - ) - except Exception as exc: - failed += 1 - m(f" {tag}: failed ({exc})") - continue - if not info: - failed += 1 - m(f" {tag}: no metadata returned") - continue - - raw_title = info.get("title") or "" - meta = library.meta_from_info(info) - parsed = parse_title(raw_title) if raw_title else {} - title = parsed.get("title") or raw_title - artist = parsed.get("artist") or meta.get("artist") or "" - if title: - meta["title"] = title - if artist: - meta["artist"] = artist - library.track_download(video_id, str(f), title, meta) - if meta.get("title"): - library.update_meta(video_id, meta) - try: - library.download_thumbnail(video_id) - except Exception: - pass - updated += 1 - label = _truncate_title(title) if title else video_id - album = f" [{meta['album']}]" if meta.get("album") else "" - dur = meta.get("duration") - dur_s = f" ({dur // 60}:{dur % 60:02d})" if dur else "" - extras = parsed.get("extras") or [] - extra_s = f" {{{', '.join(str(x) for x in extras)}}}" if extras else "" - i( - f" {tag}: {label}{dur_s}{album}{extra_s}" - + (f" — {artist}" if artist else "") - ) - tail = f" ({skipped} already done, {failed} failed)" if skipped or failed else "" - print(f"\n{P}Rebuilt metadata for {updated}/{len(files)} songs{R}{tail}") - return 0 - - _AUDIO_EXTS = { ".mp3", ".flac", diff --git a/backend/Online/player.py b/backend/Online/player.py index d1d9f30..05d55d1 100644 --- a/backend/Online/player.py +++ b/backend/Online/player.py @@ -1,17 +1,31 @@ import atexit -import curses -import errno -import fcntl import os -import signal import sys -import termios import threading import time +from backend import ( + config, + history, + ipc, + keys, + library, + lyrics, + mpris, + platform, + rich_display, + sponsor, + status, + visualizer, +) + +platform.bootstrap_vlc() import vlc -from backend import config, history, library, lyrics, mpris, sponsor, status, visualizer +try: + import curses +except ImportError: + curses = None _truncate_title = config._truncate_title @@ -30,10 +44,8 @@ _paused = False _player = None -_original_term = None +_reader = None _radio_active = False -_stop_reader = threading.Event() -_reader_thread = None _next_req = False _prev_req = False @@ -99,110 +111,81 @@ def _clear_stale_pid(): atexit.register(_clear_stale_pid) -def _sigusr1_toggle(sig, frame): +def _sigusr1_toggle(): global _paused _paused = not _paused if _player: _player.pause() -def _sigusr2_next(sig, frame): +def _sigusr2_next(): global _next_req _next_req = True if _player: _player.stop() -def _sigusr3_prev(sig, frame): +def _sigusr3_prev(): global _prev_req _prev_req = True if _player: _player.stop() -def _sigusr4_stop(sig, frame): +def _sigusr4_stop(): global _stop_req _stop_req = True if _player: _player.stop() -def _seek_current(sig, frame): - delta_ms = config.read_seek() +def _seek_current(payload=None): + delta_ms = (payload or {}).get("delta") if payload else None + if delta_ms is None: + delta_ms = config.read_seek() config.clear_seek() if _player and delta_ms: cur = _player.get_time() if cur is not None and cur >= 0: - _player.set_time(max(0, int(cur) + delta_ms)) + _player.set_time(max(0, int(cur) + int(delta_ms))) -def setup_nav_signals(): - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - signal.signal(signal.SIGUSR2, _sigusr2_next) - signal.signal(config.SIG_PREV, _sigusr3_prev) - signal.signal(config.SIG_STOP_ALL, _sigusr4_stop) - signal.signal(config.SIG_SEEK_FWD, _seek_current) - signal.signal(config.SIG_SEEK_BWD, _seek_current) +def _dispatch_action(action, payload=None): + if action == "pause": + _sigusr1_toggle() + elif action == "next": + _sigusr2_next() + elif action == "prev": + _sigusr3_prev() + elif action == "stop_all": + _sigusr4_stop() + elif action in ("seek_fwd", "seek_bwd"): + _seek_current(payload) + + +def _install_controls(): + port = ipc.serve(_dispatch_action, kind="vlc") + config.save_pid(os.getpid(), ctl_port=port) def _setup_pause_input(): - global _original_term + global _reader if _radio_active: - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - setup_nav_signals() - return - fd = sys.stdin.fileno() - try: - _original_term = termios.tcgetattr(fd) - new = termios.tcgetattr(fd) - new[0] &= ~termios.IXON - new[6][termios.VSUSP] = 0 - termios.tcsetattr(fd, termios.TCSADRAIN, new) - except termios.error, OSError: - _original_term = None return - flags = fcntl.fcntl(fd, fcntl.F_GETFL) - fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) - signal.signal(signal.SIGUSR1, _sigusr1_toggle) - signal.signal(signal.SIGTSTP, signal.SIG_IGN) - setup_nav_signals() - _stop_reader.clear() - _reader_thread = threading.Thread(target=_input_reader, daemon=True) - _reader_thread.start() - - -def _input_reader(): - fd = sys.stdin.fileno() - try: - while not _stop_reader.is_set(): - try: - ch = os.read(fd, 1) - except OSError as ex: - if ex.errno == errno.EAGAIN: - time.sleep(0.05) - continue - break - if ch == b"\x10": - os.kill(os.getpid(), signal.SIGUSR1) - except OSError: - pass + _reader = keys.RawReader(_on_pause_key) + _reader.start() + + +def _on_pause_key(ch): + if ch == 0x10: + ipc.dispatch("pause") def _restore_pause_input(): - global _original_term, _reader_thread - _stop_reader.set() - if _reader_thread and _reader_thread.is_alive(): - _reader_thread.join(timeout=0.2) - _reader_thread = None - if _original_term is not None: - try: - fd = sys.stdin.fileno() - flags = fcntl.fcntl(fd, fcntl.F_GETFL) - fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK) - termios.tcsetattr(fd, termios.TCSADRAIN, _original_term) - except termios.error, OSError: - pass - _original_term = None + global _reader + if _reader is not None: + _reader.stop() + _reader = None def _flags_str(args): @@ -282,7 +265,9 @@ def _display_loop( ): global _paused display = config.Display - if display in ("bars", "progress") and not ( + if display == "bars" and (curses is None or not platform.is_linux()): + display = "none" + if display in ("bars", "progress", "rich") and not ( sys.stdin.isatty() and sys.stdout.isatty() ): display = "none" @@ -312,7 +297,8 @@ def _display_loop( shuffle = bool(getattr(args, "shuffle", False)) repeat = bool(getattr(args, "repeat", False)) visualizer.set_status( - title, shuffle=shuffle, repeat=repeat, next_title=next_title + title, shuffle=shuffle, repeat=repeat, next_title=next_title, + artist=artist, album=album, ) fetched_lyrics = None @@ -344,6 +330,12 @@ def _display_loop( last_lyric_line = None paused_printed = False + rich_disp = None + if display == "rich": + rich_disp = rich_display.NowPlaying( + title, artist=artist, album=album, duration=duration + ) + rich_disp.start() try: while player.get_state() not in (vlc.State.Ended, vlc.State.Error): if stop_check and stop_check(): @@ -364,6 +356,11 @@ def _display_loop( stdscr.refresh() except curses.error: pass + elif display == "rich": + if rich_disp: + rich_disp.update( + max(0.0, player.get_time() / 1000.0), paused=True + ) else: sys.stdout.write(f"\r {T}[Paused]{R} ") sys.stdout.flush() @@ -382,6 +379,9 @@ def _display_loop( _tick_position(player, elapsed) if display == "bars": visualizer.draw() + elif display == "rich": + if rich_disp: + rich_disp.update(elapsed, _paused) elif display == "progress": config.render_progress(elapsed, duration) elif display == "lyrics" and fetched_lyrics: @@ -398,6 +398,8 @@ def _display_loop( except OSError: pass finally: + if rich_disp is not None: + rich_disp.stop() if display == "bars": visualizer.stop() curses.nocbreak() @@ -438,6 +440,7 @@ def play_url( media = instance.media_new(url) _player.set_media(media) _player.play() + _install_controls() _setup_pause_input() config.dev_print( @@ -454,13 +457,6 @@ def play_url( status.update(title, duration, thumbnail=thumbnail) dur_min, dur_sec = divmod(int(duration), 60) flags = _flags_str(args) - i(f"\n[⥤ Now : {_truncate_title(title)}]") - m( - f" [{dur_min}:{dur_sec:02d}] {flags}" - if flags - else f" [{dur_min}:{dur_sec:02d}]" - ) - artist = "" album = "" if entry: @@ -468,6 +464,17 @@ def play_url( if primary: artist = primary[0].get("name", "") or "" album = (entry.get("album") or {}).get("name") or "" + if config.Display != "bars": + i(f"\n[⥤ Now : {_truncate_title(title)}]") + if artist: + m(f" {artist}") + if album: + m(f" {album}") + m( + f" [{dur_min}:{dur_sec:02d}] {flags}" + if flags + else f" [{dur_min}:{dur_sec:02d}]" + ) # JioSaavn tracks have no YouTube id; namespace the song id so it can # never collide with a real video id in the library. savan_id = (entry or {}).get("id") or "" @@ -545,6 +552,7 @@ def play_entry(entry, title, args=None, flags=None, next_title=None, nav=None): _player.set_media(media) _player.play() + _install_controls() _setup_pause_input() skip_thread = None try: @@ -571,13 +579,6 @@ def play_entry(entry, title, args=None, flags=None, next_title=None, nav=None): status.update(title, duration, thumbnail=thumb) dur_min, dur_sec = divmod(int(duration), 60) fstr = _flags_str(args) - i(f"\n[⥤ Now : {_truncate_title(title)}]") - m( - f" [{dur_min}:{dur_sec:02d}] {fstr}" - if fstr - else f" [{dur_min}:{dur_sec:02d}]" - ) - artist = "" album = "" if video_id: @@ -589,6 +590,17 @@ def play_entry(entry, title, args=None, flags=None, next_title=None, nav=None): artist = entry.get("artist") or "" if not album: album = entry.get("album") or "" + if config.Display != "bars": + i(f"\n[⥤ Now : {_truncate_title(title)}]") + if artist: + m(f" {artist}") + if album: + m(f" {album}") + m( + f" [{dur_min}:{dur_sec:02d}] {fstr}" + if fstr + else f" [{dur_min}:{dur_sec:02d}]" + ) history.record_play( video_id or "", title, artist, mode="online", duration=duration ) diff --git a/backend/Online/youtube.py b/backend/Online/youtube.py index c72352c..6e61dae 100644 --- a/backend/Online/youtube.py +++ b/backend/Online/youtube.py @@ -4,7 +4,7 @@ import yt_dlp -from backend import config, library, sponsor +from backend import config, library, rich_display, sponsor logger = logging.getLogger(__name__) @@ -104,6 +104,9 @@ def progress_hook(d): if total <= 0: return pct = got / total * 100 + if rich_display.active(): + rich_display.download_update(got, total) + return title = (d.get("info_dict") or {}).get("title", "") or "" if len(title) > 26: title = title[:25] + "…" @@ -118,6 +121,7 @@ def download_url(url, outdir, fmt=None, progress=False): opts = {**ydl_opts_dwn, "outtmpl": f"{outdir}/%(id)s.%(ext)s"} if progress and sys.stdout.isatty(): opts["progress_hooks"] = [progress_hook] + rich_display.download_start() pps = sponsor.download_postprocessors() if fmt and fmt != "webm": pps = pps + [{"key": "FFmpegExtractAudio", "preferredcodec": fmt}] @@ -131,9 +135,11 @@ def download_url(url, outdir, fmt=None, progress=False): stem = pathlib.Path(filename).stem filename = str(pathlib.Path(outdir) / f"{stem}.{fmt}") except Exception as exc: + rich_display.download_stop() logger.warning("Download failed for %s: %s", url, exc) config.down_notify(url, error=True) raise + rich_display.download_stop() if opts.get("progress_hooks"): sys.stdout.write("\r" + " " * 60 + "\r") sys.stdout.flush() diff --git a/backend/config.py b/backend/config.py index 2dd916f..8002501 100644 --- a/backend/config.py +++ b/backend/config.py @@ -9,14 +9,18 @@ CONFIG_FILE = pathlib.Path.home() / ".flow/config.json" -SIG_STOP = _signal.SIGUSR1 -SIG_NEXT = _signal.SIGUSR2 -SIG_PREV = _signal.SIGRTMIN + 2 -SIG_SEEK_FWD = _signal.SIGRTMIN + 3 -SIG_SEEK_BWD = _signal.SIGRTMIN + 4 -SIG_REPEAT = _signal.SIGRTMIN + 5 -SIG_SHUFFLE = _signal.SIGRTMIN + 6 -SIG_STOP_ALL = _signal.SIGRTMIN + 7 +SIG_STOP = getattr(_signal, "SIGUSR1", None) +SIG_NEXT = getattr(_signal, "SIGUSR2", None) +if hasattr(_signal, "SIGRTMIN"): + SIG_PREV = _signal.SIGRTMIN + 2 + SIG_SEEK_FWD = _signal.SIGRTMIN + 3 + SIG_SEEK_BWD = _signal.SIGRTMIN + 4 + SIG_REPEAT = _signal.SIGRTMIN + 5 + SIG_SHUFFLE = _signal.SIGRTMIN + 6 + SIG_STOP_ALL = _signal.SIGRTMIN + 7 +else: + SIG_PREV = SIG_SEEK_FWD = SIG_SEEK_BWD = None + SIG_REPEAT = SIG_SHUFFLE = SIG_STOP_ALL = None _FLAG_MAP = {"-bg": "bg", "-s": "shuffle", "-d": "download", "-m": "multi"} @@ -59,56 +63,130 @@ def merge_flags(extra: list[str], args) -> tuple[list[str], object]: return rest, args -RED = "\033[0;31m" -GREEN = "\033[0;32m" -BROWN = "\033[0;33m" -BLUE = "\033[0;34m" -PURPLE = "\033[0;35m" -CYAN = "\033[0;36m" -GREY = "\033[90m" -YELLOW = "\033[1;33m" -WHITE = "\033[1;37m" -MAROON = "\033[38;5;124m" -OLIVE = "\033[38;5;100m" -DARK_KHAKI = "\033[38;5;136m" -GOLD = "\033[38;5;220m" -TAN = "\033[38;5;215m" -SALMON = "\033[38;5;209m" -CORAL = "\033[38;5;203m" -HOT_PINK = "\033[38;5;205m" -VIOLET = "\033[38;5;141m" -DEEP_PURPLE = "\033[38;5;129m" -TEAL = "\033[38;5;30m" -SKY_BLUE = "\033[38;5;117m" -STEEL_BLUE = "\033[38;5;67m" -NAVY = "\033[38;5;18m" -INDIGO = "\033[38;5;54m" -ORANGE = "\033[38;5;202m" -PINK = "\033[38;5;205m" -LIME = "\033[38;5;154m" -Reset = "\033[0m" +try: + from rich.color import ANSI_COLOR_NAMES + from rich.console import Console as _RichConsole + from rich.style import Style as _RichStyle -_COLORS = { - k.lower().replace("_", ""): v - for k, v in vars().items() - if isinstance(v, str) and v.startswith("\033") and k != "Reset" -} + _FORCE = _RichConsole( + force_terminal=True, color_system="truecolor", legacy_windows=False + ) + _HAS_RICH = True +except Exception: + ANSI_COLOR_NAMES = {} + _FORCE = None + _RichStyle = None + _HAS_RICH = False + + +def _sgr(style): + """Render a rich style string to its ANSI SGR prefix.""" + if not _HAS_RICH: + return "" + try: + with _FORCE.capture() as cap: + _FORCE.print("\u2593", style=str(style), end="") + out = cap.get() + if out.endswith("\x1b[0m"): + out = out[:-4] + if out.endswith("\u2593"): + out = out[:-1] + return out + except Exception: + return "" -_COLOR_NAMES = {v: k for k, v in _COLORS.items()} + +def _valid_style(value): + """True when `value` is a parseable rich style (named color, #hex, rgb(), ...).""" + if not _HAS_RICH: + return str(value).lower() in ( + "red", + "green", + "yellow", + "blue", + "purple", + "cyan", + "grey", + "white", + "black", + "orange", + "pink", + ) + try: + _RichStyle.parse(str(value)) + return True + except Exception: + return False + + +RICH_COLORS = sorted(ANSI_COLOR_NAMES) + +RED = _sgr("red") +GREEN = _sgr("green") +BROWN = _sgr("dark_goldenrod") +BLUE = _sgr("blue") +PURPLE = _sgr("purple") +CYAN = _sgr("cyan") +GREY = _sgr("grey62") +YELLOW = _sgr("bold yellow") +WHITE = _sgr("bold white") +MAROON = _sgr("red3") +OLIVE = _sgr("yellow4") +DARK_KHAKI = _sgr("dark_khaki") +GOLD = _sgr("gold1") +TAN = _sgr("tan") +SALMON = _sgr("salmon1") +CORAL = _sgr("orange_red1") +HOT_PINK = _sgr("hot_pink") +VIOLET = _sgr("violet") +DEEP_PURPLE = _sgr("purple3") +TEAL = _sgr("dark_cyan") +SKY_BLUE = _sgr("light_sky_blue1") +STEEL_BLUE = _sgr("steel_blue") +NAVY = _sgr("navy_blue") +INDIGO = _sgr("purple4") +ORANGE = _sgr("orange1") +PINK = _sgr("pink1") +LIME = _sgr("spring_green3") +Reset = "\033[0m" _TARGET_ALIASES = { "pri": "primary", "sec": "secondary", "ter": "tertiary", "spin": "spinner", + "richcols": "progress_columns", + "rich_columns": "progress_columns", + "progtype": "progress_type", + "richspin": "rich_spinner", + "rich_spin": "rich_spinner", } -_TARGETS = {"primary", "secondary", "tertiary", "display"} -_DISPLAY_MODES = {"none", "bars", "lyrics", "progress"} +_TARGETS = { + "primary", + "secondary", + "tertiary", + "display", + "progress_columns", + "progress_type", + "rich_spinner", +} +_DISPLAY_MODES = {"none", "bars", "lyrics", "progress", "rich"} _BAR_SPACING = {"min", "fit", "max"} -Primary = CYAN -Secondary = PURPLE -Tertiary = BLUE +_STYLE = {"primary": "cyan", "secondary": "purple", "tertiary": "blue"} + + +def _render(): + """Recompute Primary/Secondary/Tertiary ANSI from the chosen rich styles.""" + global Primary, Secondary, Tertiary + Primary = _sgr(_STYLE["primary"]) or CYAN + Secondary = _sgr(_STYLE["secondary"]) or PURPLE + Tertiary = _sgr(_STYLE["tertiary"]) or BLUE + + +Primary = _sgr("cyan") +Secondary = _sgr("purple") +Tertiary = _sgr("blue") Muted = GREY Display = "bars" BarWidth = 20 @@ -119,14 +197,37 @@ def merge_flags(extra: list[str], args) -> tuple[list[str], object]: ProgCharEm = "\u2591" Sensitivity = 1.0 SPINNER = "|/-\\" +RichSpinner = "dots" +ProgressType = "default" +ProgressColumns = ["bar", "percentage", "time_remaining"] + +_PROGRESS_TYPES = { + "default": ["bar", "percentage", "time_remaining"], + "download": ["download", "file_size", "total_size", "transfer_speed"], + "pulse": ["spinner"], +} + +_RICH_COLUMN_NAMES = ( + "bar", + "download", + "file_size", + "m_of_n", + "percentage", + "spinner", + "task", + "time_elapsed", + "time_remaining", + "total_size", + "transfer_speed", +) THEMES = { "ocean": ("cyan", "purple", "blue"), - "sunset": ("orange", "pink", "gold"), - "forest": ("green", "lime", "teal"), - "fire": ("red", "orange", "gold"), - "mono": ("grey", "white", "maroon"), - "royal": ("indigo", "violet", "skyblue"), + "sunset": ("orange1", "pink1", "gold1"), + "forest": ("green", "spring_green3", "dark_cyan"), + "fire": ("red", "orange1", "gold1"), + "mono": ("grey62", "white", "red3"), + "royal": ("purple4", "violet", "light_sky_blue1"), } ####### Be carefull this will make everything print on screen including links title view and all things ### @@ -495,12 +596,51 @@ def _strip_filler(text): return text +_TILE_CONTEXTS: dict = {} + + +def _tile_context(): + """Tile's junk/artist rules plus flow's `~/.flow/ignore.txt` words (cached).""" + from Tile import ( + DEFAULT_ARTIST_FILE, + DEFAULT_IGNORE_FILE, + Context, + get_context, + ) + + def mtime(path): + try: + return path.stat().st_mtime_ns + except OSError: + return -1 + + key = ( + str(IGNORE_FILE), + mtime(IGNORE_FILE), + str(DEFAULT_IGNORE_FILE), + mtime(DEFAULT_IGNORE_FILE), + str(DEFAULT_ARTIST_FILE), + mtime(DEFAULT_ARTIST_FILE), + ) + if key not in _TILE_CONTEXTS: + tile = get_context(DEFAULT_IGNORE_FILE, DEFAULT_ARTIST_FILE) + flow = get_context(IGNORE_FILE, DEFAULT_ARTIST_FILE) + _TILE_CONTEXTS.clear() + _TILE_CONTEXTS[key] = Context( + strip_words=tile.strip_words | flow.strip_words, + soft_words=tile.soft_words | flow.soft_words, + phrases=tile.phrases | flow.phrases, + artists=tile.artists, + labels=tile.labels, + ) + return _TILE_CONTEXTS[key] + + def extract_song(title): - for segment in _PIPE.split(title): - parts = [p for p in map(_strip_filler, _DASH.split(segment)) if p] - if parts: - return parts[1] if len(parts) > 1 else parts[0] - return "" + """The song name from a raw title, parsed by the Tile package.""" + from Tile import parse_title + + return parse_title(title or "", _tile_context())["title"] def _truncate_title(title): @@ -523,6 +663,8 @@ def _load_config(): ProgCharEm, \ Sensitivity, \ SPINNER, \ + RichSpinner, \ + ProgressType, \ DEV_MODE, \ FFMPEG, \ _ffmpeg_configured, \ @@ -532,19 +674,34 @@ def _load_config(): DOWN_ON_LIKE, \ MAX_SEARCH_RESULTS, \ MAX_RESULTS_RADIO, \ - NOTIFY + NOTIFY, \ + ProgressColumns if not CONFIG_FILE.exists(): return try: data = json.loads(CONFIG_FILE.read_text()) - if "primary" in data and data["primary"] in _COLORS: - Primary = _COLORS[data["primary"]] - if "secondary" in data and data["secondary"] in _COLORS: - Secondary = _COLORS[data["secondary"]] - if "tertiary" in data and data["tertiary"] in _COLORS: - Tertiary = _COLORS[data["tertiary"]] + if "primary" in data and _valid_style(data["primary"]): + _STYLE["primary"] = str(data["primary"]) + if "secondary" in data and _valid_style(data["secondary"]): + _STYLE["secondary"] = str(data["secondary"]) + if "tertiary" in data and _valid_style(data["tertiary"]): + _STYLE["tertiary"] = str(data["tertiary"]) + _render() if "display" in data and data["display"] in _DISPLAY_MODES: Display = data["display"] + if "progress_columns" in data and isinstance(data["progress_columns"], list): + cols = [ + c + for c in data["progress_columns"] + if isinstance(c, str) and c in _RICH_COLUMN_NAMES + ] + if cols: + ProgressColumns = cols + if "progress_type" in data and data["progress_type"] in _PROGRESS_TYPES: + ProgressType = data["progress_type"] + ProgressColumns = list(_PROGRESS_TYPES[ProgressType]) + elif "progress_type" in data and data["progress_type"] == "custom": + ProgressType = "custom" if ( "bar_width" in data and isinstance(data["bar_width"], int) @@ -595,6 +752,12 @@ def _load_config(): and 2 <= len(data["spinner"]) <= 16 ): SPINNER = data["spinner"] + if ( + "rich_spinner" in data + and isinstance(data["rich_spinner"], str) + and data["rich_spinner"] + ): + RichSpinner = data["rich_spinner"][:16] if "dev" in data and isinstance(data["dev"], bool): DEV_MODE = data["dev"] if "ffmpeg" in data and isinstance(data["ffmpeg"], bool): @@ -633,10 +796,12 @@ def _load_config(): def _save_config(): CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True) data = { - "primary": _COLOR_NAMES.get(Primary, "cyan"), - "secondary": _COLOR_NAMES.get(Secondary, "purple"), - "tertiary": _COLOR_NAMES.get(Tertiary, "blue"), + "primary": _STYLE["primary"], + "secondary": _STYLE["secondary"], + "tertiary": _STYLE["tertiary"], "display": Display, + "progress_columns": ProgressColumns, + "progress_type": ProgressType, "bar_width": BarWidth, "bar_height": BarHeight, "bar_spacing": BarSpacing, @@ -645,6 +810,7 @@ def _save_config(): "prog_char_em": ProgCharEm, "sensitivity": Sensitivity, "spinner": SPINNER, + "rich_spinner": RichSpinner, "dev": DEV_MODE, "ffmpeg": FFMPEG, "ad_skip": AD_SKIP, @@ -666,7 +832,7 @@ def _save_config(): VERSION = _version("flow-twinx") except PackageNotFoundError: - VERSION = "0.5.1" + VERSION = "0.8.4" Mode = "Online" @@ -694,12 +860,12 @@ def clear_seek(): SEEK_FILE.unlink(missing_ok=True) -def save_pid(pid: int): +def save_pid(pid: int, ctl_port: int | None = None): PID_FILE.parent.mkdir(parents=True, exist_ok=True) PID_FILE.write_text(str(pid)) from backend import registry - registry.register("vlc", pid) + registry.register("vlc", pid, ctl_port=ctl_port) def read_pid() -> int | None: @@ -719,12 +885,12 @@ def clear_pid(): registry.unregister("vlc") -def save_tui_pid(pid: int): +def save_tui_pid(pid: int, ctl_port: int | None = None): TUI_PID_FILE.parent.mkdir(parents=True, exist_ok=True) TUI_PID_FILE.write_text(str(pid)) from backend import registry - registry.register("tui", pid) + registry.register("tui", pid, ctl_port=ctl_port) def read_tui_pid() -> int | None: @@ -744,7 +910,7 @@ def clear_tui_pid(): registry.unregister("tui") -def save_pid_if_free(pid: int) -> bool: +def save_pid_if_free(pid: int, ctl_port: int | None = None) -> bool: """Claim the player pid slot unless another live player already holds it.""" existing = read_pid() if existing is not None and existing != pid: @@ -755,7 +921,10 @@ def save_pid_if_free(pid: int) -> bool: return False except Exception: pass - save_pid(pid) + if ctl_port is not None: + save_pid(pid, ctl_port=ctl_port) + else: + save_pid(pid) return True @@ -772,16 +941,12 @@ def clear_tui_pid_if(pid: int): def kill_stored(): - import os - import signal + from backend import platform pid = read_pid() if pid is None: return False - try: - os.kill(pid, signal.SIGTERM) - except ProcessLookupError: - pass + platform.kill_pid(pid) clear_pid() return True @@ -790,16 +955,13 @@ def kill_stored(): def _apply_color(which, value): - global Primary, Secondary, Tertiary - color = _COLORS.get(value) - if color is None: - return f"Unknown color '{value}'. Use 'config -h' to see available colors." - if which == "primary": - Primary = _COLORS[value] - elif which == "secondary": - Secondary = _COLORS[value] - else: - Tertiary = _COLORS[value] + if not _valid_style(value): + return ( + f"Unknown color '{value}'. Any rich style works: a named color, " + "#hex, rgb(r,g,b), bold/italic." + ) + _STYLE[which] = str(value) + _render() _save_config() code = {"primary": Primary, "secondary": Secondary, "tertiary": Tertiary}[which] return f"{code}{which.capitalize()} color changed to {value}{Reset}" @@ -808,12 +970,25 @@ def _apply_color(which, value): def _apply_display(value): global Display if value not in _DISPLAY_MODES: - return f"Unknown display mode '{value}'. Options: none, bars, lyrics, progress" + return f"Unknown display mode '{value}'. Options: none, bars, lyrics, progress, rich" Display = value _save_config() return f"{Tertiary}Display mode changed to {value}{Reset}" +def _apply_progress_columns(value): + global ProgressColumns, ProgressType + parts = [p.strip().lower() for p in re.split(r"[,\s]+", str(value)) if p.strip()] + if not parts or any(p not in _RICH_COLUMN_NAMES for p in parts): + return ( + f"Unknown progress column(s). Rich options: {', '.join(_RICH_COLUMN_NAMES)}" + ) + ProgressColumns = parts + ProgressType = "custom" + _save_config() + return f"{Tertiary}Rich progress columns set to {', '.join(parts)}{Reset}" + + def _apply_bar_width(v): global BarWidth BarWidth = v @@ -859,8 +1034,6 @@ def _apply_prog_char_em(v): return f"{Tertiary}Progress empty char changed to {ProgCharEm}{Reset}" -import shutil - MIN_BAR = 8 @@ -926,16 +1099,58 @@ def _apply_spinner(value): return f"{Tertiary}Spinner set to '{value}'{Reset}" +def rich_spinner_names(): + """Every spinner name rich knows (the `python -m rich.spinner` list).""" + try: + from rich.spinner import SPINNERS + + return sorted(SPINNERS) + except Exception: + return [] + + +def _spinner_choices(): + """Rich spinner picker options: every name plus the custom escape hatch.""" + return rich_spinner_names() + ["Custom…"] + + +def _apply_rich_spinner(value): + global RichSpinner + name = str(value).strip() + if not (1 <= len(name) <= 16): + return "Rich spinner must be a name or 1-16 characters" + RichSpinner = name + _save_config() + return f"{Tertiary}Rich spinner set to '{name}'{Reset}" + + +def _apply_progress_type(value): + global ProgressType, ProgressColumns + key = str(value).strip().lower() + if key == "custom": + ProgressType = "custom" + _save_config() + return f"{Tertiary}Progress type set to custom (edit the columns as you like){Reset}" + cols = _PROGRESS_TYPES.get(key) + if cols is None: + return ( + f"Unknown progress type '{value}'. Options: " + f"{', '.join(sorted(_PROGRESS_TYPES))}, custom" + ) + ProgressType = key + ProgressColumns = list(cols) + _save_config() + return f"{Tertiary}Progress type changed to {key} ({', '.join(cols)}){Reset}" + + def _apply_theme(name): - global Primary, Secondary, Tertiary if name == "list": return f"{Muted}Themes: {', '.join(sorted(THEMES))}{Reset}" trio = THEMES.get(name.lower()) if trio is None: return f"Unknown theme '{name}'. Themes: {', '.join(sorted(THEMES))}" - Primary = _COLORS[trio[0]] - Secondary = _COLORS[trio[1]] - Tertiary = _COLORS[trio[2]] + _STYLE["primary"], _STYLE["secondary"], _STYLE["tertiary"] = trio + _render() _save_config() return f"{Tertiary}Theme changed to '{name}'{Reset}" @@ -957,7 +1172,10 @@ def _apply_format(value): "tertiary", "theme", "spinner", + "rich_spinner", "display", + "progress_columns", + "progress_type", "barwidth", "barheight", "barspacing", @@ -983,6 +1201,10 @@ def apply_config(key, value): return _apply_theme(value) if target == "spinner": return _apply_spinner(value) + if target == "rich_spinner": + return _apply_rich_spinner(value) + if target == "progress_type": + return _apply_progress_type(value) if target == "primary": return _apply_color("primary", value) if target == "secondary": @@ -991,6 +1213,8 @@ def apply_config(key, value): return _apply_color("tertiary", value) if target == "display": return _apply_display(value) + if target == "progress_columns": + return _apply_progress_columns(value) if target in ("barwidth", "width"): return _apply_int("BarWidth", value, 4, 80, "Bar width changed") if target in ("barheight", "height"): @@ -1043,11 +1267,7 @@ def apply_config(key, value): def _current_theme(): - cur = ( - _COLOR_NAMES.get(Primary), - _COLOR_NAMES.get(Secondary), - _COLOR_NAMES.get(Tertiary), - ) + cur = (_STYLE["primary"], _STYLE["secondary"], _STYLE["tertiary"]) for name, trio in THEMES.items(): if tuple(trio) == cur: return name @@ -1057,12 +1277,15 @@ def _current_theme(): def config_get(key): target = _TARGET_ALIASES.get(key.lower(), key.lower()) getters = { - "primary": lambda: _COLOR_NAMES.get(Primary), - "secondary": lambda: _COLOR_NAMES.get(Secondary), - "tertiary": lambda: _COLOR_NAMES.get(Tertiary), + "primary": lambda: _STYLE["primary"], + "secondary": lambda: _STYLE["secondary"], + "tertiary": lambda: _STYLE["tertiary"], "theme": _current_theme, "spinner": lambda: SPINNER, + "rich_spinner": lambda: RichSpinner, "display": lambda: Display, + "progress_columns": lambda: ProgressColumns, + "progress_type": lambda: ProgressType, "barwidth": lambda: BarWidth, "barheight": lambda: BarHeight, "barspacing": lambda: BarSpacing, @@ -1122,7 +1345,15 @@ def cmd_config(extra: list[str], args=None): print(f" {Primary}primary{Reset} (aliases: pri)") print(f" {Secondary}secondary{Reset} (aliases: sec)") print(f" {Tertiary}tertiary{Reset} (aliases: ter)") - print(f" {GREY}display{Reset} (none, bars, lyrics)") + print(f" {GREY}display{Reset} (none, bars, lyrics, progress, rich)") + print( + f" {GREY}progress_columns{Reset} (rich progress bar columns — " + f"{', '.join(_RICH_COLUMN_NAMES)}; aliases: richcols, rich_columns)" + ) + print( + f" {GREY}progress_type{Reset} (rich progress layout — default, download, " + f"pulse, custom; current: {ProgressType})" + ) print(f" {GREY}barwidth{Reset} (4-80, current: {BarWidth})") print(f" {GREY}barheight{Reset} (10-90, current: {BarHeight})") print(f" {GREY}barspacing{Reset} (0-4, min, fit, max — current: {BarSpacing})") @@ -1139,7 +1370,11 @@ def cmd_config(extra: list[str], args=None): print( f" {GREY}theme{Reset} (ocean, sunset, forest, fire, mono, royal — or 'list')" ) - print(f" {GREY}spinner{Reset} (2-16 chars, current: {SPINNER})") + print( + f" {GREY}rich_spinner{Reset} (rich spinner — a name from `python -m " + f"rich.spinner`, or 1-16 custom chars; current: {RichSpinner})" + ) + print(f" {GREY}spinner{Reset} (2-16 chars, plain-text spinner, current: {SPINNER})") print(f" {GREY}format{Reset} (opus, m4a, mp3, webm — current: {FORMAT})") print( f" {GREY}ad_skip{Reset} (true/false — SponsorBlock segment skipping, current: {AD_SKIP})" @@ -1155,9 +1390,11 @@ def cmd_config(extra: list[str], args=None): ) print(f" {GREY}max_search{Reset} (1-20, current: {MAX_SEARCH_RESULTS})") print(f" {GREY}max_radio{Reset} (1-50, current: {MAX_RESULTS_RADIO})") - print(f"\n{Tertiary}Available colors:{Reset}") - for name, code in _COLORS.items(): - print(f" {code}{name}{Reset}") + print( + f"\n{Tertiary}Available colors (any rich style: named color, #hex, rgb(r,g,b), bold/italic):{Reset}" + ) + for name in RICH_COLORS: + print(f" {_sgr(name)}{name}{Reset}") print(f"\n{GREY}Config file: {CONFIG_FILE}{Reset}") return if not extra: @@ -1180,6 +1417,12 @@ def emit(msg): emit(_apply_color("tertiary", value)) elif target == "display": emit(_apply_display(value)) + elif target == "progress_columns": + emit(_apply_progress_columns(value)) + elif target == "progress_type": + emit(_apply_progress_type(value)) + elif target in ("rich_spinner", "richspin", "rich_spin"): + emit(_apply_rich_spinner(value)) elif target in ("barwidth", "width"): print(_apply_int("BarWidth", value, 4, 80, "Bar width changed")) elif target in ("barheight", "height"): @@ -1256,7 +1499,17 @@ def notify(title, body=""): if not NOTIFY: return try: - subprocess.run(["notify-send", title, body], check=False) + if sys.platform == "darwin": + subprocess.run( + [ + "osascript", + "-e", + f'display notification "{body}" with title "{title}"', + ], + check=False, + ) + elif os.name != "nt": + subprocess.run(["notify-send", title, body], check=False) except OSError: pass @@ -1268,8 +1521,238 @@ def down_notify(song_name, error=False): notify("Downloaded Song", f"song: {song_name}") +def _apply_bool(attr, ok_msg, v): + globals()[attr] = bool(v) + _save_config() + return f"{Tertiary}{ok_msg} {v}{Reset}" + + +def _apply_sensitivity_io(v): + try: + val = float(v) + except ValueError: + return "sensitivity must be a number (0.5-5.0)" + if not (0.5 <= val <= 5.0): + return "sensitivity must be between 0.5 and 5.0" + return _apply_sensitivity(val) + + +def _apply_bar_spacing_io(v): + s = str(v).strip().lower() + if s in _BAR_SPACING: + return _apply_bar_spacing(s) + try: + return _apply_bar_spacing(int(s)) + except ValueError: + return "bar_spacing must be min/fit/max or 0-4" + + +def _interactive_rows(): + if Display == "rich": + spinner_row = ( + "spinner", + "Spinner", + lambda: RichSpinner, + "select", + _spinner_choices(), + lambda v: _apply_rich_spinner(v) if v != "Custom…" else None, + ) + else: + spinner_row = ( + "spinner", + "Spinner", + lambda: SPINNER, + "text", + None, + _apply_spinner, + ) + rows = [ + ( + "display", + "Display mode", + lambda: Display, + "select", + ["none", "bars", "lyrics", "progress", "rich"], + lambda v: _apply_display(str(v)), + ), + ( + "primary", + "Primary color", + lambda: _STYLE["primary"], + "select", + RICH_COLORS, + lambda v: _apply_color("primary", str(v)), + ), + ( + "secondary", + "Secondary color", + lambda: _STYLE["secondary"], + "select", + RICH_COLORS, + lambda v: _apply_color("secondary", str(v)), + ), + ( + "tertiary", + "Tertiary color", + lambda: _STYLE["tertiary"], + "select", + RICH_COLORS, + lambda v: _apply_color("tertiary", str(v)), + ), + ( + "theme", + "Color theme", + _current_theme, + "select", + sorted(THEMES), + lambda v: _apply_theme(str(v)), + ), + spinner_row, + ( + "progress_type", + "Progress type", + lambda: ProgressType, + "select", + sorted(_PROGRESS_TYPES) + ["custom"], + _apply_progress_type, + ), + ( + "progress_columns", + "Rich progress columns", + lambda: ", ".join(ProgressColumns), + "text", + None, + lambda v: _apply_progress_columns(str(v)), + ), + ( + "format", + "Default download format", + lambda: FORMAT, + "select", + sorted(_VALID_FORMATS), + lambda v: _apply_format(str(v)), + ), + ( + "bar_width", + "Bar width (4-80)", + lambda: BarWidth, + "text", + None, + lambda v: _apply_int("BarWidth", v, 4, 80, "Bar width changed"), + ), + ( + "bar_height", + "Bar height (10-90)", + lambda: BarHeight, + "text", + None, + lambda v: _apply_int("BarHeight", v, 10, 90, "Bar height changed"), + ), + ( + "bar_spacing", + "Bar spacing", + lambda: BarSpacing, + "select", + ["min", "fit", "max", "0", "1", "2", "3", "4"], + _apply_bar_spacing_io, + ), + ( + "bar_char", + "Bar char", + lambda: _BC_NAME(BarChar), + "text", + None, + _apply_bar_char, + ), + ( + "prog_char", + "Progress bar fill char", + lambda: _BC_NAME(ProgChar), + "text", + None, + _apply_prog_char, + ), + ( + "prog_char_em", + "Progress bar empty char", + lambda: _BC_NAME(ProgCharEm), + "text", + None, + _apply_prog_char_em, + ), + ( + "sensitivity", + "Sensitivity (0.5-5.0)", + lambda: Sensitivity, + "text", + None, + _apply_sensitivity_io, + ), + ( + "ad_skip", + "Ad skip", + lambda: AD_SKIP, + "confirm", + None, + lambda v: _apply_bool("AD_SKIP", "Ad skip set to", v), + ), + ( + "down_on_like", + "Auto-download on like", + lambda: DOWN_ON_LIKE, + "confirm", + None, + lambda v: _apply_bool("DOWN_ON_LIKE", "Auto-download on like set to", v), + ), + ( + "notify", + "Desktop notifications", + lambda: NOTIFY, + "confirm", + None, + lambda v: _apply_bool("NOTIFY", "Desktop notifications set to", v), + ), + ( + "max_search", + "Max search results (1-20)", + lambda: MAX_SEARCH_RESULTS, + "text", + None, + lambda v: _apply_int( + "MAX_SEARCH_RESULTS", v, 1, 20, "Max search results changed" + ), + ), + ( + "max_radio", + "Max radio tracks (1-50)", + lambda: MAX_RESULTS_RADIO, + "text", + None, + lambda v: _apply_int( + "MAX_RESULTS_RADIO", v, 1, 50, "Max radio tracks changed" + ), + ), + ] + if Display == "rich": + rows = [ + r + for r in rows + if r[0] + not in ( + "bar_width", + "bar_height", + "bar_spacing", + "bar_char", + "prog_char", + "prog_char_em", + ) + ] + else: + rows = [r for r in rows if r[0] not in ("progress_columns", "progress_type")] + return rows + + def _interactive_config(): - global AD_SKIP, DOWN_ON_LIKE try: import questionary from questionary import Style @@ -1281,266 +1764,108 @@ def _interactive_config(): ) return - color_names = sorted(_COLORS.keys()) - color_choices = [questionary.Choice(title=n, value=n) for n in color_names] py_style = Style( [ - ("qmark", f"fg:{_cname(Tertiary)}"), - ("question", f"fg:{_cname(Tertiary)}"), - ("answer", f"fg:{_cname(Secondary)} bold"), - ("pointer", f"fg:{_cname(Primary)} bold"), - ("highlighted", f"fg:{_cname(Primary)} bold"), - ("selected", f"fg:{_cname(Primary)}"), - ("separator", f"fg:{_cname(Muted)}"), - ("instruction", f"fg:{_cname(Tertiary)}"), + ("qmark", f"fg:{_cname(_STYLE['tertiary'])}"), + ("question", f"fg:{_cname(_STYLE['tertiary'])}"), + ("answer", f"fg:{_cname(_STYLE['secondary'])} bold"), + ("pointer", f"fg:{_cname(_STYLE['primary'])} bold"), + ("highlighted", f"fg:{_cname(_STYLE['primary'])} bold"), + ("selected", f"fg:{_cname(_STYLE['primary'])}"), + ("separator", f"fg:{_cname('grey62')}"), + ("instruction", f"fg:{_cname(_STYLE['tertiary'])}"), ("text", ""), ] ) - questions = [ - { - "type": "select", - "name": "display", - "message": "Display mode", - "choices": ["none", "bars", "lyrics", "progress"], - "default": Display, - }, - { - "type": "select", - "name": "primary", - "message": "Primary color", - "choices": color_choices, - "default": _COLOR_NAMES.get(Primary, "cyan"), - }, - { - "type": "select", - "name": "secondary", - "message": "Secondary color", - "choices": color_choices, - "default": _COLOR_NAMES.get(Secondary, "purple"), - }, + rows = _interactive_rows() + screen = [ { "type": "select", - "name": "tertiary", - "message": "Tertiary color", - "choices": color_choices, - "default": _COLOR_NAMES.get(Tertiary, "blue"), - }, - { - "type": "select", - "name": "format", - "message": "Default download format", - "choices": sorted(_VALID_FORMATS), - "default": FORMAT if FORMAT in _VALID_FORMATS else "webm", - }, - { - "type": "text", - "name": "bar_width", - "message": "Bar width (4-80)", - "default": str(BarWidth), - "when": lambda a: a["display"] == "bars", - }, - { - "type": "text", - "name": "bar_height", - "message": "Bar height (10-90)", - "default": str(BarHeight), - "when": lambda a: a["display"] == "bars", - }, - { - "type": "select", - "name": "bar_spacing", - "message": "Bar spacing", - "choices": ["min", "fit", "max", "0", "1", "2", "3", "4"], - "default": str(BarSpacing), - "when": lambda a: a["display"] == "bars", - }, - { - "type": "text", - "name": "bar_char", - "message": "Bar char (dot/block/circle or single char)", - "default": _BC_NAME(BarChar), - "when": lambda a: a["display"] == "bars", - }, - { - "type": "text", - "name": "prog_char", - "message": "Progress bar fill char (dot/block/circle or single char)", - "default": _BC_NAME(ProgChar), - "when": lambda a: a["display"] == "progress", - }, - { - "type": "text", - "name": "prog_char_em", - "message": "Progress bar empty char (dot/block/circle or single char)", - "default": _BC_NAME(ProgCharEm), - "when": lambda a: a["display"] == "progress", - }, - { - "type": "text", - "name": "sensitivity", - "message": "Sensitivity (0.5-5.0)", - "default": str(Sensitivity), - "when": lambda a: a["display"] == "bars", - }, - { - "type": "confirm", - "name": "ad_skip", - "message": "Sponsor segment skipping (ad skip)", - "default": AD_SKIP, - }, - { - "type": "confirm", - "name": "down_on_like", - "message": "Auto-download when liking online", - "default": DOWN_ON_LIKE, - }, - { - "type": "confirm", - "name": "notify", - "message": "Desktop notifications", - "default": NOTIFY, - }, - { - "type": "text", - "name": "max_search", - "message": "Max search results (1-20)", - "default": str(MAX_SEARCH_RESULTS), - }, - { - "type": "text", - "name": "max_radio", - "message": "Max radio tracks (1-50)", - "default": str(MAX_RESULTS_RADIO), - }, + "name": "setting", + "message": "Which setting?", + "choices": [ + questionary.Choice(title=f"{label} (current: {current()})", value=key) + for key, label, current, *_ in rows + ], + } ] - - from questionary.prompts import AVAILABLE_PROMPTS - - answers = {} - interrupted = False - - def _apply_collected(): - global AD_SKIP, DOWN_ON_LIKE - - if "display" in answers: - print(_apply_display(answers["display"])) - if "primary" in answers: - print(_apply_color("primary", answers["primary"])) - if "secondary" in answers: - print(_apply_color("secondary", answers["secondary"])) - if "tertiary" in answers: - print(_apply_color("tertiary", answers["tertiary"])) - - if answers.get("display") == "bars": - if answers.get("bar_width", "").strip(): - try: - v = int(answers["bar_width"]) - if 4 <= v <= 80: - print(_apply_bar_width(v)) - except ValueError: - pass - if answers.get("bar_height", "").strip(): - try: - v = int(answers["bar_height"]) - if 10 <= v <= 90: - print(_apply_bar_height(v)) - except ValueError: - pass - if "bar_spacing" in answers: - try: - val = answers["bar_spacing"] - if str(val) in _BAR_SPACING: - print(_apply_bar_spacing(val)) - else: - print(_apply_bar_spacing(int(val))) - except ValueError: - pass - if "bar_char" in answers: - print(_apply_bar_char(answers["bar_char"])) - if answers.get("sensitivity", "").strip(): - try: - v = float(answers["sensitivity"]) - if 0.5 <= v <= 5.0: - print(_apply_sensitivity(v)) - except ValueError: - pass - if answers.get("display") == "progress": - if "prog_char" in answers: - print(_apply_prog_char(answers["prog_char"])) - if "prog_char_em" in answers: - print(_apply_prog_char_em(answers["prog_char_em"])) - - if "format" in answers: - print(_apply_format(answers["format"])) - if "max_search" in answers: - print( - _apply_int( - "MAX_SEARCH_RESULTS", - answers["max_search"], - 1, - 20, - "Max search results changed", - ) - ) - if "max_radio" in answers: - print( - _apply_int( - "MAX_RESULTS_RADIO", - answers["max_radio"], - 1, - 50, - "Max radio tracks changed", - ) - ) - if "ad_skip" in answers: - AD_SKIP = answers["ad_skip"] - print(f"{Tertiary}Ad skip set to {AD_SKIP}{Reset}") - if "down_on_like" in answers: - DOWN_ON_LIKE = answers["down_on_like"] - print(f"{Tertiary}Auto-download on like set to {DOWN_ON_LIKE}{Reset}") - if "notify" in answers: - NOTIFY = answers["notify"] - print(f"{Tertiary}Desktop notifications set to {NOTIFY}{Reset}") - try: - for question in questions: - cfg = dict(question) - when = cfg.get("when") - if when and not when(answers): - continue - kwargs = {k: v for k, v in cfg.items() if k not in ("type", "name", "when")} - kwargs["style"] = py_style - try: - answer = AVAILABLE_PROMPTS[cfg["type"]](**kwargs).unsafe_ask() - except KeyboardInterrupt, EOFError: - interrupted = True - break - answers[cfg["name"]] = answer - except KeyboardInterrupt: - interrupted = True - + answers = questionary.prompt(screen, style=py_style) + except KeyboardInterrupt, EOFError: + answers = None if not answers: - print(f"\n{GREY}Config setup cancelled. Nothing to save.{Reset}") + print(f"\n{GREY}Config cancelled. Nothing changed.{Reset}") return - if interrupted: - print(f"\n{GREY}Interrupted — saving the answers you already gave...{Reset}") - _apply_collected() - _save_config() - if interrupted: - print( - f"\n{GREY}Config saved (partial — {len(answers)} setting(s) applied).{Reset}" - ) + key = answers["setting"] + row = next((r for r in rows if r[0] == key), None) + if row is None: + return + _, label, current, kind, spec, apply = row + question = {"type": kind, "name": "value", "message": label} + if kind == "select": + question["choices"] = spec or [] + cur = current() + if cur in (spec or []): + question["default"] = cur + elif kind == "confirm": + question["default"] = bool(current()) else: - print(f"\n{GREY}Config saved.{Reset}") + question["default"] = str(current()) + try: + edit = questionary.prompt([question], style=py_style) + except KeyboardInterrupt, EOFError: + edit = None + if not edit or edit.get("value") is None: + print(f"\n{GREY}{label} unchanged.{Reset}") + return + value = edit["value"] + if value == "Custom…": + try: + custom = questionary.prompt( + [ + { + "type": "text", + "name": "value", + "message": "Custom spinner — a rich spinner name or 1-16 characters", + "default": str(current()), + } + ], + style=py_style, + ) + except KeyboardInterrupt, EOFError: + custom = None + if not custom or custom.get("value") is None or not str(custom["value"]).strip(): + print(f"\n{GREY}Spinner unchanged.{Reset}") + return + value = str(custom["value"]).strip() + msg = apply(value) + if msg: + print(msg) -def _cname(ansi_code): - name = _COLOR_NAMES.get(ansi_code, "white") - if name == "deeppurple": # not a valid prompt_toolkit color name - return "darkmagenta" - return name +def _cname(style): + """Last color word of a style, as a prompt_toolkit-friendly hex or name.""" + s = str(style) + if s.startswith("\x1b"): + # ANSI escape code: map back to the chosen rich style string. + resolved = None + for which in ("primary", "secondary", "tertiary"): + if s == _sgr(_STYLE[which]): + resolved = _STYLE[which] + break + s = resolved or "white" + name = s.rsplit(" ", 1)[-1] + try: + from rich.color import Color + + rgb = Color.parse(name).get_truecolor() + if rgb is not None: + return rgb.hex + except Exception: + pass + return name or "white" def _BC_NAME(char): diff --git a/backend/daemon.py b/backend/daemon.py index 1a3d546..d5914aa 100644 --- a/backend/daemon.py +++ b/backend/daemon.py @@ -1,13 +1,14 @@ import json import os import pathlib -import signal import socket +import subprocess import sys import threading import time from backend import config as _colors +from backend import platform from backend.config import GREY, RED, Muted, Primary, Reset E = RED @@ -40,15 +41,7 @@ def is_running() -> bool: def _alive(pid: int) -> bool: - try: - os.kill(pid, 0) - return True - except ProcessLookupError: - return False - except PermissionError: - return True - except OSError: - return False + return platform.pid_exists(pid) def _cleanup_stale(): @@ -67,21 +60,14 @@ def _cleanup_stale(): def stop_signal(pid: int) -> bool: - try: - os.kill(pid, signal.SIGTERM) - except ProcessLookupError: - return False - except OSError: + if not platform.kill_pid(pid): return False for _ in range(50): if not _alive(pid): break time.sleep(0.1) else: - try: - os.kill(pid, signal.SIGKILL) - except OSError: - pass + platform.kill_pid(pid, force=True) return True @@ -125,21 +111,29 @@ def serve(foreground: bool = False) -> int: FLOW_DIR.mkdir(parents=True, exist_ok=True) _cleanup_stale() - server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - try: - server.bind(str(SOCKET_FILE)) - except OSError: - # Socket exists — either stale or a live daemon owns it. - if is_running(): - print(f"{P}Flow daemon is already running{R}") - return 0 - SOCKET_FILE.unlink(missing_ok=True) + if platform.is_windows(): + # Windows has no AF_UNIX daemon socket in this design: bind a + # loopback TCP port and advertise "host:port" in the socket file. + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind(("127.0.0.1", 0)) + SOCKET_FILE.write_text(f"127.0.0.1:{server.getsockname()[1]}") + else: + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: server.bind(str(SOCKET_FILE)) - except OSError as exc: - print(f"{E}Could not bind {SOCKET_FILE}: {exc}{R}") - return 1 - os.chmod(SOCKET_FILE, 0o600) + except OSError: + # Socket exists — either stale or a live daemon owns it. + if is_running(): + print(f"{P}Flow daemon is already running{R}") + return 0 + SOCKET_FILE.unlink(missing_ok=True) + try: + server.bind(str(SOCKET_FILE)) + except OSError as exc: + print(f"{E}Could not bind {SOCKET_FILE}: {exc}{R}") + return 1 + os.chmod(SOCKET_FILE, 0o600) server.listen(32) if not foreground: @@ -214,6 +208,8 @@ def _handle_conn(conn: socket.socket): def _daemonize(): + if not platform.can_fork(): + return if os.fork() > 0: os._exit(0) os.setsid() @@ -233,6 +229,16 @@ def cmd_start(foreground: bool = False) -> int: from backend import registry registry.prune() # drop dead players before we start serving + if not foreground and not platform.can_fork(): + # Windows: relaunch ourselves detached in foreground mode. + platform.spawn_detached( + [sys.executable, "-m", "backend.daemon", "start", "-f"], + env=dict(os.environ), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + return 0 return serve(foreground=foreground) diff --git a/backend/help_detail.py b/backend/help_detail.py index f190a28..11be884 100644 --- a/backend/help_detail.py +++ b/backend/help_detail.py @@ -303,13 +303,14 @@ def _offline_help(): f"{G}Alias:{R} {B}ar{R}", ], "tags": [ - f"{T}> tags{R} {B}[scan | apply]{R}", - f"{G} {B}tags{R} lists the language and artist tags in your library.{R}", - f"{G} {B}tags scan{R} asks YouTube for each downloaded song's metadata and{R}", - f"{G} writes {B}~/.flow/tags-preview.tsv{R} - nothing is saved yet.{R}", - f"{G} {B}tags apply{R} writes that reviewed file into the library.{R}", - f"{G} apply sets the language and only fills an artist that is missing.{R}", - f"{G} {B}tags scan all{R} also re-scans songs that already have a language.{R}", + f"{T}> tags{R} {B}[list | add | remove | rename | delete]{R}", + f"{G} {B}tags{R} opens an interactive editor for language, artist{R}", + f"{G} and free-form tags (set on songs, rename, delete).{R}", + f"{G} {B}tags list{R} lists the current tags and how many songs use them.{R}", + f"{G} {B}tags add {R} puts a free-form tag on one song.{R}", + f"{G} {B}tags remove {R} takes it off again.{R}", + f"{G} {B}tags rename {R} renames it on every song.{R}", + f"{G} {B}tags delete {R} drops it everywhere.{R}", ], "like": [ f"{T}> like{R}", diff --git a/backend/ipc.py b/backend/ipc.py new file mode 100644 index 0000000..327270a --- /dev/null +++ b/backend/ipc.py @@ -0,0 +1,141 @@ +"""Cross-process player control: POSIX signals on Linux, a localhost socket elsewhere.""" + +import json +import os +import signal as _signal +import socket +import threading + +from backend import config, platform + +_SIGNAL_ATTR = { + "pause": "SIG_STOP", + "next": "SIG_NEXT", + "prev": "SIG_PREV", + "seek_fwd": "SIG_SEEK_FWD", + "seek_bwd": "SIG_SEEK_BWD", + "repeat": "SIG_REPEAT", + "shuffle": "SIG_SHUFFLE", + "stop_all": "SIG_STOP_ALL", +} + +WEB_COMMANDS = { + "pause": "stop", + "next": "next", + "prev": "previous", + "seek_fwd": "seek", + "seek_bwd": "seekb", +} + +_dispatch = None +_server_port = None + + +def signal_for(action: str): + """Signal number carrying ``action`` on this platform, or None.""" + return getattr(config, _SIGNAL_ATTR.get(action, ""), None) + + +def serve(dispatch, kind: str = "vlc") -> int | None: + """Install control handlers in this process; returns a socket port off Linux.""" + global _dispatch, _server_port + _dispatch = dispatch + for action in _SIGNAL_ATTR: + sig = signal_for(action) + if sig is None: + continue + try: + _signal.signal(sig, lambda s, f, a=action: _call(a, None)) + except (ValueError, OSError, RuntimeError): + pass + if platform.is_linux(): + return None + if _server_port is None: + _server_port = _start_server() + return _server_port + + +def dispatch(action: str, payload=None) -> bool: + """Run ``action`` inside this process (self-control without signals).""" + return _call(action, payload) + + +def send(entry, action: str, payload=None) -> bool: + """Deliver ``action`` to a player registry entry; True when delivered.""" + if not entry: + return False + port = entry.get("ctl_port") + if port: + return _send_socket(int(port), action, payload) + sig = signal_for(action) + if sig is None or platform.is_windows(): + return False + try: + os.kill(int(entry["pid"]), sig) + return True + except (ProcessLookupError, OSError, ValueError): + return False + + +def send_to(kind: str, action: str, payload=None) -> bool: + """Resolve ``kind`` in the player registry and deliver ``action`` to it.""" + from backend import registry + + return send(registry.resolve(kind), action, payload) + + +def _call(action: str, payload) -> bool: + handler = _dispatch + if handler is None or not action: + return False + try: + handler(action, payload) + return True + except TypeError: + try: + handler(action) + return True + except Exception: + return False + except Exception: + return False + + +def _start_server() -> int: + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(16) + port = srv.getsockname()[1] + threading.Thread(target=_serve_loop, args=(srv,), daemon=True).start() + return port + + +def _serve_loop(srv): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + try: + data = conn.recv(65536) + except OSError: + data = b"" + finally: + conn.close() + if not data: + continue + try: + msg = json.loads(data.decode()) + except (ValueError, UnicodeDecodeError): + continue + _call(msg.get("action", ""), msg.get("payload")) + + +def _send_socket(port: int, action: str, payload=None) -> bool: + try: + with socket.create_connection(("127.0.0.1", int(port)), timeout=5) as s: + s.sendall(json.dumps({"action": action, "payload": payload}).encode()) + return True + except OSError: + return False diff --git a/backend/keys.py b/backend/keys.py new file mode 100644 index 0000000..00705ee --- /dev/null +++ b/backend/keys.py @@ -0,0 +1,156 @@ +"""Cross-platform raw keyboard input: termios on POSIX, msvcrt on Windows.""" + +import errno +import os +import signal +import sys +import threading +import time + +from backend import platform + +_CTRL_Q = 0x11 +_PAUSE_KEY = 0x10 + + +def install_quit_key(fd=None): + """Map Ctrl+Q to Ctrl+C (termios on POSIX); a no-op on Windows.""" + if platform.is_windows(): + return lambda: None + import termios + + try: + target = sys.stdin.fileno() if fd is None else fd + if not os.isatty(target): + return lambda: None + old_term = termios.tcgetattr(target) + new = termios.tcgetattr(target) + new[0] &= ~termios.IXON + new[6][termios.VQUIT] = _CTRL_Q + termios.tcsetattr(target, termios.TCSADRAIN, new) + except (termios.error, OSError, ValueError, AttributeError): + return lambda: None + + def _sigquit(sig, frame): + raise KeyboardInterrupt + + try: + old_handler = signal.signal(signal.SIGQUIT, _sigquit) + except (ValueError, OSError): + old_handler = None + + def restore(): + if old_handler is not None: + try: + signal.signal(signal.SIGQUIT, old_handler) + except (ValueError, OSError): + pass + try: + import termios + + termios.tcsetattr(target, termios.TCSADRAIN, old_term) + except (termios.error, OSError, ValueError): + pass + + return restore + + +class RawReader: + """Daemon thread reading single stdin keys without blocking. + + POSIX: stdin is made raw-ish and non-blocking (restored on stop). + Windows: an msvcrt.kbhit()/getwch() polling thread. Each key byte is + handed to ``callback`` as an int; start()/stop() are idempotent. + """ + + def __init__(self, callback, fd=None): + self.callback = callback + self._fd = sys.stdin.fileno() if fd is None else fd + self._stop = threading.Event() + self._thread = None + self._restore = None + + def start(self): + if self._thread is not None: + return + if platform.is_windows(): + self._thread = threading.Thread(target=self._msvcrt_loop, daemon=True) + else: + self._restore = self._posix_prepare() + if self._restore is None: + return + self._thread = threading.Thread(target=self._posix_loop, daemon=True) + self._thread.start() + + def stop(self): + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=0.2) + self._thread = None + if self._restore is not None: + self._restore() + self._restore = None + + def _posix_prepare(self): + import fcntl + import termios + + try: + if not os.isatty(self._fd): + return None + old_term = termios.tcgetattr(self._fd) + new = termios.tcgetattr(self._fd) + new[0] &= ~termios.IXON + new[6][termios.VSUSP] = 0 + termios.tcsetattr(self._fd, termios.TCSADRAIN, new) + flags = fcntl.fcntl(self._fd, fcntl.F_GETFL) + fcntl.fcntl(self._fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) + except (termios.error, OSError, ValueError, AttributeError): + return None + try: + signal.signal(signal.SIGTSTP, signal.SIG_IGN) + except (ValueError, OSError): + pass + + def restore(): + try: + fcntl.fcntl(self._fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK) + termios.tcsetattr(self._fd, termios.TCSADRAIN, old_term) + except (termios.error, OSError, ValueError): + pass + + return restore + + def _posix_loop(self): + while not self._stop.is_set(): + try: + ch = os.read(self._fd, 1) + except OSError as ex: + if getattr(ex, "errno", None) == errno.EAGAIN: + time.sleep(0.05) + continue + break + if not ch: + break + self._emit(ch[0]) + + def _msvcrt_loop(self): + import msvcrt + + while not self._stop.is_set(): + if msvcrt.kbhit(): + ch = msvcrt.getwch() + if ch in ("\x00", "\xe0"): + # Function/arrow keys are two bytes; swallow the second. + if msvcrt.kbhit(): + msvcrt.getwch() + continue + self._emit(ord(ch)) + else: + time.sleep(0.05) + + def _emit(self, ch): + try: + self.callback(ch) + except Exception: + pass \ No newline at end of file diff --git a/backend/library.py b/backend/library.py index c08d5ba..de500ee 100644 --- a/backend/library.py +++ b/backend/library.py @@ -56,6 +56,14 @@ day TEXT PRIMARY KEY, plays INTEGER NOT NULL DEFAULT 0 ); + +CREATE TABLE IF NOT EXISTS song_tags ( + video_id TEXT NOT NULL, + tag TEXT NOT NULL, + PRIMARY KEY (video_id, tag) +); + +CREATE INDEX IF NOT EXISTS idx_song_tags_tag ON song_tags(tag); """ _COLUMNS = ( @@ -440,6 +448,192 @@ def get_tag_counts() -> list: return langs, names +def downloaded_rows() -> list: + """Every downloaded song with its tags, by name.""" + with _session() as conn: + rows = conn.execute( + "SELECT video_id, title, custom_title, artist, language " + "FROM songs WHERE downloaded = 1 AND song IS NOT NULL AND song != ''" + ).fetchall() + tag_rows = conn.execute("SELECT video_id, tag FROM song_tags").fetchall() + tags_by = {} + for t in tag_rows: + tags_by.setdefault(t["video_id"], []).append(t["tag"]) + out = [] + for r in rows: + out.append( + { + "video_id": r["video_id"], + "title": r["custom_title"] or r["title"] or r["video_id"], + "artist": r["artist"] or "", + "language": r["language"] or "", + "tags": sorted(tags_by.get(r["video_id"], [])), + } + ) + return sorted(out, key=lambda row: row["title"].lower()) + + +def song_tags(video_id: str) -> list: + """Free-form tags on one song, alphabetically.""" + if not video_id: + return [] + with _session() as conn: + rows = conn.execute( + "SELECT tag FROM song_tags WHERE video_id = ? ORDER BY tag", + (video_id,), + ).fetchall() + return [r["tag"] for r in rows] + + +def all_song_tags() -> list: + """Every free-form tag and how many songs carry it, most used first.""" + with _session() as conn: + rows = conn.execute( + "SELECT tag, COUNT(*) AS n FROM song_tags GROUP BY tag" + ).fetchall() + return sorted(((r["tag"], int(r["n"])) for r in rows), key=lambda kv: (-kv[1], kv[0])) + + +def set_song_tag(video_id: str, tag: str, on: bool = True) -> bool: + """Add (`on=True`) or remove one free-form tag on a song. False if unknown.""" + tag = (tag or "").strip() + if not video_id or not tag: + return False + with _write() as conn: + exists = conn.execute( + "SELECT 1 FROM songs WHERE video_id = ?", (video_id,) + ).fetchone() + if exists is None: + return False + if on: + conn.execute( + "INSERT OR IGNORE INTO song_tags (video_id, tag) VALUES (?, ?)", + (video_id, tag), + ) + else: + conn.execute( + "DELETE FROM song_tags WHERE video_id = ? AND tag = ?", + (video_id, tag), + ) + return True + + +def clear_song_tags(video_id: str) -> int: + """Remove every free-form tag from a song; returns how many were dropped.""" + with _write() as conn: + cur = conn.execute("DELETE FROM song_tags WHERE video_id = ?", (video_id,)) + return cur.rowcount + + +def rename_tag(old: str, new: str) -> int: + """Rename a free-form tag on every song; returns how many songs changed.""" + old, new = (old or "").strip(), (new or "").strip() + if not old or not new or old == new: + return 0 + with _write() as conn: + conn.execute( + "INSERT OR IGNORE INTO song_tags (video_id, tag) " + "SELECT video_id, ? FROM song_tags WHERE tag = ?", + (new, old), + ) + cur = conn.execute("DELETE FROM song_tags WHERE tag = ?", (old,)) + return cur.rowcount + + +def delete_tag(tag: str) -> int: + """Drop a free-form tag from every song; returns how many songs changed.""" + tag = (tag or "").strip() + if not tag: + return 0 + with _write() as conn: + cur = conn.execute("DELETE FROM song_tags WHERE tag = ?", (tag,)) + return cur.rowcount + + +def _tag_field(field: str) -> str: + """Map a user field name to the songs column it edits.""" + return "artist" if (field or "").strip().lower() in ("artist", "ar") else "language" + + +def _field_parts(value) -> list: + return [part.strip() for part in (value or "").split(",") if part.strip()] + + +def rename_field_tag(field: str, old: str, new: str) -> int: + """Rename one value inside the comma-separated `language`/`artist` column.""" + field = _tag_field(field) + old, new = (old or "").strip(), (new or "").strip() + if not old or not new or old.lower() == new.lower(): + return 0 + with _write() as conn: + rows = conn.execute( + f"SELECT video_id, {field} AS value FROM songs" + f" WHERE {field} IS NOT NULL" + ).fetchall() + changed = 0 + for r in rows: + parts = _field_parts(r["value"]) + if old.lower() not in (p.lower() for p in parts): + continue + kept, seen = [], set() + for part in parts: + if part.lower() == old.lower(): + if new.lower() not in seen: + kept.append(new) + seen.add(new.lower()) + elif part.lower() not in seen: + kept.append(part) + seen.add(part.lower()) + conn.execute( + f"UPDATE songs SET {field} = ? WHERE video_id = ?", + (", ".join(kept), r["video_id"]), + ) + changed += 1 + return changed + + +def delete_field_tag(field: str, value: str) -> int: + """Drop one value out of the comma-separated `language`/`artist` column.""" + field = _tag_field(field) + value = (value or "").strip() + if not value: + return 0 + with _write() as conn: + rows = conn.execute( + f"SELECT video_id, {field} AS value FROM songs" + f" WHERE {field} IS NOT NULL" + ).fetchall() + changed = 0 + for r in rows: + parts = _field_parts(r["value"]) + if value.lower() not in (p.lower() for p in parts): + continue + kept = [p for p in parts if p.lower() != value.lower()] + conn.execute( + f"UPDATE songs SET {field} = ? WHERE video_id = ?", + (", ".join(kept) if kept else None, r["video_id"]), + ) + changed += 1 + return changed + + +def set_song_field(video_id: str, field: str, value: str) -> bool: + """Set a song's whole `language`/`artist` value; an empty string clears it.""" + field = _tag_field(field) + value = (value or "").strip() + with _write() as conn: + exists = conn.execute( + "SELECT 1 FROM songs WHERE video_id = ?", (video_id,) + ).fetchone() + if exists is None: + return False + conn.execute( + f"UPDATE songs SET {field} = ? WHERE video_id = ?", + (value or None, video_id), + ) + return True + + def _default_entry(video_id: str, title: str = "") -> dict: return { "liked": False, @@ -709,6 +903,8 @@ def mutate(library): return True _mutate(mutate) + with _write() as conn: + conn.execute("DELETE FROM song_tags WHERE video_id = ?", (video_id,)) def _forgettable(entry: dict) -> bool: diff --git a/backend/lockfile.py b/backend/lockfile.py new file mode 100644 index 0000000..0d3de1f --- /dev/null +++ b/backend/lockfile.py @@ -0,0 +1,44 @@ +"""Cross-platform advisory file lock: flock on POSIX, msvcrt.locking on Windows.""" + +import contextlib +import os + + +@contextlib.contextmanager +def locked(path): + """Hold an exclusive lock on ``path`` for the duration of the block.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_RDWR) + try: + _acquire(fd) + yield + finally: + try: + _release(fd) + finally: + os.close(fd) + + +def _acquire(fd): + if os.name == "nt": + import msvcrt + + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_EX) + + +def _release(fd): + if os.name == "nt": + import msvcrt + + try: + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + except OSError: + pass + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_UN) diff --git a/backend/mpris.py b/backend/mpris.py index 38e2e3c..66999b7 100644 --- a/backend/mpris.py +++ b/backend/mpris.py @@ -6,6 +6,8 @@ import time from backend import config +from backend import ipc +from backend import platform BUS_NAME = "org.mpris.MediaPlayer2.flow" OBJECT_PATH = "/org/mpris/MediaPlayer2" @@ -89,32 +91,25 @@ def _next_trackid() -> str: class _Control: - """Sends flow's control signals to the current process (the player).""" - - @staticmethod - def _kill(sig): - try: - os.kill(os.getpid(), sig) - except OSError: - pass + """Sends control actions to the current process.""" def play(self): - self._kill(config.SIG_STOP) + ipc.dispatch("pause") def pause(self): - self._kill(config.SIG_STOP) + ipc.dispatch("pause") def playpause(self): - self._kill(config.SIG_STOP) + ipc.dispatch("pause") def stop(self): - self._kill(config.SIG_STOP_ALL) + ipc.dispatch("stop_all") def next(self): - self._kill(config.SIG_NEXT) + ipc.dispatch("next") def previous(self): - self._kill(config.SIG_PREV) + ipc.dispatch("prev") def _art_uri(value): @@ -738,7 +733,11 @@ def close(self): def _build_backend(): - if _DBUS_OK: + if platform.is_windows(): + # D-Bus/MPRIS is a Linux desktop integration; dbus_fast.aio + # cannot import on Windows (no socket.CMSG_LEN). + backend = _StubBackend() + elif _DBUS_OK: backend = _GlibBackend() elif _FAST_OK: backend = _FastBackend() diff --git a/backend/platform.py b/backend/platform.py new file mode 100644 index 0000000..f9e0070 --- /dev/null +++ b/backend/platform.py @@ -0,0 +1,132 @@ +"""Cross-platform OS helpers: detection, live-pid checks, detached spawning.""" + +import os +import signal +import subprocess +import sys +from pathlib import Path + + +def is_linux() -> bool: + return sys.platform.startswith("linux") + + +def is_macos() -> bool: + return sys.platform == "darwin" + + +def is_windows() -> bool: + return os.name == "nt" + + +def widen_stdio() -> None: + """Force UTF-8 on stdout/stderr so cp1252 pipes survive box-drawing output.""" + for stream in (sys.stdout, sys.stderr): + if stream is None: + continue + try: + stream.reconfigure(encoding="utf-8") + except (AttributeError, ValueError, OSError): + pass + + +def can_fork() -> bool: + return hasattr(os, "fork") + + +def pid_exists(pid) -> bool: + """True when ``pid`` is a live process on this OS.""" + if not pid: + return False + try: + import psutil + + return psutil.pid_exists(int(pid)) + except Exception: + pass + if is_windows(): + return False + try: + os.kill(int(pid), 0) + return True + except (OSError, ValueError): + return False + + +def kill_pid(pid, force: bool = False) -> bool: + """Terminate a process gracefully, or forcefully when ``force`` is set.""" + if not pid: + return False + try: + import psutil + + proc = psutil.Process(int(pid)) + if force: + proc.kill() + else: + proc.terminate() + return True + except Exception: + pass + if is_windows(): + return False + try: + os.kill(int(pid), signal.SIGKILL if force else signal.SIGTERM) + return True + except (OSError, ValueError): + return False + + +def spawn_detached(argv: list, **kwargs) -> subprocess.Popen: + """Start a child in its own session/process group, independent of the parent.""" + if is_windows(): + flags = getattr(subprocess, "DETACHED_PROCESS", 0) | getattr( + subprocess, "CREATE_NEW_PROCESS_GROUP", 0 + ) + kwargs.setdefault("close_fds", True) + return subprocess.Popen(argv, creationflags=flags, **kwargs) + return subprocess.Popen(argv, start_new_session=True, **kwargs) + + +def bootstrap_vlc() -> None: + """Point python-vlc at a system VLC install before ``import vlc`` runs. + + Linux is left alone (apt/brew already place libvlc where python-vlc's + default search looks). On Windows the exact libvlc.dll is exported as + PYTHON_VLC_LIB_PATH. On macOS that variable is *never* set: python-vlc's + darwin branch has to preload libvlccore before libvlc, and pinning the lib + path skips that and fails to load. macOS only gets a plugin path (and, for + a Homebrew install, DYLD_LIBRARY_PATH). + """ + if is_linux() or os.environ.get("PYTHON_VLC_LIB_PATH"): + return + plugins = None + if is_macos(): + base = Path("/Applications/VLC.app/Contents/MacOS") + if (base / "lib/libvlccore.dylib").exists(): + plugins = next( + (base / p for p in ("plugins", "modules") if (base / p).is_dir()), + None, + ) + else: + for root in ("/opt/homebrew/lib", "/usr/local/lib"): + if (Path(root) / "libvlc.dylib").exists(): + dyld = os.environ.get("DYLD_LIBRARY_PATH", "") + os.environ["DYLD_LIBRARY_PATH"] = ( + str(root) + (os.pathsep + dyld if dyld else "") + ) + plugins = Path(root) / "vlc/plugins" + break + elif is_windows(): + dirs = [Path(sys.executable).resolve().parent] + for env in ("LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"): + root = os.environ.get(env) + if root: + dirs.append(Path(root) / "VideoLAN" / "VLC") + for d in dirs: + if (d / "libvlc.dll").exists(): + os.environ.setdefault("PYTHON_VLC_LIB_PATH", str(d / "libvlc.dll")) + plugins = d / "plugins" + break + if plugins is not None and plugins.is_dir(): + os.environ.setdefault("PYTHON_VLC_MODULE_PATH", str(plugins)) diff --git a/backend/playlist.py b/backend/playlist.py index 1422686..2d24085 100644 --- a/backend/playlist.py +++ b/backend/playlist.py @@ -1,5 +1,4 @@ import contextlib -import fcntl import hashlib import json import os @@ -7,6 +6,8 @@ import re import time +from backend import lockfile + PLAYLISTS_DIR = pathlib.Path.home() / ".flow/playlists" PLAYLISTS_FILE = pathlib.Path.home() / ".flow/playlists.json" LEGACY_BAK = pathlib.Path.home() / ".flow/playlists.json.bak" @@ -65,14 +66,8 @@ def _slugify(name): @contextlib.contextmanager def _locked(): - PLAYLISTS_DIR.mkdir(parents=True, exist_ok=True) - fd = os.open(_LOCK_FILE, os.O_CREAT | os.O_RDWR) - try: - fcntl.flock(fd, fcntl.LOCK_EX) + with lockfile.locked(_LOCK_FILE): yield - finally: - fcntl.flock(fd, fcntl.LOCK_UN) - os.close(fd) def _atomic_write_json(path, obj): diff --git a/backend/plugin_api/flow_api.py b/backend/plugin_api/flow_api.py index bffe791..77e3028 100644 --- a/backend/plugin_api/flow_api.py +++ b/backend/plugin_api/flow_api.py @@ -66,6 +66,8 @@ def _connect() -> socket.socket | None: target = socket_path() if not os.path.exists(target): return None + if os.name == "nt": + return _connect_tcp(target) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(_CONNECT_TIMEOUT) try: @@ -79,6 +81,27 @@ def _connect() -> socket.socket | None: return sock +def _connect_tcp(address_file: str) -> socket.socket | None: + """Windows: the socket file holds ``host:port`` for the loopback daemon.""" + try: + host, _, port = pathlib.Path(address_file).read_text().strip().rpartition(":") + except OSError: + return None + if not host or not port.isdigit(): + return None + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(_CONNECT_TIMEOUT) + try: + sock.connect((host, int(port))) + except OSError: + try: + sock.close() + except OSError: + pass + return None + return sock + + def _read_frame(sock: socket.socket): # -> dict | None """Read one newline-delimited JSON frame from the daemon.""" data = sock.recv(65536) diff --git a/backend/plugins.py b/backend/plugins.py index 46ca04a..85efd4c 100644 --- a/backend/plugins.py +++ b/backend/plugins.py @@ -4,12 +4,11 @@ import os import pathlib import shutil -import signal import subprocess import sys import time -from backend import config +from backend import config, platform from backend.config import GREY, RED, Muted, Primary, Reset, Secondary P = Primary @@ -152,9 +151,9 @@ def _ensure_daemon() -> bool: # entry point does (editable install, site-packages, or a source # checkout on sys.path) — a bare script path would depend on the # cwd/editable-finder and can break for users. - subprocess.Popen( + platform.spawn_detached( [sys.executable, "-m", "backend.daemon", "start"], - start_new_session=True, + env=dict(os.environ), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) @@ -387,15 +386,7 @@ def _pid_file(name: str) -> pathlib.Path: def _alive(pid: int) -> bool: - try: - os.kill(pid, 0) - return True - except ProcessLookupError: - return False - except PermissionError: - return True - except OSError: - return False + return platform.pid_exists(pid) def running() -> dict[str, int]: @@ -477,11 +468,10 @@ def cmd_run(extra) -> int: LOGS_DIR.mkdir(parents=True, exist_ok=True) log_file = open(LOGS_DIR / f"{name}.log", "ab", buffering=0) - proc = subprocess.Popen( + proc = platform.spawn_detached( [sys.executable, str(entry_path), *plugin_args], cwd=str(dest), env=env, - start_new_session=True, stdout=log_file, stderr=log_file, ) @@ -503,21 +493,13 @@ def cmd_run(extra) -> int: def _kill_pid(name: str, pid: int): - try: - os.kill(pid, signal.SIGTERM) - except ProcessLookupError: - pass - except OSError as exc: - print(f"{E}Failed to signal {name}: {exc}{R}") + platform.kill_pid(pid) for _ in range(50): if not _alive(pid): break time.sleep(0.1) else: - try: - os.kill(pid, signal.SIGKILL) - except OSError: - pass + platform.kill_pid(pid, force=True) _pid_file(name).unlink(missing_ok=True) print(f"{P}Stopped plugin '{name}'{R}") diff --git a/backend/registry.py b/backend/registry.py index 867bc55..3fcc4fd 100644 --- a/backend/registry.py +++ b/backend/registry.py @@ -30,6 +30,8 @@ import pathlib import time +from backend import platform + HOME = pathlib.Path.home() STATE_DIR = HOME / ".flow" PLAYERS_FILE = STATE_DIR / "players.json" @@ -63,13 +65,7 @@ def _write(data: dict): def _alive(pid) -> bool: """True when the pid belongs to a live process.""" - if not pid: - return False - try: - os.kill(int(pid), 0) - return True - except (OSError, ValueError): - return False + return platform.pid_exists(pid) def entry(kind: str) -> dict | None: @@ -80,7 +76,9 @@ def entry(kind: str) -> dict | None: return rec -def register(kind: str, pid: int, port: int | None = None) -> dict: +def register( + kind: str, pid: int, port: int | None = None, ctl_port: int | None = None +) -> dict: """Register (or refresh) a live player of the given kind.""" if kind not in KINDS: raise ValueError(f"unknown player kind {kind!r}") @@ -88,6 +86,8 @@ def register(kind: str, pid: int, port: int | None = None) -> dict: rec = {"pid": int(pid), "ts": time.time()} if port is not None: rec["port"] = int(port) + if ctl_port is not None: + rec["ctl_port"] = int(ctl_port) data[kind] = rec _write(data) return rec @@ -118,6 +118,8 @@ def live() -> list[dict]: row = {"kind": kind, "pid": int(rec["pid"])} if rec.get("port") is not None: row["port"] = int(rec["port"]) + if rec.get("ctl_port") is not None: + row["ctl_port"] = int(rec["ctl_port"]) out.append(row) return out diff --git a/backend/rich_display.py b/backend/rich_display.py new file mode 100644 index 0000000..24e2c9e --- /dev/null +++ b/backend/rich_display.py @@ -0,0 +1,238 @@ +"""Rich-based now-playing display and live spinners for `display rich`.""" + +from __future__ import annotations + +import sys +import time + +from backend import config + + +def active(): + """True when the rich display mode is on and stdout can render it.""" + try: + return config.Display == "rich" and sys.stdout.isatty() + except Exception: + return False + + +def _progress(): + """Build a rich Progress bar from the user's configured column names.""" + from rich.progress import ( + BarColumn, + DownloadColumn, + FileSizeColumn, + MofNCompleteColumn, + Progress, + SpinnerColumn, + TaskProgressColumn, + TimeElapsedColumn, + TimeRemainingColumn, + TotalFileSizeColumn, + TransferSpeedColumn, + ) + + registry = { + "bar": BarColumn, + "download": DownloadColumn, + "file_size": FileSizeColumn, + "m_of_n": MofNCompleteColumn, + "percentage": TaskProgressColumn, + "spinner": SpinnerColumn, + "task": TaskProgressColumn, + "time_elapsed": TimeElapsedColumn, + "time_remaining": TimeRemainingColumn, + "total_size": TotalFileSizeColumn, + "transfer_speed": TransferSpeedColumn, + } + picked = [] + seen = set() + for name in config.ProgressColumns: + cls = registry.get(name) + if cls is None or cls in seen: + continue + seen.add(cls) + if cls is SpinnerColumn: + picked.append(_spinner_column()) + else: + picked.append(cls()) + return Progress(*picked, auto_refresh=False) + + +def _spinner_name(): + """A valid rich spinner name from config (falls back to 'dots').""" + try: + from rich.spinner import SPINNERS + except Exception: + return "dots" + name = config.RichSpinner + return name if name in SPINNERS else "dots" + + +def _spinner_column(): + """A SpinnerColumn for the configured spinner (rich version tolerant).""" + from rich.progress import SpinnerColumn + + name = _spinner_name() + try: + return SpinnerColumn(spinner_name=name) + except TypeError: # rich < 15 used `spinner=` + return SpinnerColumn(spinner=name) + + +class NowPlaying: + """A live rich panel with the track metadata and a progress bar.""" + + def __init__(self, title, artist="", album="", duration=0, status=""): + from rich.console import Console + from rich.live import Live + + self.title = title or "" + self.artist = artist or "" + self.album = album or "" + self.duration = int(duration or 0) + self.status = status or "" + self.console = Console() + self.progress = _progress() + self.task = self.progress.add_task("", total=self.duration or None) + self._live = Live( + self._panel(0.0, False), + console=self.console, + refresh_per_second=8, + screen=False, + ) + + def set_track(self, title, artist="", album="", duration=0, status=""): + """Point the panel at another track (used by the `--full` monitor).""" + self.title = title or "" + self.artist = artist or "" + self.album = album or "" + self.duration = int(duration or 0) + self.status = status or "" + try: + self.progress.update(self.task, completed=0.0, total=self.duration or None) + except Exception: + pass + + def render(self, elapsed=0.0, paused=False): + """The panel renderable for the given position (no Live required).""" + return self._panel(elapsed, paused) + + def _panel(self, elapsed, paused): + from rich.panel import Panel + + parts = [x for x in (self.artist, self.album) if x] + if self.status: + parts.append(self.status) + if paused: + parts.append("[Paused]") + sub = " \u00b7 ".join(parts) + return Panel( + self.progress, + title=self.title or "Flow", + subtitle=sub or None, + border_style="yellow" if paused else "cyan", + padding=(0, 1), + width=self._panel_width(), + ) + + def _panel_width(self): + """A small panel: about 40% of the terminal, within a readable range.""" + try: + cols = self.console.width or 80 + except Exception: + cols = 80 + return max(30, min(int(cols * 0.4), 80)) + + def start(self): + try: + self._live.start() + except Exception: + pass + + def update(self, elapsed, paused=False): + try: + self.progress.update( + self.task, + completed=max(0.0, float(elapsed)), + total=self.duration or None, + ) + self._live.update(self._panel(elapsed, paused)) + except Exception: + pass + + def stop(self): + try: + self._live.stop() + except Exception: + pass + + +def spinner_run(stop, label="Searching"): + """Block until `stop()` is true, showing a rich spinner meanwhile.""" + from rich.console import Console + + console = Console() + try: + with console.status(f"[bold]{label}...[/]", spinner=_spinner_name()): + while not stop(): + time.sleep(0.08) + except Exception: + pass + + +class _DownloadBar: + def __init__(self): + from rich.console import Console + from rich.live import Live + + self.console = Console() + self.progress = _progress() + self.task = self.progress.add_task("", total=None) + self._live = Live( + self.progress, console=self.console, refresh_per_second=8, screen=False + ) + + def start(self): + try: + self._live.start() + except Exception: + pass + + def update(self, got, total): + try: + self.progress.update( + self.task, completed=float(got), total=float(total) or None + ) + except Exception: + pass + + def stop(self): + try: + self._live.stop() + except Exception: + pass + + +_download_bar = None + + +def download_start(): + """Open the rich download progress bar (no-op unless rich display).""" + global _download_bar + if not active(): + return + _download_bar = _DownloadBar() + _download_bar.start() + + +def download_update(got, total): + if _download_bar is not None: + _download_bar.update(got, total) + + +def download_stop(): + global _download_bar + if _download_bar is not None: + _download_bar.stop() + _download_bar = None diff --git a/backend/rpc.py b/backend/rpc.py index 0861277..6f1a491 100644 --- a/backend/rpc.py +++ b/backend/rpc.py @@ -1,26 +1,3 @@ -"""Typed RPC dispatch for the Flow daemon socket. - -This runs *inside* the resident daemon, in-process. Every method resolves to a -real validated backend function — there is no plugin-facing passthrough that -lets a plugin run arbitrary `flow` flags. The method surface is small and -typed (`docs/dev/plugins.md`): - -- state current_track / is_playing / status (file reads) -- data library_stats / history (SQLite reads via backend.library -- and backend.history) -- player pause / resume / next / previous / seek / seek_back / like / - unlike / download (host-routed player control) -- players players — live player registry (kind, pid, port) -- config get_config / get_configs / set_config (PLUGIN_SAFE_KEYS enforced) -- ui set_theme / list_themes / set_spinner -- raw raw_cli — only when the plugin is installed with ``"raw": true`` - in plugin.json or FLOW_PLUGIN_RAW=1 was set by the launcher -- events connection-level event registry; server can push ``event`` frames - -Generic ``control(*flow_args)`` passthrough is gone. `raw_cli` is the only -arbitrary flag surface, and it's gated host-side. -""" - import json import os import pathlib @@ -137,53 +114,46 @@ def _player_running() -> bool: return registry.resolve("vlc") is not None or registry.resolve("web") is not None -def _send_player(command: str, sig, label: str, delta=None): +def _send_player(action: str, label: str, delta=None): """Host-authoritative player routing — same as the CLI does it.""" - from backend import registry + from backend import ipc, registry entry = registry.resolve("vlc") if entry is not None: pid = entry["pid"] - try: - if delta is not None: - config.write_seek(int(delta)) - os.kill(pid, sig) - except ProcessLookupError: - config.clear_pid_if(pid) - except OSError: - pass - return f"{label} (VLC pid {pid})" - else: - control.send(command, delta) - return f"{label} (web player)" + if delta is not None: + config.write_seek(int(delta)) + payload = {"delta": delta} if delta is not None else None + if ipc.send(entry, action, payload): + return f"{label} (VLC pid {pid})" + config.clear_pid_if(pid) + command = ipc.WEB_COMMANDS.get(action, action) + control.send(command, delta) + return f"{label} (web player)" def rpc_pause() -> str: - return _send_player("stop", config.SIG_STOP, "Toggled pause/resume") + return _send_player("pause", "Toggled pause/resume") def rpc_resume() -> str: - return _send_player("stop", config.SIG_STOP, "Resumed playback") + return _send_player("pause", "Resumed playback") def rpc_next() -> str: - return _send_player("next", config.SIG_NEXT, "Skipped to next track") + return _send_player("next", "Skipped to next track") def rpc_previous() -> str: - return _send_player("previous", config.SIG_PREV, "Went to previous track") + return _send_player("prev", "Went to previous track") def rpc_seek(sec: float) -> str: - return _send_player( - "seek", config.SIG_SEEK_FWD, f"Seeked forward {int(sec)}s", int(sec) * 1000 - ) + return _send_player("seek_fwd", f"Seeked forward {int(sec)}s", int(sec) * 1000) def rpc_seek_back(sec: float) -> str: - return _send_player( - "seekb", config.SIG_SEEK_BWD, f"Seeked backward {int(sec)}s", -int(sec) * 1000 - ) + return _send_player("seek_bwd", f"Seeked backward {int(sec)}s", -int(sec) * 1000) def _act_current(action: str) -> str: diff --git a/backend/status.py b/backend/status.py index c54e020..678d3a7 100644 --- a/backend/status.py +++ b/backend/status.py @@ -99,6 +99,7 @@ def _vid_from_thumb(thumb: str): if not thumb: return None try: + thumb = thumb.replace("\\", "/") # Windows paths use backslashes for pat in ("/vi_webp/", "/vi/", ".cache/"): if pat in thumb: return thumb.split(pat)[1].split("/")[0].split(".")[0] or None diff --git a/backend/tags.py b/backend/tags.py index 39f84a7..4d65ff3 100644 --- a/backend/tags.py +++ b/backend/tags.py @@ -1,11 +1,3 @@ -"""One-word tags trimmed out of a track's YouTube metadata. - -A music video's title and description carry credits, hashtags, "(Official -Video)" noise and film names. Everything except the language and the artist is -dropped here, so the library keeps two clean single-word tags it can filter and -play by. -""" - import re LANGUAGE_NAMES = { @@ -215,4 +207,4 @@ def tags_from_info(info: dict) -> dict: artist = artist_from_info(info) if artist: tags["artist"] = artist - return tags \ No newline at end of file + return tags diff --git a/backend/ui.py b/backend/ui.py index 3789df4..1d26a4a 100644 --- a/backend/ui.py +++ b/backend/ui.py @@ -4,32 +4,36 @@ def questionary_style(mode="online"): from questionary import Style - def name(ansi_code): - return config._cname(ansi_code) + def name(style): + return config._cname(style) + + primary = config._STYLE["primary"] + secondary = config._STYLE["secondary"] + tertiary = config._STYLE["tertiary"] if mode == "online": return Style( [ - ("qmark", f"fg:{name(config.Primary)} bold"), - ("question", f"fg:{name(config.Primary)} bold"), - ("answer", f"fg:{name(config.Primary)} bold"), - ("pointer", f"fg:{name(config.Primary)} bold"), - ("highlighted", f"fg:{name(config.Primary)} bold"), - ("selected", f"fg:{name(config.Primary)}"), - ("instruction", f"fg:{name(config.Tertiary)}"), + ("qmark", f"fg:{name(primary)} bold"), + ("question", f"fg:{name(primary)} bold"), + ("answer", f"fg:{name(primary)} bold"), + ("pointer", f"fg:{name(primary)} bold"), + ("highlighted", f"fg:{name(primary)} bold"), + ("selected", f"fg:{name(primary)}"), + ("instruction", f"fg:{name(tertiary)}"), ("text", ""), ] ) else: return Style( [ - ("qmark", f"fg:{name(config.Secondary)} bold"), - ("question", f"fg:{name(config.Secondary)} bold"), - ("answer", f"fg:{name(config.Secondary)} bold"), - ("pointer", f"fg:{name(config.Secondary)} bold"), - ("highlighted", f"fg:{name(config.Secondary)} bold"), - ("selected", f"fg:{name(config.Secondary)}"), - ("instruction", f"fg:{name(config.Tertiary)}"), + ("qmark", f"fg:{name(secondary)} bold"), + ("question", f"fg:{name(secondary)} bold"), + ("answer", f"fg:{name(secondary)} bold"), + ("pointer", f"fg:{name(secondary)} bold"), + ("highlighted", f"fg:{name(secondary)} bold"), + ("selected", f"fg:{name(secondary)}"), + ("instruction", f"fg:{name(tertiary)}"), ("text", ""), ] ) diff --git a/backend/visualizer.py b/backend/visualizer.py index 8902783..9e370ce 100644 --- a/backend/visualizer.py +++ b/backend/visualizer.py @@ -1,4 +1,3 @@ -import curses import re import shutil import subprocess @@ -8,6 +7,11 @@ import sounddevice as sd from backend import config +try: + import curses +except ImportError: + curses = None + BLOCK_SIZE = 4096 SAMPLE_RATE = 48000 MIN_FREQ = 60 @@ -29,6 +33,8 @@ _status_repeat = False _status_next = None _status_paused = False +_status_artist = "" +_status_album = "" def _ansi_to_curses_color(ansi_code): @@ -204,6 +210,8 @@ def _audio_callback(indata, frames, time_info, status): def start(stdscr, ansi_color): global _stream, _bins, _bars, _peak, _stdscr, _orig_source + if curses is None: + return False if _stream is not None: return _stdscr = stdscr @@ -247,12 +255,16 @@ def start(stdscr, ansi_color): return True -def set_status(title=None, shuffle=False, repeat=False, next_title=None): +def set_status(title=None, shuffle=False, repeat=False, next_title=None, + artist="", album=""): global _status_title, _status_shuffle, _status_repeat, _status_next + global _status_artist, _status_album _status_title = title _status_shuffle = shuffle _status_repeat = repeat _status_next = next_title + _status_artist = artist or "" + _status_album = album or "" def set_paused(paused): @@ -317,6 +329,8 @@ def _draw_footer(max_y, max_x): and not _status_shuffle and not _status_repeat and not _status_next + and not _status_artist + and not _status_album and not _status_paused ): return @@ -333,6 +347,12 @@ def _draw_footer(max_y, max_x): if len(n) > 24: n = n[:23] + "…" badges.append(f"[Next: {n}]") + for extra in (_status_artist, _status_album): + if extra: + e = extra + if len(e) > 24: + e = e[:23] + "…" + badges.append(f"[{e}]") title_row = max_y - 1 badge_row = max_y - 2 diff --git a/cli/main.py b/cli/main.py index eb4ff42..e51eecc 100644 --- a/cli/main.py +++ b/cli/main.py @@ -3,7 +3,6 @@ import os import re import shutil -import signal import sys import threading import time @@ -13,7 +12,10 @@ if __name__ == "__main__" and __package__ is None: sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from backend import config, shortcuts +from backend.platform import bootstrap_vlc + +bootstrap_vlc() +from backend import config, platform, shortcuts from backend.Offline import commands as _offline_commands from backend.Online import commands as _online_commands from backend.ping import is_connected @@ -53,21 +55,20 @@ def _send_web_command(port, command, payload=None): return False -def _send_control(command, sig, label, payload=None): - from backend import registry +def _send_control(action, label, payload=None): + from backend import ipc, registry entry = registry.resolve("vlc") if entry is not None: pid = entry["pid"] - try: - os.kill(pid, sig) + if ipc.send(entry, action, payload): print(f"{P}{label} (VLC PID: {pid}){R}") return - except ProcessLookupError: - config.clear_pid_if(pid) + config.clear_pid_if(pid) web = registry.resolve("web") if web is not None and web.get("port"): + command = ipc.WEB_COMMANDS.get(action, action) if _send_web_command(web["port"], command, payload): print(f"{P}{label} (web player){R}") return @@ -76,6 +77,11 @@ def _send_control(command, sig, label, payload=None): def _spinner(stop): + from backend import rich_display + + if rich_display.active(): + rich_display.spinner_run(stop, "Checking connection") + return chars = config.SPINNER i = 0 while not stop(): @@ -175,8 +181,12 @@ def _resume(args): def _full_view(): - """Full-screen now-playing card: clear, logo + a live progress readout - that refreshes once a second (Ctrl-C to exit).""" + """Full-screen now-playing view; follows the configured display mode + (rich live panel, or the bordered progress card). Ctrl-C to exit.""" + if config.Display == "rich": + _full_view_rich() + return + from backend import status as _status def _tty_width(default=96): @@ -257,6 +267,61 @@ def _row(label, value): print() +def _full_view_rich(): + """`--full` in rich mode: a live rich panel fed from status.json.""" + from backend import library, rich_display + from backend import status as _status + + def _meta(data): + vid = _status._vid_from_thumb(data.get("thumbnail", "")) + artist = album = "" + if vid: + entry = library.get(vid) or {} + artist = entry.get("artist") or "" + album = entry.get("album") or "" + return artist, album + + panel = rich_display.NowPlaying("", duration=0) + if not sys.stdout.isatty(): + data = _status._read() + artist, album = _meta(data) + playing = bool(data.get("playing")) and _status._fresh(data) + panel.set_track( + data.get("title") or "—", + artist, + album, + int(data.get("duration", 0)), + status="playing" if playing else "not playing", + ) + panel.console.print(panel.render(int(data.get("elapsed", 0)), not playing)) + return + + tui_shell.clear_screen() + panel.start() + last = None + try: + while True: + data = _status._read() + playing = bool(data.get("playing")) and _status._fresh(data) + title = data.get("title") or "—" + dur = int(data.get("duration", 0)) + elapsed = int(data.get("elapsed", 0)) + artist, album = _meta(data) + status_text = "playing" if playing else "not playing" + key = (title, artist, album, dur, status_text) + if key != last: + panel.set_track(title, artist, album, dur, status=status_text) + last = key + panel.update(elapsed, paused=not playing) + time.sleep(1) + except KeyboardInterrupt: + pass + finally: + panel.stop() + tui_shell.clear_screen() + print() + + def _act_current(action): from backend import status as _status @@ -297,6 +362,7 @@ def _act_current(action): def main(): + platform.widen_stdio() parser = argparse.ArgumentParser( description="Flow Music Player", epilog=( @@ -381,11 +447,6 @@ def main(): action="store_true", help="download the currently playing song (requires an active player)", ) - parser.add_argument( - "--meta", - action="store_true", - help="backfill metadata in library.db for already downloaded songs (temporary)", - ) parser.add_argument( "--summary", action="store_true", @@ -440,6 +501,9 @@ def main(): args, unknown = parser.parse_known_args() if getattr(args, "setup_island", False): + if not platform.is_linux(): + print(f"{config.Muted}--setup-island is Linux-only (Hyprland) and is skipped here{R}") + sys.exit(0) _setup_island() sys.exit(0) @@ -529,34 +593,27 @@ def main(): control_args = [] if getattr(args, "pause", False): - control_args.append(("stop", signal.SIGUSR1, "Toggled pause/resume", None)) + control_args.append(("pause", "Toggled pause/resume", None)) if getattr(args, "next", False): - control_args.append(("next", signal.SIGUSR2, "Skipped to next track", None)) + control_args.append(("next", "Skipped to next track", None)) if getattr(args, "previous", False): - control_args.append( - ("previous", config.SIG_PREV, "Went to previous track", None) - ) + control_args.append(("prev", "Went to previous track", None)) if getattr(args, "seek", None) is not None: - control_args.append( - ("seek", config.SIG_SEEK_FWD, "Seeked forward", getattr(args, "seek")) - ) + control_args.append(("seek_fwd", "Seeked forward", getattr(args, "seek"))) if getattr(args, "seekb", None) is not None: - control_args.append( - ("seekb", config.SIG_SEEK_BWD, "Seeked backward", -getattr(args, "seekb")) - ) + control_args.append(("seek_bwd", "Seeked backward", -getattr(args, "seekb"))) if control_args: - for command, sig, label, delta in control_args: + for action, label, delta in control_args: if delta is not None: from backend import registry - if registry.resolve("vlc") is not None: + if registry.resolve("vlc") is not None or registry.resolve("tui") is not None: config.write_seek(delta * 1000) label = f"{label} {abs(delta)}s" _send_control( - command, - sig, + action, label, - payload={"delta": delta} if delta is not None else None, + payload={"delta": delta * 1000} if delta is not None else None, ) sys.exit(0) @@ -566,8 +623,6 @@ def main(): sys.exit(_act_current("unlike")) if getattr(args, "download", False): sys.exit(_act_current("download")) - if getattr(args, "meta", False): - sys.exit(_online_commands.backfill_metadata()) forced_offline = False if getattr(args, "resume", False): diff --git a/cli/tui.py b/cli/tui.py index a8d96ea..93b06da 100644 --- a/cli/tui.py +++ b/cli/tui.py @@ -1,10 +1,8 @@ import builtins import os -import signal import sys -import termios -from backend import config +from backend import config, keys BANNER = r""" ███████╗██╗ ██████╗ ██╗ ██╗ @@ -45,53 +43,19 @@ def input(prompt: str = "") -> str: def install_quit_key(fd=None): - """Make Ctrl+Q leave the shell, exactly like Ctrl+C does. + """Map Ctrl+Q to Ctrl+C so it leaves the shell like Ctrl+C does. Ctrl+Q raises no signal on a stock terminal: it is XON (resume output), so it is swallowed by flow control while a command is running and arrives as a plain byte while readline is editing a line. The only way to make it quit is to take XON away and hand the terminal's QUIT character to it, then catch SIGQUIT and re-raise it as the KeyboardInterrupt the shell loop - already treats as "leave". - - Radio mode does the same remap for its own lifetime and restores whatever - it found on exit, so the two nest safely. Anything that is not a real - terminal (piped stdin, background fork) is a no-op. + already treats as "leave". Implementation lives in backend.keys; anything + that is not a real terminal (piped stdin, background fork) is a no-op, + as is the whole remap on Windows. `fd` exists so tests can point this at a pty slave; it defaults to stdin. Returns the callable that puts the terminal and handler back. """ - try: - if fd is None: - fd = sys.stdin.fileno() - if not os.isatty(fd): - return lambda: None - old_term = termios.tcgetattr(fd) - new = termios.tcgetattr(fd) - new[0] &= ~termios.IXON - new[6][termios.VQUIT] = _CTRL_Q - termios.tcsetattr(fd, termios.TCSADRAIN, new) - except (AttributeError, ValueError, OSError, termios.error): - return lambda: None - - def _sigquit(sig, frame): - raise KeyboardInterrupt - - try: - old_handler = signal.signal(signal.SIGQUIT, _sigquit) - except (ValueError, OSError): - old_handler = None - - def restore(): - if old_handler is not None: - try: - signal.signal(signal.SIGQUIT, old_handler) - except (ValueError, OSError): - pass - try: - termios.tcsetattr(fd, termios.TCSADRAIN, old_term) - except (OSError, termios.error): - pass - - return restore + return keys.install_quit_key(fd) diff --git a/demo.mp4 b/demo.mp4 index 55770d3..dac0484 100644 Binary files a/demo.mp4 and b/demo.mp4 differ diff --git a/docs/dev/storage.md b/docs/dev/storage.md index ed988d7..2cf9772 100644 --- a/docs/dev/storage.md +++ b/docs/dev/storage.md @@ -119,8 +119,17 @@ Notes: - `library.get_tag_rows(field, tag)` is the read side: downloaded rows only, fuzzy (case-insensitive substring) on `language` or `artist`, ascending by display name. `library.get_tag_counts()` returns both tag lists with counts. - The `Offline.lang_track` / `Offline.artist_track` commands and `tags apply` - are the only writers. + The writers are `Offline.lang_track` / `Offline.artist_track` (readers too), + the `tags` editor in `Offline.commands`, and the `tags add|remove|rename|delete` + forms of both the offline shell and `flow-min`. +- `song_tags` is a second table of **free-form** tags the user assigns by hand: + one `(video_id, tag)` row per tag. `library.set_song_tag` adds or removes + one, `rename_tag` / `delete_tag` act on a whole tag across songs, + `clear_song_tags` empties a song, and `downloaded_rows` joins them for the + editor's pickers. `library.clear_download` drops them with the download. + `library.rename_field_tag` / `delete_field_tag` / `set_song_field` edit the + `language`/`artist` columns whole-value, splitting on commas so a + `"hindi, punjabi"` value counts as (and renames/deletes) either tag. - **A row is only deleted when nothing is left to remember** — not liked, not downloaded, not on speed dial, no `song` path, *and* `song_count == 0` — so a play count survives an unlike or a delete. diff --git a/docs/user/command-line.md b/docs/user/command-line.md index 390081e..a46b6dc 100644 --- a/docs/user/command-line.md +++ b/docs/user/command-line.md @@ -131,7 +131,7 @@ download the matching index can be used the same way. | `rename ` | Rename a downloaded song (offline; alias: `re`). You are then asked for the new name. An index is the number in the `list` output (ascending by name) and the prompt repeats it | | `lang ` | Play every downloaded song with that language tag (offline). One word — `hindi`, `punjabi`, `telugu`, ... — set when the song was downloaded. Partial words work (`lang pun`); `-s` shuffles | | `artist ` | Play every song by that artist. Offline plays your downloads, online plays the YouTube results whose title credits the artist (falling back to the current track's artist). Partial words work; `-s` shuffles (alias: `ar`) | -| `tags [scan \| apply]` | List the language and artist tags in your library. `tags scan` asks YouTube for each downloaded song's metadata and writes `~/.flow/tags-preview.tsv` (nothing is saved); `tags apply` writes that reviewed file into the library | +| `tags [list \| add \| remove \| rename \| delete]` | Inspect or maintain tags. Bare `tags` opens an interactive editor (delete/clear steps multi-select); `tags add ` / `tags remove ` tag a song, `tags rename ` renames a free-form tag everywhere, `tags delete ` drops it everywhere | | `playlist ` | Manage playlists — see below | | `switch` | Toggle between online and offline mode | | `config [target [value]]` | Change settings; run bare for an interactive wizard | @@ -195,7 +195,7 @@ the credited artist (never the channel name). Everything else in a music video's title and description — credits, hashtags, `(Official Video)` — is thrown away. ```bash -flow tags # what you can play by right now +flow tags list # what you can play by right now flow lang hindi # every hindi download, ascending by name flow lang pun -s # partial word, shuffled flow artist karan # every Karan Aujla song, ascending by name @@ -207,20 +207,29 @@ modes: offline it filters your library the same way; online there is no library to filter, so it keeps the search results whose **title** credits the artist and, when none of them do, falls back to the artist of the track that is playing. -Songs downloaded before tags existed have none. `tags scan` asks YouTube about -each of them, one at a time, and writes what it finds to -`~/.flow/tags-preview.tsv` — one row per song, nothing saved to the library -until you say so: +Songs downloaded before tags existed have none. `tags` maintains them. Bare +`tags` opens an interactive editor — pick language, artist or free-form tags, +then set a value on songs, rename it everywhere or delete it everywhere. The +plain forms are scriptable: ```bash -flow tags scan # writes ~/.flow/tags-preview.tsv -$EDITOR ~/.flow/tags-preview.tsv # read it, fix or drop rows you disagree with -flow tags apply # writes the file into library.db +flow tags # interactive editor (in the shell) +flow tags list # languages + artists + free-form tags +flow tags add "Mitti" workout # free-form tag on one song +flow tags remove "Mitti" workout +flow tags rename workout gym # on every song that has it +flow tags delete workout ``` -`apply` sets the language tag and only fills in an artist where there is none, -so it never replaces an artist you already have. Add `all` (`flow tags scan all`) -to re-scan songs that already have a language tag. +Every song-picking step checks a checkbox list, and the delete steps let you +pick several tags at once — `flow tags`, pick *Free-form tags → Delete +tag(s) everywhere* (or the language/artist equivalent), tick two or three +tags with space, confirm, and they are all gone. + +`language` and `artist` come from YouTube's metadata at download time — +`tags` fixes or extends them by hand. Free-form tags (`workout`, `roadtrip`, +…) are yours to assign: create one with `tags add`, tidy up with +rename/delete. ### export diff --git a/docs/user/configuration.md b/docs/user/configuration.md index 7627011..d8162ce 100644 --- a/docs/user/configuration.md +++ b/docs/user/configuration.md @@ -13,7 +13,9 @@ color names, or `config ` for one-off changes. | `primary` (pri) | Color for online songs | any color name | | `secondary` (sec) | Color for offline songs | any color name | | `tertiary` (ter) | Color for labels | any color name | -| `display` | Playback display mode | `none`, `bars`, `lyrics`, `progress` | +| `display` | Playback display mode | `none`, `bars`, `lyrics`, `progress`, `rich` | +| `progress_type` | Rich progress layout (when `display rich`) | `default`, `download`, `pulse`, `custom` | +| `rich_spinner` | Rich spinner (when `display rich`) | any name from `python -m rich.spinner`, or custom chars | | `barwidth` | Number of bars in the visualizer | 4–80 | | `barheight` | Height of bars | 10–90 | | `barspacing` | Space between bars | 0–4, or `min` / `fit` / `max` | @@ -40,6 +42,8 @@ Settings persist to `~/.flow/config.json`: "secondary": "purple", "tertiary": "blue", "display": "bars", + "progress_columns": ["bar", "percentage", "time_remaining"], + "progress_type": "default", "bar_width": 20, "bar_height": 40, "bar_spacing": 1, @@ -47,6 +51,8 @@ Settings persist to `~/.flow/config.json`: "prog_char": "█", "prog_char_em": "░", "sensitivity": 1.0, + "spinner": "|/-\\", + "rich_spinner": "dots", "dev": false, "ffmpeg": true, "ad_skip": true, diff --git a/docs/user/installation.md b/docs/user/installation.md index 4d4fc61..79cc950 100644 --- a/docs/user/installation.md +++ b/docs/user/installation.md @@ -46,6 +46,58 @@ flow --check prints a table of core dependencies (ffmpeg, vlc, yt-dlp, psutil, flask, numpy, sounddevice, ytmusicapi) with pass/fail status. +## Installing VLC + +Flow plays audio through libvlc via `python-vlc`. `python-vlc` resolves the +library at `import vlc` time, so VLC must be installed *before* Flow imports +it. Flow's startup bootstrap (`backend.platform.bootstrap_vlc`) picks up a +standard install automatically on each OS. + +### Linux + +```bash +sudo apt install vlc # Debian / Ubuntu +sudo dnf install vlc # Fedora +sudo pacman -S vlc # Arch +``` + +libvlc is resolved through ldconfig and its plugins are found next to it — +nothing to configure. + +### macOS + +```bash +brew install --cask vlc +``` + +Flow points `python-vlc` at `/Applications/VLC.app` automatically (plugin +dir: `/Applications/VLC.app/Contents/MacOS/plugins`). If you keep VLC +somewhere non-standard, export the plugin path before starting Flow: + +```bash +export VLC_PLUGIN_PATH="/path/to/VLC.app/Contents/MacOS/plugins" +``` + +### Windows + +Install the official [VLC installer](https://www.videolan.org/vlc/), or use +the portable zip (same 64-bit build, no installer): + +``` +https://get.videolan.org/vlc/3.0.21/win64/vlc-3.0.21-win64.zip +``` + +Flow finds `libvlc.dll` in the standard `VideoLAN\VLC` install locations +automatically. When running from a portable/extracted copy, point python-vlc +at it before starting Flow (PowerShell): + +```powershell +$env:PYTHON_VLC_LIB_PATH = "C:\path\to\vlc\libvlc.dll" +$env:VLC_PLUGIN_PATH = "C:\path\to\vlc\plugins" +``` + +`flow --check` reports whether VLC resolved correctly on every OS. + ## First run Everything is stored under `~/.flow/` and created on demand — there is no diff --git a/minimal/common.py b/minimal/common.py index 70feef4..5b8f7cc 100644 --- a/minimal/common.py +++ b/minimal/common.py @@ -6,7 +6,7 @@ import types import urllib.request -from backend import config, library, registry, status +from backend import config, ipc, library, registry, status def ns(**over): @@ -48,16 +48,15 @@ def web_command(port, command, payload=None): return False -def signal(command, sig, payload=None): - """Signal the player (VLC pid first, web player as fallback); returns its pid or "web".""" +def signal(action, payload=None): + """Deliver a control action to the running player; returns its pid or "web".""" entry = registry.resolve("vlc") if entry is not None: - try: - os.kill(entry["pid"], sig) + if ipc.send(entry, action, payload): return entry["pid"] - except ProcessLookupError: - config.clear_pid_if(entry["pid"]) + config.clear_pid_if(entry["pid"]) web = registry.resolve("web") + command = ipc.WEB_COMMANDS.get(action, action) if web is not None and web.get("port") and web_command(web["port"], command, payload): return "web" return None diff --git a/minimal/core.py b/minimal/core.py index 9fda3b9..8dd62a0 100644 --- a/minimal/core.py +++ b/minimal/core.py @@ -60,17 +60,17 @@ def stop(): def pause(): """Toggle pause on the running player.""" - _control("pause", config.SIG_STOP, "pause toggled") + _control("pause", "pause toggled") def next_track(): """Skip to the next track.""" - _control("next", config.SIG_NEXT, "next") + _control("next", "next") def prev_track(): """Go back to the previous track.""" - _control("previous", config.SIG_PREV, "previous") + _control("prev", "previous") def seek(seconds, back=False): @@ -78,18 +78,17 @@ def seek(seconds, back=False): if live_player() is None: out.fail("no player running") delta = int(seconds) * 1000 * (-1 if back else 1) - command = "seekb" if back else "seek" - sig = config.SIG_SEEK_BWD if back else config.SIG_SEEK_FWD + action = "seek_bwd" if back else "seek_fwd" with out.quiet(): config.write_seek(delta) - target = signal(command, sig, {"delta": delta}) + target = signal(action, {"delta": delta}) if target is None: out.fail("no player running") direction = "back" if back else "forward" out.emit( { "status": "ok", - "command": command, + "command": "seekb" if back else "seek", "seconds": int(seconds), "pid": _pid(target), }, @@ -97,12 +96,18 @@ def seek(seconds, back=False): ) -def _control(command, sig, label): +_EMIT_CMD = {"prev": "previous"} + + +def _control(action, label): with out.quiet(): - target = signal(command, sig) + target = signal(action) if target is None: out.fail("no player running") - out.emit({"status": "ok", "command": command, "pid": _pid(target)}, f"ok {label}") + out.emit( + {"status": "ok", "command": _EMIT_CMD.get(action, action), "pid": _pid(target)}, + f"ok {label}", + ) def _pid(target): @@ -214,7 +219,7 @@ def play_paths(paths, foreground=False, label=None): out.emit(payload, f"played {len(paths)} track(s)") return _spawn( - off_player.setup_nav_signals, + off_player._install_controls, lambda: off_commands._play_queue(paths, args), payload, label or f"playing {len(paths)} track(s)", @@ -233,7 +238,7 @@ def play_online_queue(results, foreground=False, label=None): out.emit(payload, f"played {len(results)} track(s)") return _spawn( - on_player.setup_nav_signals, + on_player._install_controls, lambda: on_commands._play_queue(results, args), payload, label or f"playing {len(results)} track(s)", @@ -278,7 +283,7 @@ def _play_online(info, title, shuffle=False, foreground=False): out.emit(payload, f"played {title}") return _spawn( - on_player.setup_nav_signals, + on_player._install_controls, lambda: on_player.play_entry(info, title, args), payload, f"playing {title}", @@ -301,7 +306,7 @@ def _play_file(path, shuffle=False, foreground=False, matches=1): out.emit(payload, f"played {title}") return _spawn( - off_player.setup_nav_signals, + off_player._install_controls, lambda: off_player.play_file(path, title, args), payload, f"playing {title}", diff --git a/minimal/extras.py b/minimal/extras.py index fdb360d..6a3ca08 100644 --- a/minimal/extras.py +++ b/minimal/extras.py @@ -4,13 +4,13 @@ import random from backend import config, library, lyrics as lyrics_mod, playlist, status -from backend.Offline import commands as off_commands from backend.Offline import file as lib from backend.Online import youtube from backend.status import _vid_from_thumb from . import core, out from .common import clock, current +from .local import _one_download def radio(seed=None, limit=None): @@ -44,27 +44,57 @@ def radio_off(seed=None, limit=None): core.play_paths(paths, label=f"radio {len(paths)} local tracks") -def tags(action=None, all_songs=False, path=None): - """Show language and artist tags, or run the backfill scan/apply.""" +def tags(action="list", args=None): + """Show tags, or maintain the free-form ones: add/remove/rename/delete.""" + args = list(args or []) if action in (None, "list"): languages, artists = library.get_tag_counts() + custom = library.all_song_tags() rows = [{"kind": "language", "tag": tag, "count": count} for tag, count in languages] rows += [{"kind": "artist", "tag": tag, "count": count} for tag, count in artists] + rows += [{"kind": "tag", "tag": tag, "count": count} for tag, count in custom] text = [f"{row['kind']:<8} {row['tag']} {row['count']}" for row in rows] - out.emit(rows, text or ["no tags yet - run: flow-min tags scan"]) + out.emit(rows, text or ["no tags yet"]) return - if action not in ("scan", "apply"): - out.fail(f"unknown tags action {action!r}; use list, scan or apply") - with out.quiet(): - if action == "scan": - off_commands.scan_tags(["-a"] if all_songs else []) - else: - off_commands.apply_tags([path] if path else []) - languages, artists = library.get_tag_counts() - out.emit( - {"action": action, "languages": len(languages), "artists": len(artists)}, - f"ok {action} ({len(languages)} languages, {len(artists)} artists)", - ) + if action in ("add", "remove"): + if len(args) < 2: + out.fail(f"tags {action} needs a song and a tag: tags {action} ") + path = _one_download(args[0]) + tag = " ".join(args[1:]).strip() + if not tag: + out.fail(f"tags {action}: empty tag") + with out.quiet(): + ok = library.set_song_tag(pathlib.Path(path).stem, tag, action == "add") + if not ok: + out.fail(f"could not {action} the tag on {args[0]!r}") + out.emit( + {"status": action, "tag": tag, "song": lib.display_name(path)}, + f"{'tagged' if action == 'add' else 'untagged'} '{tag}' on {lib.display_name(path)}", + ) + return + if action == "rename": + if len(args) < 2: + out.fail("tags rename needs a tag and its new name: rename ") + old, new = args[0], " ".join(args[1:]).strip() + with out.quiet(): + changed = library.rename_tag(old, new) + out.emit( + {"status": "renamed", "old": old, "new": new, "songs": changed}, + f"renamed '{old}' -> '{new}' ({changed} song(s))", + ) + return + if action == "delete": + if not args: + out.fail("tags delete needs a tag: delete ") + tag = " ".join(args).strip() + with out.quiet(): + changed = library.delete_tag(tag) + out.emit( + {"status": "deleted", "tag": tag, "songs": changed}, + f"deleted '{tag}' ({changed} song(s))", + ) + return + out.fail(f"unknown tags action {action!r}; use list, add, remove, rename or delete") def lyrics(): diff --git a/minimal/main.py b/minimal/main.py index d76c248..bbad212 100644 --- a/minimal/main.py +++ b/minimal/main.py @@ -3,6 +3,9 @@ import argparse import sys +from backend.platform import bootstrap_vlc + +bootstrap_vlc() from backend import history as history_mod from . import core, extras, local, out, stats @@ -110,11 +113,19 @@ def playback_flags(sub, index=True): radio.add_argument("--limit", type=int) radio.set_defaults(func=(lambda a, f=func: f(" ".join(a.seed) or None, limit=a.limit))) - tags = add("tags", "show tags, or backfill them with scan/apply") - tags.add_argument("action", nargs="?", choices=["list", "scan", "apply"], default="list") - tags.add_argument("path", nargs="?", help="preview file to apply") - tags.add_argument("-a", "--all", action="store_true", help="scan songs that already have a language tag") - tags.set_defaults(func=lambda a: extras.tags(a.action, all_songs=a.all, path=a.path)) + tags = add("tags", "show tags, or maintain them: add/remove/rename/delete") + tags.add_argument( + "action", + nargs="?", + choices=["list", "add", "remove", "rename", "delete"], + default="list", + ) + tags.add_argument( + "args", + nargs="*", + help="add/remove: rename: delete: ", + ) + tags.set_defaults(func=lambda a: extras.tags(a.action, list(a.args))) add("lyrics", "plain lyrics for the current track").set_defaults(func=lambda a: extras.lyrics()) diff --git a/minimal/out.py b/minimal/out.py index 12bf504..d413cfa 100644 --- a/minimal/out.py +++ b/minimal/out.py @@ -15,7 +15,7 @@ def init(as_json=False): _json = bool(as_json) sys.stdout.flush() previous = _stdout - _stdout = os.fdopen(os.dup(1), "w", encoding="utf-8") + _stdout = os.fdopen(os.dup(1), "w", encoding="utf-8", newline="\n") if previous is not None: previous.close() @@ -65,6 +65,10 @@ def quiet(): def fork_bg(): """Fork for background playback: the parent gets the child pid, the child goes quiet.""" sys.stdout.flush() + from backend import platform + + if not platform.can_fork(): + return None pid = os.fork() if pid: from backend import config diff --git a/flow.spec b/packaging/flow.linux.spec similarity index 75% rename from flow.spec rename to packaging/flow.linux.spec index 394fb64..fb2a658 100644 --- a/flow.spec +++ b/packaging/flow.linux.spec @@ -1,16 +1,20 @@ # -*- mode: python ; coding: utf-8 -*- +# Linux onefile build: `pyinstaller packaging/flow.linux.spec` import os +_SPEC_DIR = os.path.dirname(os.path.abspath(SPECPATH)) +_ROOT = os.path.dirname(_SPEC_DIR) if os.path.basename(_SPEC_DIR) == "packaging" else _SPEC_DIR + a = Analysis( - ["cli/main.py"], - pathex=[SPECPATH], + [os.path.join(_ROOT, "cli/main.py")], + pathex=[_ROOT], binaries=[], datas=[ - ("web/templates", "web/templates"), - ("backend/Hyprland/island.qml", "backend/Hyprland"), - ("backend/plugin_api/flow_api.py", "backend/plugin_api"), - ("pyproject.toml", "."), + (os.path.join(_ROOT, "web/templates"), "web/templates"), + (os.path.join(_ROOT, "backend/Hyprland/island.qml"), "backend/Hyprland"), + (os.path.join(_ROOT, "backend/plugin_api/flow_api.py"), "backend/plugin_api"), + (os.path.join(_ROOT, "pyproject.toml"), "."), ], hiddenimports=[ "vlc", @@ -62,7 +66,7 @@ a = Analysis( _VLC_BUNDLED = {"libvlc.so.5", "libvlccore.so.9"} _dropped = [b for b in a.binaries if os.path.basename(b[0]) not in _VLC_BUNDLED] if len(_dropped) != len(a.binaries): - print("[flow.spec] dropping bundled VLC libs: libvlc/libvlccore must come from the system") + print("[flow.linux.spec] dropping bundled VLC libs: libvlc/libvlccore must come from the system") a.binaries = _dropped pyz = PYZ(a.pure) @@ -86,4 +90,4 @@ exe = EXE( target_arch=None, codesign_identity=None, entitlements_file=None, -) +) \ No newline at end of file diff --git a/packaging/flow.macos.spec b/packaging/flow.macos.spec new file mode 100644 index 0000000..f213eb3 --- /dev/null +++ b/packaging/flow.macos.spec @@ -0,0 +1,86 @@ +# -*- mode: python ; coding: utf-8 -*- +# macOS onefile build: `pyinstaller packaging/flow.macos.spec` +# +# VLC is an external install on macOS (the .app in /Applications, or a +# Homebrew cask). python-vlc resolves libvlc at import time; `flow` calls +# backend.platform.bootstrap_vlc() before importing vlc, which points +# python-vlc at the app bundle (or /opt/homebrew|/usr/local/lib) and exports +# VLC_PLUGIN_PATH. The onefile must NOT bundle libvlc, or the bundled copy +# would lose its plugin directory. + +import os + +_SPEC_DIR = os.path.dirname(os.path.abspath(SPECPATH)) +_ROOT = os.path.dirname(_SPEC_DIR) if os.path.basename(_SPEC_DIR) == "packaging" else _SPEC_DIR + +a = Analysis( + [os.path.join(_ROOT, "cli/main.py")], + pathex=[_ROOT], + binaries=[], + datas=[ + (os.path.join(_ROOT, "web/templates"), "web/templates"), + (os.path.join(_ROOT, "backend/plugin_api/flow_api.py"), "backend/plugin_api"), + (os.path.join(_ROOT, "pyproject.toml"), "."), + ], + hiddenimports=[ + "vlc", + "psutil", + "sounddevice", + "ytmusicapi", + "yt_dlp", + "flask", + "cli", + "cli.tui", + "backend", + "backend.Online", + "backend.Online.commands", + "backend.Online.player", + "backend.Online.youtube", + "backend.Online.savan", + "backend.Offline", + "backend.Offline.commands", + "backend.Offline.player", + "backend.Offline.file", + "web", + "web.app", + "web.devlog", + "dbus_fast", + ], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=["tkinter"], + noarchive=False, + optimize=0, +) + +# Never bundle libvlc into the onefile: python-vlc must keep resolving the +# system/app-bundle library at runtime (see bootstrap_vlc). +_VLC_BUNDLED = {"libvlc.dylib", "libvlccore.dylib"} +_dropped = [b for b in a.binaries if os.path.basename(b[0]) not in _VLC_BUNDLED] +if len(_dropped) != len(a.binaries): + print("[flow.macos.spec] dropping bundled VLC libs: libvlc must come from VLC.app or brew") +a.binaries = _dropped + +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name="flow", + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=False, + upx_exclude=[], + runtime_tmpdir=None, + console=True, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) \ No newline at end of file diff --git a/packaging/flow.windows.spec b/packaging/flow.windows.spec new file mode 100644 index 0000000..40fd0a8 --- /dev/null +++ b/packaging/flow.windows.spec @@ -0,0 +1,86 @@ +# -*- mode: python ; coding: utf-8 -*- +# Windows onefile build: `pyinstaller packaging/flow.windows.spec` +# +# VLC is an external install on Windows (the portable zip or an installer). +# python-vlc resolves libvlc.dll at import time; `flow` calls +# backend.platform.bootstrap_vlc() before importing vlc, which honours +# PYTHON_VLC_LIB_PATH and exports VLC_PLUGIN_PATH, falling back to common +# install locations. The onefile must NOT bundle libvlc. + +import os + +_SPEC_DIR = os.path.dirname(os.path.abspath(SPECPATH)) +_ROOT = os.path.dirname(_SPEC_DIR) if os.path.basename(_SPEC_DIR) == "packaging" else _SPEC_DIR + +a = Analysis( + [os.path.join(_ROOT, "cli/main.py")], + pathex=[_ROOT], + binaries=[], + datas=[ + (os.path.join(_ROOT, "web/templates"), "web/templates"), + (os.path.join(_ROOT, "backend/plugin_api/flow_api.py"), "backend/plugin_api"), + (os.path.join(_ROOT, "pyproject.toml"), "."), + ], + hiddenimports=[ + "vlc", + "psutil", + "sounddevice", + "ytmusicapi", + "yt_dlp", + "flask", + "cli", + "cli.tui", + "backend", + "backend.Online", + "backend.Online.commands", + "backend.Online.player", + "backend.Online.youtube", + "backend.Online.savan", + "backend.Offline", + "backend.Offline.commands", + "backend.Offline.player", + "backend.Offline.file", + "web", + "web.app", + "web.devlog", + "dbus_fast", + ], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=["tkinter"], + noarchive=False, + optimize=0, +) + +# If PyInstaller ever picks libvlc.dll up (it is only referenced via +# ctypes at runtime, so normally it will not), drop it so the runtime +# bootstrap keeps working against the external VLC install. +_VLC_BUNDLED = {"libvlc.dll", "libvlccore.dll"} +_dropped = [b for b in a.binaries if os.path.basename(b[0]) not in _VLC_BUNDLED] +if len(_dropped) != len(a.binaries): + print("[flow.windows.spec] dropping bundled VLC libs: libvlc must come from the VLC install") +a.binaries = _dropped + +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name="flow", + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=False, + upx_exclude=[], + runtime_tmpdir=None, + console=True, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 6edb8a6..9a855e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "psutil>=7.2.2", "python-vlc", "questionary", + "rich>=13.7.0", "sounddevice", "textual>=8.2.8", "tile-twinx>=1.0.1", diff --git a/tests/conftest.py b/tests/conftest.py index cc5af4d..245af2e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,4 +14,8 @@ _TEST_HOME = tempfile.mkdtemp(prefix="flow-tests-") os.environ["HOME"] = _TEST_HOME +# pathlib.Path.home() reads USERPROFILE (not HOME) on Windows, and HOMEDRIVE/ +# HOMEPATH are its fallbacks -- set all three so the scratch tree wins there too. +os.environ["USERPROFILE"] = _TEST_HOME +os.environ["HOMEDRIVE"], os.environ["HOMEPATH"] = os.path.splitdrive(_TEST_HOME) atexit.register(shutil.rmtree, _TEST_HOME, ignore_errors=True) \ No newline at end of file diff --git a/tests/test_bars.py b/tests/test_bars.py index 514e1f3..7559511 100644 --- a/tests/test_bars.py +++ b/tests/test_bars.py @@ -80,9 +80,16 @@ def restore_config_globals(): config.ProgChar = "\u2588" config.ProgCharEm = "\u2591" config.Sensitivity = 1.0 + config.SPINNER = "|/-\\" + config.RichSpinner = "dots" + config.ProgressType = "default" config.Primary = config.CYAN config.Secondary = config.PURPLE config.Tertiary = config.BLUE + config._STYLE["primary"] = "cyan" + config._STYLE["secondary"] = "purple" + config._STYLE["tertiary"] = "blue" + config.ProgressColumns = ["bar", "percentage", "time_remaining"] config.FORMAT = "webm" config.MAX_SEARCH_RESULTS = 5 config.MAX_RESULTS_RADIO = 35 @@ -96,14 +103,22 @@ def _fake_interactive(monkeypatch, tmp_path, answers_seq): answers = iter(answers_seq) asked = [] + collected = {} class _FakePrompt: def __init__(self, **kwargs): self.kwargs = kwargs - def unsafe_ask(self): - asked.append(self.kwargs.get("name")) - return next(answers) + def unsafe_ask(self, patch_stdout=None): + when = self.kwargs.get("when") + if when is not None and not when(collected): + return None + name = self.kwargs.get("name") + value = next(answers) + if name is not None: + collected[name] = value + asked.append(name) + return value monkeypatch.setattr(config, "CONFIG_FILE", tmp_path / "config.json") monkeypatch.setattr( @@ -115,75 +130,84 @@ def unsafe_ask(self): return asked -def test_interactive_config_offers_prog_chars_for_progress( +def test_interactive_config_picks_one_setting( monkeypatch, tmp_path, capsys, restore_config_globals ): - asked = _fake_interactive( - monkeypatch, - tmp_path, - [ - "progress", "cyan", "purple", "blue", "webm", - "|", "-", - True, True, True, "5", "35", - ], - ) - # display, 3 colors, format, prog_char, prog_char_em, 3 confirms, - # max_search, max_radio — the visualizer questions (width/height/ - # spacing/char/sensitivity) must NOT fire for progress. - assert len(asked) == 12 + asked = _fake_interactive(monkeypatch, tmp_path, ["bar_width", "30"]) + assert len(asked) == 2 # one pick + one value edit + out = _clean(capsys.readouterr().out) + assert "Bar width changed to 30" in out + assert config.BarWidth == 30 + # nothing else was edited + assert config.Display == "bars" + assert config.ProgChar == "\u2588" + assert config.ProgCharEm == "\u2591" + + +def test_interactive_config_picks_display( + monkeypatch, tmp_path, capsys, restore_config_globals +): + _fake_interactive(monkeypatch, tmp_path, ["display", "rich"]) + out = _clean(capsys.readouterr().out) + assert "Display mode changed to rich" in out + assert config.Display == "rich" + + +def test_interactive_config_picks_prog_char( + monkeypatch, tmp_path, capsys, restore_config_globals +): + _fake_interactive(monkeypatch, tmp_path, ["prog_char", "|"]) out = _clean(capsys.readouterr().out) assert "Progress char changed to |" in out - assert "Progress empty char changed to -" in out - assert "Bar width" not in out - assert "Bar char changed" not in out - assert "Bar height" not in out - assert "Bar spacing" not in out - assert "Sensitivity" not in out - assert config.Display == "progress" assert config.ProgChar == "|" - assert config.ProgCharEm == "-" -def test_interactive_config_hides_bar_chars_for_lyrics( - monkeypatch, tmp_path, restore_config_globals +def test_interactive_config_picks_theme( + monkeypatch, tmp_path, capsys, restore_config_globals ): - asked = _fake_interactive( - monkeypatch, - tmp_path, - [ - "lyrics", "cyan", "purple", "blue", "webm", - True, True, True, "5", "35", - ], - ) - # display, 3 colors, format, 3 confirms, max_search, max_radio - assert len(asked) == 10 - assert config.Display == "lyrics" + _fake_interactive(monkeypatch, tmp_path, ["theme", "sunset"]) + out = _clean(capsys.readouterr().out) + assert "Theme changed to 'sunset'" in out + assert config._STYLE["primary"] == "orange1" + assert config._STYLE["secondary"] == "pink1" -def test_interactive_config_keeps_visualizer_options_for_bars( +def test_interactive_config_picks_confirm( monkeypatch, tmp_path, capsys, restore_config_globals ): - asked = _fake_interactive( - monkeypatch, - tmp_path, - [ - "bars", "cyan", "purple", "blue", "webm", - "30", "40", "1", "|", "1.0", - True, True, True, "5", "35", - ], - ) - assert len(asked) == 15 + _fake_interactive(monkeypatch, tmp_path, ["notify", False]) out = _clean(capsys.readouterr().out) - assert "Bar width changed to 30" in out - assert "Bar height changed to 40" in out - assert "Bar spacing changed to 1" in out - assert "Bar char changed to |" in out - assert "Sensitivity changed to 1.0" in out - assert "Progress char" not in out - assert config.BarWidth == 30 - assert config.BarHeight == 40 - assert config.BarSpacing == 1 - assert config.BarChar == "|" + assert "Desktop notifications set to False" in out + assert config.NOTIFY is False + + +def test_interactive_config_lists_every_setting(restore_config_globals): + config.Display = "rich" + rows = config._interactive_rows() + keys = {r[0] for r in rows} + assert len(rows) == len(keys) # no duplicate keys + for key in ( + "display", "primary", "secondary", "tertiary", "theme", "spinner", + "progress_type", "progress_columns", "format", "sensitivity", "ad_skip", + "down_on_like", "notify", "max_search", "max_radio", + ): + assert key in keys + # bar settings belong to the `bars`/plain-text displays, not rich + for key in ( + "bar_width", "bar_height", "bar_spacing", "bar_char", + "prog_char", "prog_char_em", + ): + assert key not in keys + + +def test_interactive_config_hides_rich_columns_outside_rich(restore_config_globals): + config.Display = "bars" + keys = {r[0] for r in config._interactive_rows()} + assert "progress_columns" not in keys + assert "progress_type" not in keys + assert "display" in keys + assert "bar_width" in keys + assert "spinner" in keys def test_display_mode_accepts_progress(): @@ -192,6 +216,45 @@ def test_display_mode_accepts_progress(): assert "changed to progress" in msg +def test_display_mode_accepts_rich(): + assert "rich" in config._DISPLAY_MODES + msg = config._apply_display("rich") + assert "changed to rich" in msg + + +def test_progress_columns_accept_rich_options(): + assert all(c in config._RICH_COLUMN_NAMES for c in config.ProgressColumns) + msg = config._apply_progress_columns("bar,percentage") + assert "set to" in msg + assert config.ProgressColumns == ["bar", "percentage"] + other = config._apply_progress_columns("spinner time_remaining") + assert "set to" in other + bad = config._apply_progress_columns("bogus") + assert "Unknown" in bad + assert "bar" in bad and "spinner" in bad + + +def test_rich_color_styles_accepted(): + msg = config._apply_color("primary", "#ff8800") + assert "changed to" in msg + assert config._STYLE["primary"] == "#ff8800" + bad = config._apply_color("secondary", "not_a_color") + assert "Unknown" in bad + + +def test_rich_display_panel_renders(capsys, restore_config_globals): + import backend.rich_display as rich_display + + disp = rich_display.NowPlaying("Some Track", artist="Artist", duration=120) + disp.start() + disp.update(30.0, paused=True) + disp.stop() + out = capsys.readouterr().out + assert "Some Track" in out + assert "Artist" in out + assert "[Paused]" in out + + def test_render_progress_writes_live_line(capsys): config.render_progress(63, 180, 8) out = _clean(capsys.readouterr().out) @@ -217,4 +280,202 @@ def test_youtube_progress_hook_renders_bar(capsys): def test_youtube_progress_hook_ignores_other_statuses(capsys): youtube.progress_hook({"status": "finished"}) - assert capsys.readouterr().out == "" \ No newline at end of file + assert capsys.readouterr().out == "" + + +def test_rich_progress_columns_dedupe(restore_config_globals): + import backend.rich_display as rich_display + + config.ProgressColumns = ["bar", "task", "percentage"] + columns = rich_display._progress().columns + names = [type(c).__name__ for c in columns] + assert names.count("TaskProgressColumn") == 1 + assert "BarColumn" in names + + +def test_rich_panel_width_is_small(restore_config_globals): + import backend.rich_display as rich_display + from rich.console import Console + + disp = rich_display.NowPlaying("Track", duration=60) + disp.console = Console(width=100) + assert 30 <= disp._panel_width() <= 80 + disp.console = Console(width=80) + assert disp._panel_width() == 32 + + +def test_rich_display_active_gates_on_display(monkeypatch, restore_config_globals): + import backend.rich_display as rich_display + import sys + + monkeypatch.setattr(sys.stdout, "isatty", lambda: True) + config.Display = "bars" + assert rich_display.active() is False + config.Display = "rich" + assert rich_display.active() is True + + +def test_rich_panel_renders_track_metadata(capsys, restore_config_globals): + import backend.rich_display as rich_display + from rich.console import Console + + disp = rich_display.NowPlaying("First", duration=60) + disp.console = Console(width=80) # pinned: subtitle truncation is width-sensitive + disp.start() + disp.set_track( + "Second", artist="Artist", album="Album", duration=120, status="playing" + ) + disp.update(5.0) + disp.stop() + out = capsys.readouterr().out + assert "Second" in out + assert "Artist" in out + assert "Album" in out + assert "playin" in out # subtitle truncates at the small width + + +def test_connection_spinner_delegates_to_rich(monkeypatch, restore_config_globals): + import cli.main as cli_main + import backend.rich_display as rich_display + + calls = [] + monkeypatch.setattr(rich_display, "active", lambda: True) + monkeypatch.setattr( + rich_display, "spinner_run", lambda stop, label="": calls.append(label) + ) + config.Display = "rich" + cli_main._spinner(lambda: True) + assert calls == ["Checking connection"] + + +def test_search_spinner_delegates_to_rich(monkeypatch, restore_config_globals): + from backend.Online import commands as online_commands + import backend.rich_display as rich_display + + calls = [] + monkeypatch.setattr(rich_display, "active", lambda: True) + monkeypatch.setattr( + rich_display, "spinner_run", lambda stop, label="": calls.append(label) + ) + config.Display = "rich" + online_commands._spinner(lambda: True, label="Searching") + assert calls == ["Searching"] + + +def test_download_hook_delegates_to_rich(monkeypatch, restore_config_globals): + import backend.rich_display as rich_display + + calls = [] + monkeypatch.setattr(rich_display, "active", lambda: True) + monkeypatch.setattr( + rich_display, + "download_update", + lambda got, total: calls.append((got, total)), + ) + youtube.progress_hook( + { + "status": "downloading", + "downloaded_bytes": 5_000_000, + "total_bytes": 10_000_000, + } + ) + assert calls == [(5_000_000, 10_000_000)] + + +def test_progress_type_applies_presets(restore_config_globals): + msg = config._apply_progress_type("default") + assert "changed to default" in msg + assert config.ProgressType == "default" + assert config.ProgressColumns == ["bar", "percentage", "time_remaining"] + config._apply_progress_type("download") + assert config.ProgressColumns == [ + "download", "file_size", "total_size", "transfer_speed", + ] + msg = config._apply_progress_type("pulse") + assert "changed to pulse" in msg + assert config.ProgressColumns == ["spinner"] + config._apply_progress_type("default") + + +def test_progress_type_rejects_unknown(restore_config_globals): + bad = config._apply_progress_type("bogus") + assert "Unknown progress type" in bad + assert config.ProgressType == "default" + + +def test_progress_columns_edit_marks_custom(restore_config_globals): + config._apply_progress_type("download") + config._apply_progress_columns("bar,time_remaining") + assert config.ProgressType == "custom" + assert config.ProgressColumns == ["bar", "time_remaining"] + + +def test_progress_type_custom_keeps_columns(restore_config_globals): + config._apply_progress_columns("bar,time_remaining") + msg = config._apply_progress_type("custom") + assert "custom" in msg + assert config.ProgressType == "custom" + assert config.ProgressColumns == ["bar", "time_remaining"] + config._apply_progress_type("default") + + +def test_rich_spinner_applies_and_persists(restore_config_globals): + msg = config._apply_rich_spinner("dots5") + assert "dots5" in msg + assert config.RichSpinner == "dots5" + saved = json.loads(pathlib.Path(config.CONFIG_FILE).read_text()) + assert saved["rich_spinner"] == "dots5" + config.RichSpinner = "bounce" + config._load_config() + assert config.RichSpinner == "dots5" # loaded back from file + config._apply_rich_spinner("dots") + + +def test_rich_spinner_rejects_empty(restore_config_globals): + bad = config._apply_rich_spinner("") + assert "Rich spinner must" in bad + assert config.RichSpinner == "dots" + + +def test_interactive_config_picks_progress_type( + monkeypatch, tmp_path, capsys, restore_config_globals +): + config.Display = "rich" + _fake_interactive(monkeypatch, tmp_path, ["progress_type", "download"]) + assert config.ProgressType == "download" + assert config.ProgressColumns == [ + "download", "file_size", "total_size", "transfer_speed", + ] + + +def test_interactive_config_spinner_custom( + monkeypatch, tmp_path, capsys, restore_config_globals +): + config.Display = "rich" + _fake_interactive(monkeypatch, tmp_path, ["spinner", "Custom…", "dots6"]) + assert config.RichSpinner == "dots6" + out = _clean(capsys.readouterr().out) + assert "Rich spinner set to 'dots6'" in out + + +def test_spinner_name_validates(restore_config_globals): + import backend.rich_display as rich_display + + config.RichSpinner = "dots" + assert rich_display._spinner_name() == "dots" + config.RichSpinner = "bounce" + assert rich_display._spinner_name() == "bounce" + config.RichSpinner = "|/-\\" + assert rich_display._spinner_name() == "dots" # custom chars fall back + config.RichSpinner = "dots" + + +def test_rich_spinner_column_builds(restore_config_globals): + import backend.rich_display as rich_display + + config.ProgressType = "pulse" + config.ProgressColumns = list(config._PROGRESS_TYPES["pulse"]) + columns = rich_display._progress().columns + assert any(type(c).__name__ == "SpinnerColumn" for c in columns) + config.ProgressType = "default" + config.ProgressColumns = list(config._PROGRESS_TYPES["default"]) \ No newline at end of file diff --git a/tests/test_daemon_rpc.py b/tests/test_daemon_rpc.py index 48278ee..d3f98ed 100644 --- a/tests/test_daemon_rpc.py +++ b/tests/test_daemon_rpc.py @@ -74,7 +74,7 @@ def test_raw_cli_gated_without_capability(): def test_players_method_reflects_registry(): - proc = subprocess.Popen(["sleep", "60"]) + proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) try: registry.register("vlc", proc.pid) resp = rpc.handle({"method": "players"}) @@ -105,7 +105,7 @@ def test_pause_routes_to_web_command_file_when_no_player(): # E2E: real daemon socket # --------------------------------------------------------------------------- -@pytest.mark.skipif(not HAS_FLOW, reason="flow binary not available") +@pytest.mark.skipif(not HAS_FLOW or os.name == "nt", reason="flow binary not available, or Windows socket daemon not exercised here") def test_daemon_socket_e2e(): flow = _flow_bin() sock_path = str(Path(os.environ["HOME"]) / ".flow/flow.sock") diff --git a/tests/test_ipc_control.py b/tests/test_ipc_control.py new file mode 100644 index 0000000..3ce16cb --- /dev/null +++ b/tests/test_ipc_control.py @@ -0,0 +1,64 @@ +"""Control IPC round-trips: the localhost control socket (all OSes) plus the +POSIX signal path, both delivered to an in-process dispatch handler.""" + +import os +import time + +from backend import ipc, registry + + +def _wait(cond, timeout=2.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if cond(): + return True + time.sleep(0.02) + return False + + +def test_socket_control_round_trip(): + """A registry entry with a ctl_port receives actions over the socket.""" + received = [] + ipc._dispatch = lambda action, payload=None: received.append((action, payload)) + port = ipc._start_server() + try: + registry.register("vlc", os.getpid(), ctl_port=port) + assert ipc.send_to("vlc", "pause") is True + assert ipc.send_to("vlc", "seek_fwd", {"delta": 5000}) is True + assert _wait(lambda: ("pause", None) in received) + assert _wait(lambda: ("seek_fwd", {"delta": 5000}) in received) + finally: + registry.clear() + ipc._dispatch = None + + +def test_signal_control_round_trip_on_posix(): + """On Linux, actions with a mapped signal reach the handler via os.kill.""" + if os.name == "nt" or ipc.signal_for("pause") is None: + return + received = [] + ipc.serve(lambda action, payload=None: received.append(action), kind="vlc") + try: + registry.register("vlc", os.getpid()) + assert ipc.send_to("vlc", "pause") is True + assert _wait(lambda: "pause" in received) + finally: + registry.clear() + + +def test_send_is_false_for_unknown_entry(): + assert ipc.send(None, "pause") is False + assert ipc.send({}, "pause") is False + + +def test_windows_control_is_socket_only(): + """On Windows there are no control signals: only the ctl_port socket works.""" + if os.name != "nt": + return + assert ipc.signal_for("pause") is None + ipc._dispatch = lambda action, payload=None: None + registry.register("vlc", os.getpid()) # no ctl_port -> no signal path + try: + assert ipc.send_to("vlc", "pause") is False + finally: + registry.clear() \ No newline at end of file diff --git a/tests/test_minimal.py b/tests/test_minimal.py index 89d4d17..1caab1c 100644 --- a/tests/test_minimal.py +++ b/tests/test_minimal.py @@ -309,15 +309,24 @@ def test_control_without_a_player_fails(capfd): def test_seek_writes_the_delta_before_signalling(capfd): - registry.register("vlc", os.getpid()) - start() - core.seek(30) - assert "ok seek forward 30s" in read(capfd)[0] - assert config.read_seek() == 30000 - core.seek(10, back=True) - assert "ok seek back 10s" in read(capfd)[0] - assert config.read_seek() == -10000 - config.clear_seek() + from backend import ipc as _ipc + + # Linux signals the player; macOS/Windows have no seek signal, so deliver + # over the same localhost control socket a real player would use. + port = None if _ipc.signal_for("seek_fwd") is not None else _ipc._start_server() + registry.register("vlc", os.getpid(), ctl_port=port) + try: + start() + core.seek(30) + assert "ok seek forward 30s" in read(capfd)[0] + assert config.read_seek() == 30000 + core.seek(10, back=True) + assert "ok seek back 10s" in read(capfd)[0] + assert config.read_seek() == -10000 + config.clear_seek() + finally: + registry.clear() + config.clear_seek() def test_list_songs_is_sorted_and_filterable(capfd): @@ -436,10 +445,11 @@ def test_parser_covers_every_command(): ["radio", "--limit", "10"], ["radio-off", "--limit", "5"], ["tags"], - ["tags", "scan"], - ["tags", "scan", "-a"], - ["tags", "apply"], - ["tags", "apply", "/tmp/preview.tsv"], + ["tags", "list"], + ["tags", "add", "some", "anthem", "workout"], + ["tags", "remove", "some", "anthem", "workout"], + ["tags", "rename", "workout", "gym"], + ["tags", "delete", "workout"], ["lyrics"], ["playlist", "chill"], ["pl", "chill", "create"], diff --git a/tests/test_offline_radio_seed.py b/tests/test_offline_radio_seed.py index 72749f8..310755d 100644 --- a/tests/test_offline_radio_seed.py +++ b/tests/test_offline_radio_seed.py @@ -14,6 +14,7 @@ assertions are about ordering and argument handling, not disk scanning. """ +import os import pathlib import pytest @@ -88,6 +89,7 @@ def test_an_unknown_song_name_is_reported_not_ignored(): assert offline._radio_queue("no such song") is None +@pytest.mark.skipif(os.name == "nt", reason="pty is POSIX-only") def test_the_queue_is_published_for_the_next_index(monkeypatch): """`radio ` publishes its queue the way online mode publishes tracks.""" import os diff --git a/tests/test_offline_tags.py b/tests/test_offline_tags.py index 4bc8109..62b04c5 100644 --- a/tests/test_offline_tags.py +++ b/tests/test_offline_tags.py @@ -1,9 +1,9 @@ -"""Tests for playing the library by tag: `lang`, `artist` and `tags`. +"""Tests for tags: `lang`, `artist` playback and the `tags` editor/commands. A tag only works if the numbers add up: `lang punjabi` has to reach the punjabi songs and nothing else, `artist karan` has to reach the Karan Aujla -songs, both ascending by name, and `tags scan` must not touch `library.db` -before `tags apply` runs. +songs, both ascending by name. `tags` adds, removes, renames and deletes +free-form tags and the language/artist columns directly in `library.db`. Uses the scratch `HOME` from `conftest.py`; playback is faked so the assertions are about which songs were queued, not about VLC. @@ -29,6 +29,8 @@ def _args(**flags): @pytest.fixture(autouse=True) def fake_library(monkeypatch, tmp_path): + with library._write() as conn: + conn.execute("DELETE FROM song_tags") songs = {} for idx, (name, language, artist) in enumerate( ( @@ -121,63 +123,191 @@ def test_lang_is_not_an_online_command(): assert "artist" in online.COMMANDS -def test_tags_scan_writes_a_file_and_changes_nothing(monkeypatch, tmp_path): - preview = tmp_path / "tags-preview.tsv" - monkeypatch.setattr(offline, "PREVIEW_FILE", preview) +def test_tags_add_puts_a_free_form_tag_on_one_song(fake_library, capsys): + offline.tags_cmd(["add", "Zed", "roadtrip"], _args()) + assert library.song_tags("tagplay0") == ["roadtrip"] + assert "Tagged" in capsys.readouterr().out + + +def test_tags_add_matches_by_list_index_too(fake_library, monkeypatch): monkeypatch.setattr( - "backend.Online.youtube.fetch_info", - lambda video_id: {"title": "Zed Track", "language": "pa"}, + offline.lib, + "get_songs", + lambda: [ + pathlib.Path("/songs/tagplay2.opus"), + pathlib.Path("/songs/tagplay0.opus"), + ], ) - library.track_download("scanvid", str(tmp_path / "scanvid.opus"), "Scan Me") + offline.tags_cmd(["add", "1", "workout"], _args()) + assert library.song_tags("tagplay2") == ["workout"] + - offline.tags_cmd(["scan"], _args()) +def test_tags_remove_takes_a_tag_off_a_song(fake_library): + library.set_song_tag("tagplay0", "roadtrip", True) + offline.tags_cmd(["remove", "Zed", "roadtrip"], _args()) + assert library.song_tags("tagplay0") == [] - body = preview.read_text().splitlines() - assert body[0].startswith("# video_id") - assert any("scanvid\tpunjabi\t" in line for line in body) - assert (library.get("scanvid").get("language") or "") == "" +def test_edit_field_delete_picks_several_tags(fake_library, monkeypatch): + from backend import ui -def test_tags_apply_saves_language_and_only_fills_a_missing_artist(monkeypatch, tmp_path): - preview = tmp_path / "tags-preview.tsv" - preview.write_text( - "# video_id\tlanguage\tartist\ttitle\n" - "tagplay0\tpunjabi\tSomebody New\tZed Track\n" - "tagplay1\thindi\tArijit Singh\tAlpha Track\n" + monkeypatch.setattr( + ui, "pick_many", lambda q, c, **kw: (["punjabi", "hindi"], True) ) - monkeypatch.setattr(offline, "PREVIEW_FILE", preview) + monkeypatch.setattr(offline, "_ask_confirm", lambda prompt, style: True) + offline._edit_field_delete("language", "Language", "style") + langs = dict(library.get_tag_counts()[0]) + assert "punjabi" not in langs + assert "hindi" not in langs - offline.tags_cmd(["apply"], _args()) - assert library.get("tagplay0")["language"] == "punjabi" - assert library.get("tagplay0")["artist"] == "Karan Aujla" - assert library.get("tagplay1")["artist"] == "Arijit Singh" +def test_edit_field_clear_picks_several_songs(fake_library, monkeypatch): + monkeypatch.setattr( + offline, "_pick_songs", lambda prompt: ["tagplay0", "tagplay1"] + ) + monkeypatch.setattr(offline, "_ask_confirm", lambda prompt, style: True) + offline._edit_field_clear("language", "Language", "style") + langs = dict(library.get_tag_counts()[0]) + assert "hindi" not in langs + assert langs.get("punjabi") == 1 -def test_tags_apply_skips_rows_that_are_gone(monkeypatch, tmp_path, capsys): - preview = tmp_path / "tags-preview.tsv" - preview.write_text("ghostvid\thindi\tNobody\tVanished\n") - monkeypatch.setattr(offline, "PREVIEW_FILE", preview) +def test_edit_custom_delete_picks_several_tags(fake_library, monkeypatch): + from backend import ui - offline.tags_cmd(["apply"], _args()) + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay1", "gym", True) + library.set_song_tag("tagplay2", "roadtrip", True) + monkeypatch.setattr( + ui, "pick_many", lambda q, c, **kw: (["roadtrip", "gym"], True) + ) + monkeypatch.setattr(offline, "_ask_confirm", lambda prompt, style: True) + offline._edit_custom_delete("style") + assert library.all_song_tags() == [] - assert "no longer in the library" in capsys.readouterr().out +def test_edit_custom_remove_picks_several_songs(fake_library, monkeypatch): + from backend import ui -def test_tags_apply_without_a_preview_explains_itself(monkeypatch, tmp_path, capsys): - monkeypatch.setattr(offline, "PREVIEW_FILE", tmp_path / "nothing.tsv") - offline.tags_cmd(["apply"], _args()) - assert "run: tags scan" in capsys.readouterr().out + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay1", "roadtrip", True) + monkeypatch.setattr( + offline, "_pick_songs", lambda prompt: ["tagplay0", "tagplay1"] + ) + monkeypatch.setattr(ui, "pick", lambda q, c, **kw: ("roadtrip", True)) + offline._edit_custom_remove("style") + assert library.song_tags("tagplay0") == [] + assert library.song_tags("tagplay1") == [] + assert library.song_tags("tagplay2") == [] -def test_an_unknown_tags_action_lists_the_ones_that_work(capsys): - offline.tags_cmd(["frobnicate"], _args()) - assert "tags scan" in capsys.readouterr().out +def test_edit_custom_clear_picks_several_songs(fake_library, monkeypatch, capsys): + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay1", "gym", True) + monkeypatch.setattr( + offline, "_pick_songs", lambda prompt: ["tagplay0", "tagplay1"] + ) + monkeypatch.setattr(offline, "_ask_confirm", lambda prompt, style: True) + offline._edit_custom_clear("style") + assert library.song_tags("tagplay0") == [] + assert library.song_tags("tagplay1") == [] + assert "Cleared 2 tag(s) from 2 song(s)" in capsys.readouterr().out + + +def test_tags_rename_renames_a_tag_everywhere(fake_library): + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay1", "roadtrip", True) + offline.tags_cmd(["rename", "roadtrip", "driving"], _args()) + assert library.song_tags("tagplay0") == ["driving"] + assert library.song_tags("tagplay1") == ["driving"] + assert library.all_song_tags() == [("driving", 2)] + +def test_tags_delete_drops_a_tag_everywhere(fake_library): + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay1", "roadtrip", True) + offline.tags_cmd(["delete", "roadtrip"], _args()) + assert library.all_song_tags() == [] -def test_tags_lists_languages_and_artists(fake_library, capsys): - offline.tags_cmd([], _args()) + +def test_tags_list_shows_languages_artists_and_free_form_tags(fake_library, capsys): + library.set_song_tag("tagplay0", "roadtrip", True) + offline.tags_cmd(["list"], _args()) out = capsys.readouterr().out assert "Languages:" in out assert "punjabi (2)" in out - assert "Artists:" in out \ No newline at end of file + assert "Artists:" in out + assert "Tags:" in out + assert "roadtrip (1)" in out + + +def test_the_preview_file_flow_is_gone(): + assert not hasattr(offline, "scan_tags") + assert not hasattr(offline, "apply_tags") + assert not hasattr(offline, "PREVIEW_FILE") + + +def test_an_unknown_tags_action_lists_the_ones_that_work(capsys): + offline.tags_cmd(["frobnicate"], _args()) + out = capsys.readouterr().out + assert "tags add" in out + assert "tags delete" in out + + +def test_song_tags_are_sorted_and_counted(fake_library): + library.set_song_tag("tagplay0", "roadtrip", True) + library.set_song_tag("tagplay0", "gym", True) + library.set_song_tag("tagplay1", "roadtrip", True) + assert library.song_tags("tagplay0") == ["gym", "roadtrip"] + assert library.all_song_tags() == [("roadtrip", 2), ("gym", 1)] + + +def test_rename_tag_merges_instead_of_duplicating(fake_library): + library.set_song_tag("tagplay0", "gym", True) + library.set_song_tag("tagplay0", "workout", True) + library.set_song_tag("tagplay1", "workout", True) + assert library.rename_tag("workout", "gym") == 2 + assert library.song_tags("tagplay0") == ["gym"] + assert library.all_song_tags() == [("gym", 2)] + + +def test_clearing_a_download_drops_its_free_form_tags(fake_library): + library.set_song_tag("tagplay0", "roadtrip", True) + library.clear_download("tagplay0") + assert library.song_tags("tagplay0") == [] + assert library.all_song_tags() == [] + + +def test_set_song_field_sets_and_clears(fake_library): + assert library.set_song_field("tagplay0", "language", "telugu") + assert library.get("tagplay0")["language"] == "telugu" + assert library.set_song_field("tagplay0", "language", "") + assert library.get("tagplay0")["language"] is None + + +def test_tag_mutation_refuses_unknown_songs(): + assert not library.set_song_tag("ghost", "roadtrip", True) + assert not library.set_song_field("ghost", "language", "hindi") + + +def test_rename_field_tag_is_comma_aware(fake_library): + changed = library.rename_field_tag("artist", "Ikky", "Ikky Singh") + assert changed == 1 + assert library.get("tagplay2")["artist"] == "Karan Aujla, Ikky Singh" + + +def test_delete_field_tag_keeps_the_other_parts(fake_library): + changed = library.delete_field_tag("artist", "Ikky") + assert changed == 1 + assert library.get("tagplay2")["artist"] == "Karan Aujla" + + +def test_delete_field_tag_clears_a_sole_value_to_none(fake_library): + changed = library.delete_field_tag("language", "hindi") + assert changed == 1 + assert library.get("tagplay1")["language"] is None + + +def test_field_tag_matching_is_case_insensitive(fake_library): + assert library.rename_field_tag("artist", "ikky", "Ikky S.") == 1 + assert library.get("tagplay2")["artist"] == "Karan Aujla, Ikky S." \ No newline at end of file diff --git a/tests/test_registry.py b/tests/test_registry.py index 2d05f2e..fc7df8d 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -5,12 +5,14 @@ """ import subprocess +import sys from backend import config, registry def _sleeper(): - return subprocess.Popen(["sleep", "60"]) + # `sleep` is a POSIX binary; a tiny Python process sleeps on every OS. + return subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) def _wait_dead(proc): diff --git a/tests/test_shell_quit_key.py b/tests/test_shell_quit_key.py index 3406f79..953698e 100644 --- a/tests/test_shell_quit_key.py +++ b/tests/test_shell_quit_key.py @@ -10,12 +10,16 @@ """ import os + +import pytest + +if os.name == "nt": + pytest.skip("pty/termios are POSIX-only", allow_module_level=True) + import pty import signal import termios -import pytest - from cli import tui diff --git a/tests/test_ui.py b/tests/test_ui.py new file mode 100644 index 0000000..23ecaf3 --- /dev/null +++ b/tests/test_ui.py @@ -0,0 +1,26 @@ +from backend import config +from backend import ui + + +def test_questionary_style_builds_from_current_palette(): + # Both modes must build a valid prompt_toolkit Style from the rich + # palette (named colors, hex, styled strings) without ValueError. + online = ui.questionary_style("online") + offline = ui.questionary_style("offline") + assert str(online) + assert str(offline) + assert ui.questionary_style() is not None + + +def test_cname_resolves_ansi_codes_from_rich_styles(): + # ANSI codes that still reach _cname (old call sites / plugins) + # must resolve back to a prompt_toolkit color instead of crashing. + for code in (config.Primary, config.Secondary, config.Tertiary): + color = config._cname(code) + assert color + assert color != code # resolved, not passed through raw + + +def test_cname_resolves_arbitrary_rich_styles(): + assert config._cname("#ff8800") == "#ff8800" + assert config._cname("bold spring_green3").startswith("#") \ No newline at end of file diff --git a/tests/test_vlc_bootstrap.py b/tests/test_vlc_bootstrap.py new file mode 100644 index 0000000..0c33260 --- /dev/null +++ b/tests/test_vlc_bootstrap.py @@ -0,0 +1,103 @@ +"""Unit tests for `backend.platform.bootstrap_vlc` — python-vlc env hints. + +python-vlc resolves libvlc at ``import vlc`` time, so the bootstrap must pick +the right library/plugin dirs on macOS and Windows before any import. These +tests fake the OS detection and the filesystem layout (the app bundle / the +portable VLC tree) and assert the exported ``PYTHON_VLC_*`` vars. +""" + +import os +import pathlib + +from backend import platform + + +def _clear(monkeypatch): + monkeypatch.delenv("PYTHON_VLC_LIB_PATH", raising=False) + monkeypatch.delenv("PYTHON_VLC_MODULE_PATH", raising=False) + + +def test_linux_is_a_noop(monkeypatch): + _clear(monkeypatch) + monkeypatch.setattr(platform, "is_linux", lambda: True) + monkeypatch.setattr(platform, "is_macos", lambda: False) + monkeypatch.setattr(platform, "is_windows", lambda: False) + platform.bootstrap_vlc() + assert "PYTHON_VLC_LIB_PATH" not in os.environ + assert "PYTHON_VLC_MODULE_PATH" not in os.environ + + +def test_macos_locates_the_app_bundle(monkeypatch, tmp_path): + _clear(monkeypatch) + app = tmp_path / "VLC.app" / "Contents" / "MacOS" + (app / "lib").mkdir(parents=True) + (app / "plugins").mkdir() + (app / "lib" / "libvlc.dylib").write_bytes(b"x") + (app / "lib" / "libvlccore.dylib").write_bytes(b"x") + real_path = pathlib.Path + + def fake_path(p): + p = str(p) + if p.startswith("/Applications/VLC.app"): + p = p.replace("/Applications/VLC.app", str(tmp_path / "VLC.app")) + return real_path(p) + + monkeypatch.setattr(platform, "Path", fake_path) + monkeypatch.setattr(platform, "is_linux", lambda: False) + monkeypatch.setattr(platform, "is_macos", lambda: True) + monkeypatch.setattr(platform, "is_windows", lambda: False) + platform.bootstrap_vlc() + # Never pin the lib path on macOS: python-vlc must preload libvlccore. + assert "PYTHON_VLC_LIB_PATH" not in os.environ + assert os.environ["PYTHON_VLC_MODULE_PATH"].endswith("plugins") + + +def test_macos_homebrew_fallback_uses_dyld(monkeypatch, tmp_path): + _clear(monkeypatch) + monkeypatch.delenv("DYLD_LIBRARY_PATH", raising=False) + libdir = tmp_path / "lib" + (libdir / "vlc" / "plugins").mkdir(parents=True) + (libdir / "libvlc.dylib").write_bytes(b"x") + real_path = pathlib.Path + + def fake_path(p): + p = str(p) + if p.startswith("/opt/homebrew"): + p = p.replace("/opt/homebrew", str(tmp_path)) + elif p.startswith("/Applications"): + p = p.replace("/Applications", str(tmp_path / "extra")) + return real_path(p) + + monkeypatch.setattr(platform, "Path", fake_path) + monkeypatch.setattr(platform, "is_linux", lambda: False) + monkeypatch.setattr(platform, "is_macos", lambda: True) + monkeypatch.setattr(platform, "is_windows", lambda: False) + platform.bootstrap_vlc() + assert "PYTHON_VLC_LIB_PATH" not in os.environ + assert os.environ["DYLD_LIBRARY_PATH"].startswith("/opt/homebrew/lib") + + +def test_windows_locates_installed_vlc(monkeypatch, tmp_path): + _clear(monkeypatch) + vlc_dir = tmp_path / "VideoLAN" / "VLC" + (vlc_dir / "plugins").mkdir(parents=True) + (vlc_dir / "libvlc.dll").write_bytes(b"x") + monkeypatch.setattr(platform, "Path", pathlib.Path) + monkeypatch.setattr(platform, "is_linux", lambda: False) + monkeypatch.setattr(platform, "is_macos", lambda: False) + monkeypatch.setattr(platform, "is_windows", lambda: True) + monkeypatch.setenv("LOCALAPPDATA", str(tmp_path)) + platform.bootstrap_vlc() + assert os.environ["PYTHON_VLC_LIB_PATH"] == str(vlc_dir / "libvlc.dll") + assert os.environ["PYTHON_VLC_MODULE_PATH"] == str(vlc_dir / "plugins") + + +def test_pre_set_lib_path_is_trusted(monkeypatch): + monkeypatch.setenv("PYTHON_VLC_LIB_PATH", "C:\\fake\\libvlc.dll") + monkeypatch.delenv("PYTHON_VLC_MODULE_PATH", raising=False) + monkeypatch.setattr(platform, "is_linux", lambda: False) + monkeypatch.setattr(platform, "is_macos", lambda: True) + monkeypatch.setattr(platform, "is_windows", lambda: False) + platform.bootstrap_vlc() + assert os.environ["PYTHON_VLC_LIB_PATH"] == "C:\\fake\\libvlc.dll" + assert "PYTHON_VLC_MODULE_PATH" not in os.environ \ No newline at end of file diff --git a/tui/__init__.py b/tui/__init__.py index ccb9451..599bfc1 100644 --- a/tui/__init__.py +++ b/tui/__init__.py @@ -1,5 +1,4 @@ import argparse -import os def _running_pid(): @@ -13,23 +12,19 @@ def _running_pid(): return None -def _is_tui_pid(pid): - """True when the pid belongs to a running Flow TUI.""" - from backend import registry - - entry = registry.resolve("tui") - return entry is not None and entry["pid"] == pid +def _control(action, label, require_tui=False): + from backend import ipc, registry - -def _control(sig, label, require_tui=False): pid = _running_pid() if pid is None: return False, f"{label}: no running Flow player (start `flowt` first)" - if require_tui and not _is_tui_pid(pid): - return False, f"{label}: no running Flow TUI (start `flowt` first)" - try: - os.kill(pid, sig) - except ProcessLookupError: + if require_tui: + entry = registry.resolve("tui") + if entry is None or entry["pid"] != pid: + return False, f"{label}: no running Flow TUI (start `flowt` first)" + else: + entry = registry.resolve("vlc") or registry.resolve("tui") + if not ipc.send(entry, action): return False, f"{label}: player PID {pid} is gone" return True, f"{label} (PID {pid})" @@ -81,24 +76,24 @@ def main(): _show_status() return - from backend import config - controls = ( - (args.pause, config.SIG_STOP, "Pause toggled", False), - (args.next, config.SIG_NEXT, "Next", False), - (args.previous, config.SIG_PREV, "Previous", False), - (args.repeat, config.SIG_REPEAT, "Repeat toggled", True), - (args.shuffle, config.SIG_SHUFFLE, "Shuffle toggled", True), + (args.pause, "pause", "Pause toggled", False), + (args.next, "next", "Next", False), + (args.previous, "prev", "Previous", False), + (args.repeat, "repeat", "Repeat toggled", True), + (args.shuffle, "shuffle", "Shuffle toggled", True), ) active = [ - (sig, label, require_tui) for flag, sig, label, require_tui in controls if flag + (action, label, require_tui) + for flag, action, label, require_tui in controls + if flag ] hard = args.pause or args.next or args.previous if active and _running_pid() is not None: delivered = True - for sig, label, require_tui in active: - ok, msg = _control(sig, label, require_tui=require_tui) + for action, label, require_tui in active: + ok, msg = _control(action, label, require_tui=require_tui) print(msg) if require_tui and not ok: delivered = False diff --git a/tui/main.py b/tui/main.py index ee66e5d..7c20944 100644 --- a/tui/main.py +++ b/tui/main.py @@ -4,7 +4,6 @@ import os import pathlib import random -import signal import threading import time from dataclasses import dataclass @@ -27,7 +26,10 @@ Static, ) -from backend import config, history, library, mpris, sponsor, status +from backend.platform import bootstrap_vlc + +bootstrap_vlc() +from backend import config, history, ipc, library, mpris, sponsor, status from backend.Offline import file as offline_file from backend.Online import youtube @@ -405,9 +407,9 @@ def on_mount(self) -> None: self._update_mode_ui() self._reload_library() self._loop = asyncio.get_running_loop() - config.save_pid_if_free(os.getpid()) - config.save_tui_pid(os.getpid()) - self._install_signals() + port = ipc.serve(self._signal_dispatch, kind="tui") + config.save_pid_if_free(os.getpid(), ctl_port=port) + config.save_tui_pid(os.getpid(), ctl_port=port) def _apply_launch_modes(self) -> None: np = self.now_playing @@ -418,22 +420,6 @@ def _apply_launch_modes(self) -> None: if self._repeat or self._shuffle: np.refresh_status() - def _install_signals(self) -> None: - for sig, action in ( - (signal.SIGUSR1, "pause"), - (signal.SIGUSR2, "next"), - (config.SIG_PREV, "prev"), - (config.SIG_REPEAT, "repeat"), - (config.SIG_SHUFFLE, "shuffle"), - (config.SIG_STOP_ALL, "stop"), - (config.SIG_SEEK_FWD, "seek"), - (config.SIG_SEEK_BWD, "seek"), - ): - try: - signal.signal(sig, lambda *_, a=action: self._signal_dispatch(a)) - except (ValueError, OSError): - pass - def _signal_dispatch(self, action: str) -> None: if self._loop is None: return @@ -451,9 +437,9 @@ def _signal_action(self, action: str) -> None: self.action_toggle_repeat() elif action == "shuffle": self.action_toggle_shuffle() - elif action == "stop": + elif action in ("stop", "stop_all"): self.action_stop() - elif action == "seek": + elif action in ("seek", "seek_fwd", "seek_bwd"): self._apply_seek() except Exception: pass diff --git a/uv.lock b/uv.lock index d22045b..7414578 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.14" [[package]] @@ -259,6 +259,7 @@ dependencies = [ { name = "pygobject", marker = "sys_platform == 'linux'" }, { name = "python-vlc" }, { name = "questionary" }, + { name = "rich" }, { name = "sounddevice" }, { name = "textual" }, { name = "tile-twinx" }, @@ -282,6 +283,7 @@ requires-dist = [ { name = "pygobject", marker = "sys_platform == 'linux'", specifier = ">=3.58.0" }, { name = "python-vlc" }, { name = "questionary" }, + { name = "rich", specifier = ">=13.7.0" }, { name = "sounddevice" }, { name = "textual", specifier = ">=8.2.8" }, { name = "tile-twinx", specifier = ">=1.0.1" }, diff --git a/web/main.py b/web/main.py index f213743..268a3e6 100644 --- a/web/main.py +++ b/web/main.py @@ -1,7 +1,7 @@ import argparse import builtins import os -import signal +import subprocess import sys import time import warnings @@ -9,6 +9,11 @@ import psutil +from backend.platform import bootstrap_vlc + +bootstrap_vlc() +from backend import platform + WEB_PID = Path.home() / ".flow/web.pid" WEB_PORT_FILE = Path.home() / ".flow/web_port" @@ -131,7 +136,7 @@ def _stop_all(): return 0 -def _start_server(new, port): +def _start_server(new, port, spawned=False): from backend import config P = config.Primary @@ -171,10 +176,7 @@ def _start_server(new, port): break time.sleep(0.2) else: - try: - os.kill(existing_pid, signal.SIGTERM) - except ProcessLookupError: - pass + platform.kill_pid(existing_pid) WEB_PID.unlink(missing_ok=True) WEB_PORT_FILE.unlink(missing_ok=True) from backend import registry @@ -193,18 +195,40 @@ def _start_server(new, port): warnings.filterwarnings( "ignore", category=DeprecationWarning, message=".*fork.*" ) - pid = os.fork() - if pid > 0: - WEB_PID.write_text(str(pid)) + if not spawned and platform.can_fork(): + pid = os.fork() + if pid > 0: + WEB_PID.write_text(str(pid)) + WEB_PORT_FILE.write_text(str(port)) + from backend import registry + + registry.register("web", pid, port=port) + print(f"{P}Flow web server → http://127.0.0.1:{port}{R}") + return + devnull = os.open(os.devnull, os.O_RDWR) + os.dup2(devnull, 1) + os.dup2(devnull, 2) + _run_web(port) + return + if not spawned: + proc = platform.spawn_detached( + [sys.executable, "-m", "web.main", f"--_spawn={port}"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + WEB_PID.write_text(str(proc.pid)) WEB_PORT_FILE.write_text(str(port)) from backend import registry - registry.register("web", pid, port=port) + registry.register("web", proc.pid, port=port) print(f"{P}Flow web server → http://127.0.0.1:{port}{R}") return - devnull = os.open(os.devnull, os.O_RDWR) - os.dup2(devnull, 1) - os.dup2(devnull, 2) + WEB_PID.write_text(str(os.getpid())) + WEB_PORT_FILE.write_text(str(port)) + from backend import registry + + registry.register("web", os.getpid(), port=port) _run_web(port) else: WEB_PID.write_text(str(os.getpid())) @@ -247,13 +271,19 @@ def main(): metavar="PORT", help="start the web server on a specific port", ) + parser.add_argument( + "--_spawn", + type=int, + default=None, + help=argparse.SUPPRESS, + ) args = parser.parse_args() if args.stop_all: sys.exit(_stop_all()) if args.stop is not None: sys.exit(_stop_port(args.stop or _default_web_port())) - _start_server(new=args.new, port=args.port) + _start_server(new=args.new, port=args.port or args._spawn, spawned=args._spawn is not None) if __name__ == "__main__":