diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..6626bd3 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,5 @@ +[build] +# The manual FJS publisher runs Cargo from this workspace with an external +# manifest path. Normal client builds only compile the tiny Rust resource. +rustc-wrapper = "kache" +incremental = false diff --git a/.github/workflows/client.yml b/.github/workflows/client.yml new file mode 100644 index 0000000..30f1cf5 --- /dev/null +++ b/.github/workflows/client.yml @@ -0,0 +1,166 @@ +name: Client + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: client-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: ${{ matrix.target }} + runs-on: ${{ matrix.runner }} + env: + RUSTUP_TOOLCHAIN: 1.98.1-${{ matrix.rust_host }} + KACHE_CONFIG: ${{ github.workspace }}/.kache.toml + strategy: + fail-fast: false + matrix: + include: + - target: macos-arm64 + runner: macos-15 + cli: listenbox + rust_host: aarch64-apple-darwin + - target: macos-x64 + runner: macos-15-intel + cli: listenbox + rust_host: x86_64-apple-darwin + - target: windows-x64 + runner: windows-2025 + cli: listenbox.exe + rust_host: x86_64-pc-windows-msvc + - target: windows-arm64 + runner: windows-11-arm + cli: listenbox.exe + rust_host: aarch64-pc-windows-msvc + - target: linux-x64 + runner: ubuntu-24.04 + cli: listenbox + rust_host: x86_64-unknown-linux-gnu + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - uses: subosito/flutter-action@v2 + if: matrix.target != 'windows-arm64' + with: + channel: stable + flutter-version: '3.47.5' + cache: true + # The Flutter 3.47.5 Windows archive contains only x64 Dart. A source + # checkout bootstraps the pinned native ARM64 Dart and engine artifacts. + - name: Set up native Windows ARM64 Flutter SDK + if: matrix.target == 'windows-arm64' + shell: pwsh + run: | + $flutterDir = Join-Path $env:RUNNER_TEMP 'flutter-arm64' + git clone --depth 1 --branch 3.47.5 https://github.com/flutter/flutter.git $flutterDir + if ($LASTEXITCODE -ne 0) { throw 'Flutter checkout failed.' } + & (Join-Path $flutterDir 'bin/flutter.bat') --version + if ($LASTEXITCODE -ne 0) { throw 'Flutter bootstrap failed.' } + $dartVersion = & (Join-Path $flutterDir 'bin/dart.bat') --version 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -or $dartVersion -notmatch 'windows_arm64') { + throw "Expected native Windows ARM64 Dart: $dartVersion" + } + (Join-Path $flutterDir 'bin') >> $env:GITHUB_PATH + (Join-Path $flutterDir 'bin/cache/dart-sdk/bin') >> $env:GITHUB_PATH + - uses: moonrepo/setup-toolchain@v0 + if: matrix.target != 'windows-arm64' + with: + moon-version: '2.5.5' + # Moon 2.5.5 has no Windows ARM64 binary. Only the task runner is emulated; + # Flutter and Dart above remain native ARM64. + - name: Set up Moon on Windows ARM64 + if: matrix.target == 'windows-arm64' + shell: pwsh + run: | + $tools = Join-Path $env:RUNNER_TEMP 'moon-x64' + New-Item -ItemType Directory -Force $tools | Out-Null + $archive = Join-Path $tools 'moon.zip' + Invoke-WebRequest 'https://github.com/moonrepo/moon/releases/download/v2.5.5/moon_cli-x86_64-pc-windows-msvc.zip' -OutFile $archive + $expected = '36d4d88284f3444d3e5759f69b7f181eb807a3bcd20ce0bf475099132b41eb74' + if ((Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { + throw 'Moon archive checksum mismatch.' + } + Expand-Archive $archive -DestinationPath $tools + $tools >> $env:GITHUB_PATH + - name: Install native Rust 1.98.1 for YouTube.js resource asset + run: | + rustup toolchain install 1.98.1-${{ matrix.rust_host }} --profile minimal + rustup default 1.98.1-${{ matrix.rust_host }} + - name: Verify native Rust host + shell: bash + run: | + rustc -vV | grep -F 'host: ${{ matrix.rust_host }}' + - name: Restore shared Rust compiler cache + uses: actions/cache@v6 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + ${{ runner.temp }}/kache + key: client2-rust-kache-v1-0.27.0-${{ matrix.target }}-${{ hashFiles('.kache.toml', '.cargo/config.toml', 'rust-toolchain.toml') }}-${{ github.workflow }}-${{ github.sha }} + restore-keys: | + client2-rust-kache-v1-0.27.0-${{ matrix.target }}-${{ hashFiles('.kache.toml', '.cargo/config.toml', 'rust-toolchain.toml') }}- + - name: Install Kache 0.27.0 for the Rust resource + uses: kunobi-ninja/kache-action@ad7317540dcdd71c904f7a60a87b620a0c0e67ed # v1 + with: + version: '0.27.0' + cache-dir: ${{ runner.temp }}/kache + cache-executables: true + github-cache: false + pr-comment: false + - name: Install Linux desktop, tray, and audio libraries + if: matrix.target == 'linux-x64' + run: | + sudo apt-get update + sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-12-dev libasound2t64 libayatana-appindicator3-dev + - name: Resolve frozen Dart workspace + run: flutter pub get --enforce-lockfile + - name: Analyze and format check + if: matrix.target == 'linux-x64' + run: moon run client:lint + - name: Build CLI bundle + run: moon run cli:build + - name: Smoke CLI bundle + shell: bash + run: ./packages/cli/dist/release/bundle/bin/${{ matrix.cli }} --help + - name: Build desktop release bundle + run: moon run desktop:build + - name: Run headless desktop integration test + run: moon run desktop:test-e2e + # Actions artifacts do not preserve Unix executable bits or app-bundle + # symlinks; archive each complete bundle before uploading it. + - name: Archive Unix bundles + if: runner.os != 'Windows' + shell: bash + run: | + mkdir -p release-artifacts + tar -C packages/cli/dist/release -czf release-artifacts/listenbox-cli-${{ matrix.target }}.tar.gz bundle + tar -C packages/desktop/dist -czf release-artifacts/listenbox-desktop-${{ matrix.target }}.tar.gz release + - name: Archive Windows bundles + if: runner.os == 'Windows' + shell: pwsh + run: | + New-Item -ItemType Directory -Force release-artifacts | Out-Null + Compress-Archive -Path packages/cli/dist/release/bundle -DestinationPath release-artifacts/listenbox-cli-${{ matrix.target }}.zip + Compress-Archive -Path packages/desktop/dist/release -DestinationPath release-artifacts/listenbox-desktop-${{ matrix.target }}.zip + - name: Upload CLI bundle + uses: actions/upload-artifact@v7 + with: + name: listenbox-cli-${{ matrix.target }} + path: release-artifacts/listenbox-cli-${{ matrix.target }}.* + if-no-files-found: error + - name: Upload desktop bundle + uses: actions/upload-artifact@v7 + with: + name: listenbox-desktop-${{ matrix.target }} + path: release-artifacts/listenbox-desktop-${{ matrix.target }}.* + if-no-files-found: error diff --git a/.github/workflows/publish-ffmpeg.yml b/.github/workflows/publish-ffmpeg.yml index 206991b..81d72f1 100644 --- a/.github/workflows/publish-ffmpeg.yml +++ b/.github/workflows/publish-ffmpeg.yml @@ -33,14 +33,14 @@ jobs: if: matrix.target == 'linux-x64' run: | sudo apt-get update - sudo apt-get install -y clang cmake ninja-build pkg-config libasound2-dev zip + sudo apt-get install -y clang cmake ninja-build pkg-config libasound2-dev zip xz-utils - uses: msys2/setup-msys2@v2 if: matrix.target == 'windows-x64' with: msystem: CLANG64 update: true install: >- - git curl make tar zip python + git curl make tar zip python diffutils mingw-w64-clang-x86_64-toolchain mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-ninja @@ -51,7 +51,7 @@ jobs: msystem: CLANGARM64 update: true install: >- - git curl make tar zip python + git curl make tar zip python diffutils mingw-w64-clang-aarch64-toolchain mingw-w64-clang-aarch64-cmake mingw-w64-clang-aarch64-ninja diff --git a/.github/workflows/publish-quickjs.yml b/.github/workflows/publish-quickjs.yml index a051bb9..d4bb551 100644 --- a/.github/workflows/publish-quickjs.yml +++ b/.github/workflows/publish-quickjs.yml @@ -12,6 +12,7 @@ jobs: runs-on: ${{ matrix.runner }} env: RUSTUP_TOOLCHAIN: 1.98.1-${{ matrix.rust_host }} + KACHE_CONFIG: ${{ github.workspace }}/.kache.toml strategy: fail-fast: false matrix: @@ -63,6 +64,24 @@ jobs: shell: bash run: | rustc -vV | grep -F 'host: ${{ matrix.rust_host }}' + - name: Restore shared Rust compiler cache + uses: actions/cache@v6 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + ${{ runner.temp }}/kache + key: client2-rust-kache-v1-0.27.0-${{ matrix.target }}-${{ hashFiles('.kache.toml', '.cargo/config.toml', 'rust-toolchain.toml') }}-${{ github.workflow }}-${{ github.sha }} + restore-keys: | + client2-rust-kache-v1-0.27.0-${{ matrix.target }}-${{ hashFiles('.kache.toml', '.cargo/config.toml', 'rust-toolchain.toml') }}- + - name: Install Kache 0.27.0 for the FJS source publisher + uses: kunobi-ninja/kache-action@ad7317540dcdd71c904f7a60a87b620a0c0e67ed # v1 + with: + version: '0.27.0' + cache-dir: ${{ runner.temp }}/kache + cache-executables: true + github-cache: false + pr-comment: false - name: Resolve frozen Dart workspace run: flutter pub get --enforce-lockfile # This explicit release job is the only caller of the native source diff --git a/.kache.toml b/.kache.toml new file mode 100644 index 0000000..39ddd5d --- /dev/null +++ b/.kache.toml @@ -0,0 +1,6 @@ +[cache] +# One OS-level store is shared across checkouts; do not put it in a build tree. +# The hook's generated YouTube.js resource is a cdylib, so opt it into caching. +cache_executables = true +adaptive_incremental = false +preserve_incremental = false diff --git a/.moon/workspace.yml b/.moon/workspace.yml new file mode 100644 index 0000000..049bb78 --- /dev/null +++ b/.moon/workspace.yml @@ -0,0 +1,17 @@ +defaultProject: client +projects: + client: . + cli: packages/cli + desktop: packages/desktop + client-engine: packages/sync-engine + client-youtubei: packages/youtubei +versionConstraint: ">=2.5.4 <3.0.0" +vcs: + client: git + defaultBranch: master +pipeline: + installDependencies: false + syncProjects: false + syncWorkspace: false +hasher: + walkStrategy: glob diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..e6e2bc6 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Listenbox desktop", + "type": "dart", + "request": "launch", + "cwd": "${workspaceFolder}/packages/desktop", + "program": "lib/main.dart", + "env": { + "LISTENBOX_CONFIG": "${workspaceFolder}/config/dev.yaml" + }, + "flutterMode": "debug" + }, + { + "name": "Listenbox CLI help", + "type": "dart", + "request": "launch", + "cwd": "${workspaceFolder}/packages/cli", + "program": "bin/listenbox.dart", + "args": ["--help"] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5333c1a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "dart.projectSearchDepth": 3, + "dart.flutterHotReloadOnSave": "allIfDirty", + "[dart]": { + "editor.defaultFormatter": "Dart-Code.dart-code", + "editor.formatOnSave": true + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..fa4d0fa --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,32 @@ +# Dart and Flutter client + +- The four application modules are `packages/youtubei`, `packages/sync-engine`, + `packages/cli`, and `packages/desktop`. +- All application logic is Dart. Desktop is Flutter; CLI is standalone Dart. +- One Dart isolate owns each process's application state. Use async operations + and explicit admission queues; native execution details stay inside libraries. +- Shared HTTP, profiles, credentials, cookies, persistence, download management, + media preparation, and synchronization belong in sync-engine. +- Embed the pinned YouTube.js submodule through youtubei. Never invoke a Node + subprocess or the superseded Rust client at runtime. +- Import the pinned upstream `package:fjs/fjs.dart`; do not copy its Dart + bindings or fork its runtime. Accept the QuickJS version shipped with FJS + and upgrade the Dart package and matching native artifacts together. +- CLI and desktop must independently bundle pinned SQLite, QuickJS, and FFmpeg + libraries. Normal builds consume verified prebuilt artifacts, never silently + fall back to compiling native dependencies or loading system versions. +- The youtubei hook may compile a tiny generated Rust resource library that only + exposes the pinned YouTube.js bundle bytes to Dart 3.13/Flutter 3.47 native + assets. It must not compile the FJS/QuickJS runtime or application logic. + Dart and Flutter data assets are not supported on the stable SDK in use. +- A YouTube.js source or native artifact change requires a full Flutter + restart; ordinary Dart UI changes keep the hot-reload session and must not + rebuild the YouTube.js resource library. +- Preserve resumable work and acknowledgement-loss safety. Cancellation must + settle owned work before logout or exit; UI progress is never durable truth. +- Use the parent repository's integrated API E2E suites for the real Dart CLI. + Keep integrated Flutter UI coverage headless in `packages/desktop/test` with + the real shared client and local HTTP fixtures. Tests must not open or focus + a native window. The API E2E suite must not launch or build the desktop app. +- Desktop development uses Flutter's ordinary run/hot-reload session. +- Do not add unit tests or compatibility paths for the superseded Rust client. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b7b007 --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# Listenbox client + +The Listenbox desktop app and command-line client are a Dart workspace. The +desktop app uses Flutter; the CLI runs as a standalone Dart executable. Both use +the same synchronization engine and an embedded, pinned YouTube.js runtime. +Each process keeps application state in one Dart isolate; the small Rust asset +only carries bundled JavaScript bytes. + +| Package | Responsibility | +| --- | --- | +| `packages/youtubei` | Embedded YouTube.js and QuickJS host | +| `packages/sync-engine` | Profiles, API access, SQLite journal, downloads, media, and synchronization | +| `packages/cli` | Terminal commands and protocol output | +| `packages/desktop` | Flutter desktop interface | + +## Get started + +Install Flutter **3.47.5** (Dart **3.13.4**), Rust **1.98.1**, Moon +**2.5.5**, and the [prebuilt Kache **0.27.0** executable](https://github.com/kunobi-ninja/kache/releases/tag/v0.27.0) +for your host, then clone with submodules: + +```sh +git clone --recurse-submodules https://github.com/listenbox/client2.git +cd client2 +dart tool/flutter.dart pub get --enforce-lockfile +moon run cli:build +moon run desktop:build +``` + +The CLI bundle is `packages/cli/dist/release/bundle/`; launch its `bin/listenbox` +executable (`bin/listenbox.exe` on Windows) from that complete bundle. The +desktop release bundle is `packages/desktop/dist/release/`. Keep each complete +bundle together so its verified native libraries remain available. + +For development, run Flutter directly from `packages/desktop`: + +```sh +cd packages/desktop +flutter run -d macos +``` + +Use `-d windows` or `-d linux` on those hosts. Debug sessions load +`config/dev.yaml` for the parent repository's local API and dashboard. +`moon run desktop:dev` and the included VS Code launch use that same config. +Save a Dart file in that VS Code session to hot reload; in a terminal Flutter +session, press `r` to reload or `R` to restart. See +[the development guide](docs/DEVELOPMENT.md) for setup and build details. + +Build hooks verify and bundle pinned SQLite, QuickJS, and FFmpeg libraries. +The youtubei hook bundles pinned `vendor/youtubejs` source and compiles a small +Rust resource containing its bytes. Normal builds need neither Node.js nor +Aube, and never compile the larger native libraries from source. Kache caches +the resource compilation in a shared OS-level store across checkouts. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..1ef9941 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,6 @@ +analyzer: + exclude: + - '**/build/**' + - '**/dist/**' + - '**/ephemeral/**' + - '**/.dart_tool/**' diff --git a/config/dev.yaml b/config/dev.yaml new file mode 100644 index 0000000..0863c19 --- /dev/null +++ b/config/dev.yaml @@ -0,0 +1,2 @@ +api_origin: http://localhost:8080 +dashboard_origin: http://localhost:5174 diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 0000000..8ada407 --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,161 @@ +# Development + +Open this repository itself as the workspace. It can also be checked out at +`apps/client2` inside the parent Listenbox repository. The client has four Dart +packages: `client_youtubei`, `listenbox_sync_engine`, `listenbox_cli`, and +`listenbox_desktop`. The CLI and Flutter desktop both call the shared engine. +Its API client is generated by Oasmith from the parent repository's canonical +OpenAPI contract; change that contract and regenerate the client together. + +## Set up + +Use Flutter 3.47.5 (which includes Dart 3.13.4), Rust 1.98.1, Moon 2.5.5, +and the [prebuilt Kache 0.27.0 executable](https://github.com/kunobi-ninja/kache/releases/tag/v0.27.0) +for your host. Keep `kache` on `PATH`; the hook invokes it directly around the +pinned `rustc`, and the manual FJS publisher uses it as Cargo's rustc wrapper. +Clone with submodules, then resolve the committed workspace lockfile: + +```sh +git clone --recurse-submodules https://github.com/listenbox/client2.git +cd client2 +dart tool/flutter.dart pub get --enforce-lockfile +``` + +Flutter desktop builds need their ordinary host toolchain: Xcode on macOS, +Visual Studio C++ desktop tools on Windows, or `clang`, `cmake`, `ninja-build`, +`pkg-config`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, and +`libstdc++-12-dev` on Ubuntu. On Ubuntu 24.04, install `libasound2t64` as well; +it supplies `libasound.so.2` used by the Linux media library. A desktop session +also needs a display server; the integrated Flutter tests run headlessly. + +Moon's desktop tasks use the selected Xcode or an explicit `DEVELOPER_DIR`. +When macOS only selected Command Line Tools, they use the installed +`/Applications/Xcode.app` for the Flutter process. For direct Flutter commands +and IDE launches, select full Xcode under **Xcode Settings → Locations → Command +Line Tools**, or set `DEVELOPER_DIR` to its `Contents/Developer` directory. + +On Windows ARM64, use a Flutter checkout at tag `3.47.5` and run its +`bin/flutter.bat` once to bootstrap the native SDK. Check that `bin/dart.bat +--version` reports `windows_arm64` before building. The published Flutter +3.47.5 Windows SDK archive contains x64 Dart. Moon 2.5.5's x64 Windows +executable can run under Windows ARM emulation; Dart and the app build remain +native ARM64. + +Build hooks verify and bundle pinned SQLite, QuickJS, and FFmpeg libraries. +They fail when a target has no published asset. They also bundle the pinned +YouTube.js source with a downloaded, checksum-verified esbuild binary and +compile a small Rust resource containing its bytes. Normal builds need +neither Node.js nor Aube, and never compile the larger native libraries from +source. + +Kache stores compiled Rust artifacts in one OS-level cache shared by client2 +checkouts. The `.kache.toml` enables caching for the small YouTube.js resource +library and disables incremental state; `.cargo/config.toml` applies the same +wrapper to the rare FJS source release build. Keep each checkout's build output +local to that checkout; do not share a `CARGO_TARGET_DIR`. On a cold machine, +the build still needs the pinned Rust toolchain, Kache executable, and access +to the verified source and native downloads. A cache hit is only an +optimization. Normal Flutter or CLI builds never invoke Cargo for FJS. + +All five FJS targets are pinned by URL and SHA-256 in +`packages/youtubei/native_artifacts.json`. The manual **Publish pinned QuickJS +artifacts** workflow can rebuild the Linux and Windows libraries and publish a +candidate manifest with measured URLs and digests. Commit any new pins before +normal builds consume them. + +The manual **Publish patched FFmpegKit artifacts** workflow builds native +libraries for all five targets from pinned FFmpegKit and FFmpeg sources. Its +source patch leaves process signals with Dart, and the workflow writes a +candidate URL, archive entry, and SHA-256 map. Commit the resulting pins before +normal builds consume a new release. + +The patched FFmpegKit pins are still pending. Current builds use the original +four-platform archives; Windows ARM64 is unavailable until the new release is +pinned. Cancellation and clean CLI output also require that patched release. + +## Run and edit + +From this repository's root, start the standard Flutter debug session: + +```sh +cd packages/desktop +flutter run -d macos +``` + +Debug runs from `packages/desktop` load `../../config/dev.yaml`, which points +to the parent repository's local API and dashboard. Release builds use the +profile's `config.yaml` when present, otherwise the production API origins. +Choose `windows` or `linux` instead of `macos` on those hosts. +Press `r` in the terminal for hot reload, `R` for a full restart, and `q` to +quit. Dart edits can hot reload; changes to the vendored JavaScript or native +assets need a full restart. In VS Code, select a desktop device and launch +**Listenbox desktop**. +Saving a changed Dart file reloads it. That launch sets `LISTENBOX_CONFIG` to +`config/dev.yaml` for the parent repository's local API and dashboard. + +Moon also starts an interactive Flutter session with that config. It resolves +the frozen dependencies once, shows dependency output only on failure, and +leaves hot reload to Flutter: + +```sh +moon run desktop:dev +``` + +Closing the desktop window hides it to the tray and keeps the same Flutter +engine and Dart client running. The tray has **Open Listenbox** and **Quit +Listenbox**; only Quit cancels and drains active work before exiting. On macOS, +either mouse button opens the tray menu. On Windows, left-click opens the +window and right-click opens the menu. + +Automatic podcast sync uses the shared engine's hourly asynchronous wait. +There is no busy loop, separate background service, or wake lock. System sleep +and normal OS power management can defer syncs. The app does not wake the +computer for them. + +For a development CLI invocation: + +```sh +cd packages/cli +dart run bin/listenbox.dart --help +``` + +When testing against the parent repository's local API, start its services with +`moon run dev` in that repository before using commands that access the API. +From `packages/cli`, point the CLI at the same development configuration: + +```sh +dart run bin/listenbox.dart --config ../../config/dev.yaml shows list +``` + +## Analyze and build + +Run the scoped checks and builds from this repository's root: + +```sh +moon run client:lint +moon run cli:build +moon run desktop:build +moon run desktop:test-e2e +``` + +The CLI build uses `dart build cli` and creates +`packages/cli/dist/release/bundle/bin/listenbox` (or `listenbox.exe`) with native +libraries under the same bundle. The Flutter release output is copied to +`packages/desktop/dist/release/`. Copy or upload each entire directory; the +application executable alone is insufficient. The desktop target builds for the +host OS and architecture. The intended release targets are macOS arm64 and x64, +Windows x64 and ARM64, and Linux x64. + +When updating YouTube.js, update the `vendor/youtubejs` submodule pin and +`packages/youtubei/youtubejs_tools.json` revision together. The hook rebuilds +the Rust resource on the next full build. + +## CI artifacts + +The `Client` workflow runs the frozen pub lockfile, analysis, release builds, +a CLI `--help` smoke check, and the headless desktop Flutter integration test +on runners for all five targets. The test uses the real shared client and a +local HTTP fixture without opening a window. Parent API E2E exercises the CLI. +The workflow uploads separate CLI and desktop archives for each target, +preserving Unix executable bits and macOS app symlinks. Missing native assets +fail their target's build. The workflow does not publish a GitHub release. diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..d4837f3 --- /dev/null +++ b/docs/IMPLEMENTATION_PLAN.md @@ -0,0 +1,79 @@ +# Dart/Flutter client cutover + +## Behavior and boundaries + +Port the existing Rust client to four Dart packages: `client_youtubei`, +`listenbox_sync_engine`, `listenbox_cli`, and `listenbox_desktop`. The desktop +preserves the established application layout and native interactions. The CLI +preserves the public command/protocol behavior exercised by API E2E. Application +state is owned by one Dart isolate per process; async downloads and queued writes +do not introduce shared application-state threads. + +`youtubei` owns the embedded QuickJS host and pinned YouTube.js bundle. The sync +engine owns API/config contracts, authorization, cookie transport, validated source +enumeration, format selection, range downloads, SQLite checkpoints, media +preparation, package uploads, source reconciliation, and scan scheduling. CLI and +desktop call the same engine. The API continues to own remote admission, published +episodes, object ownership, and cleanup. The SQLite journal owns local resumable +work, while progress events are projections only. + +## Native and build contracts + +Use pinned prebuilt SQLite, QuickJS, and FFmpeg artifacts in each release bundle. +Build hooks verify native artifacts and register them with Dart code assets. The +runtime must not depend on system installations of these libraries. Native source +builds belong in deliberate artifact publishing jobs, outside normal dev/PR builds. +The YouTube.js repository stays a nested submodule with the existing pinned source +revision initially. Bundle names must be preserved for its parser. + +Moon launches Flutter directly for development, retaining terminal input and a +single running application session. Shared Dart edits use Flutter hot reload. +The youtubei build hook bundles its pinned YouTube.js source and embeds the +result in a small generated Rust resource library. This cached resource has no +application policy, and Dart-only edits do not rebuild it. Source and native +library changes require a full restart. Normal builds never compile the large +QuickJS, SQLite, or FFmpeg libraries. +Moon targets must declare all code generation, bundle, package-resolution, and +native artifact prerequisites, including on absent-artifact/cold-cache startup. +The parent API E2E build copies the complete Dart CLI bundle, not just its executable. +Oasmith emits the public Dart client from public.responsible.ts through +openapi:generate-public-dart-client. The shared transport supplies authorization, +tracing, proxy routing, bounded responses, and cancellation to generated +operations; endpoint paths and public DTOs are owned by the generator. Generated +source is committed for standalone client development. + +## Failure and ownership walkthrough + +- Downloads persist completed ranges only after bytes and hashes are durable; + interrupted ranges resume through the same manager. Source/format changes + invalidate only the affected owned download records. +- Prepared media and its complete manifest remain durable across a lost admission + acknowledgement. Re-entry uses the operation identity and existing package. +- Upload completion checkpoints survive successful remote writes with lost + acknowledgements; the API's idempotent operation contract remains authoritative. +- Failed/incomplete source enumeration never authorizes deletion. Authentication + errors remain errors, while explicitly unavailable items remain distinguishable. +- Cancellation stops admission and awaits owned operations. Logout removes shared + credentials only after draining, preventing an in-flight login restoring them. +- Cross-process SQLite initialization is serialized; WAL readers can observe + committed state while a write transaction is active. Durable writes retain the + existing explicit fsync settings. + +## Acceptance proof + +Reuse the integrated cases in apps/api/e2e/cli*_test.go and client*_test.go against +the compiled Dart CLI. API E2E does not build or launch the desktop. Preserve real native media +processing and real embedded YouTube.js against test-local provider responses. +Retain assertions on protocol outcomes, durable API/SQLite state, range requests, +owned media outputs, absence of duplicate publication, and actual process closure. +Desktop control scenarios live in the desktop package and run Flutter headlessly +with the shared Dart client against local HTTP fixtures. Tests establish their intended states through explicit gates, +finish below ten seconds, and retain the hard thirty-second failure guard. + +Verification targets: client package analysis, cli:build, desktop:build, +desktop:test-e2e, focused api:test-e2e CLI/client regressions, then the complete +affected integrated group. Inspect the resolved Moon action graph and exercise +an isolated cold startup. Verify packaged CLI native operations outside source +checkout paths, and inspect a Flutter hot-reload session with retained state. +Local macOS verification cannot establish Windows/Linux execution; those require +their native runners and must be reported accurately. Do not poll CI. diff --git a/moon.yml b/moon.yml new file mode 100644 index 0000000..0d6b937 --- /dev/null +++ b/moon.yml @@ -0,0 +1,80 @@ +language: dart +layer: library +tags: [client-workspace] +toolchains: + default: system +taskOptions: + cache: true + shell: false +fileGroups: + sources: + - pubspec.yaml + - pubspec.lock + - rust-toolchain.toml + - .cargo/config.toml + - .kache.toml + - analysis_options.yaml + - config/*.yaml + - .gitmodules + - .moon/**/*.yml + - moon.yml + - tool/**/*.dart + - packages/**/pubspec.yaml + - packages/**/lib/**/*.dart + - packages/**/bin/**/*.dart + - packages/**/tool/**/* + - packages/**/hook/**/* + - packages/**/native/**/* + - packages/**/native*.json + - packages/youtubei/linux/CMakeLists.txt + - packages/youtubei/windows/CMakeLists.txt + - packages/youtubei/youtubejs_tools.json + - packages/**/moon.yml + - packages/desktop/test/**/*.dart + - packages/desktop/macos/**/* + - packages/desktop/windows/**/* + - packages/desktop/linux/**/* + - packages/desktop/assets/**/* + - vendor/youtubejs/src/**/* + - vendor/youtubejs/protos/generated/**/* + - vendor/youtubejs/package.json + - vendor/youtubejs/tsconfig.json + - '!**/ephemeral/**' + - '!**/Pods/**' + - '!**/build/**' + - '!**/dist/**' +tasks: + install: + command: dart tool/flutter.dart pub get --enforce-lockfile + inputs: [pubspec.yaml, pubspec.lock, 'packages/*/pubspec.yaml'] + options: + cache: false + internal: true + outputStyle: buffer-only-failure + codegen: + description: Use the committed API client; the parent workspace regenerates it with Oasmith. + inputs: [] + prerequisites: + deps: ['~:install', '~:codegen'] + inputs: [] + lint: + deps: ['~:prerequisites'] + command: dart tool/check.dart + inputs: ['@group(sources)'] + format: + command: dart format tool packages + inputs: ['@group(sources)'] + options: + cache: false + runInCI: false + check: + deps: ['~:lint', 'cli:build', 'desktop:build', 'desktop:test-e2e'] + inputs: [] + options: + runInCI: false + outdated: + command: flutter pub outdated + inputs: [pubspec.yaml, pubspec.lock, 'packages/**/pubspec.yaml'] + options: + cache: false + runInCI: false diff --git a/packages/cli/bin/listenbox.dart b/packages/cli/bin/listenbox.dart new file mode 100644 index 0000000..fa3ff97 --- /dev/null +++ b/packages/cli/bin/listenbox.dart @@ -0,0 +1,7 @@ +import 'dart:io'; + +import 'package:listenbox_cli/listenbox_cli.dart'; + +Future main(List arguments) async { + exitCode = await runListenbox(arguments, debugProfile: false); +} diff --git a/packages/cli/lib/listenbox_cli.dart b/packages/cli/lib/listenbox_cli.dart new file mode 100644 index 0000000..6a88127 --- /dev/null +++ b/packages/cli/lib/listenbox_cli.dart @@ -0,0 +1,1003 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:http/http.dart' as http; +import 'package:image/image.dart' as img; +import 'package:listenbox_sync_engine/sync_engine.dart'; +import 'package:listenbox_sync_engine/sync_engine.dart' as p; + +/// The same command runner is used by the release and development bundles. +Future runListenbox( + List arguments, { + required bool debugProfile, +}) async { + final cancellation = CancellationToken(); + var interrupted = false; + final signals = >[]; + void interrupt(ProcessSignal _) { + interrupted = true; + cancellation.cancel(); + } + + signals.add(ProcessSignal.sigint.watch().listen(interrupt)); + if (!Platform.isWindows) { + signals.add(ProcessSignal.sigterm.watch().listen(interrupt)); + } + Api? api; + try { + final command = _ParsedCommand.parse(arguments); + if (command.help) { + stdout.writeln(_help(command.path)); + return 0; + } + if (command.version) { + stdout.writeln('listenbox 0.1.0'); + return 0; + } + final config = Config.load( + explicitPath: command.configPath, + debugProfile: debugProfile, + ); + api = await Api.open( + config, + cancel: cancellation, + enableHttpLog: debugProfile, + ); + await _execute(command, api, config, cancellation); + return interrupted ? 130 : 0; + } on _UsageError catch (error) { + stderr.writeln(error.message); + stderr.writeln('Run listenbox --help for usage.'); + return 2; + } catch (error) { + stderr.writeln(error); + return interrupted ? 130 : 1; + } finally { + api?.close(); + for (final signal in signals) { + await signal.cancel(); + } + } +} + +Future _execute( + _ParsedCommand command, + Api api, + Config config, + CancellationToken cancellation, +) async { + final path = command.path; + final options = command.options; + if (path == 'youtube-cookies import') { + await CookieJar(config.directory).importFile(options.positionals.single); + stdout.writeln('YouTube cookies updated. Sync your podcast to continue.'); + return; + } + if (path == 'youtube-cookies remove') { + await CookieJar(config.directory).remove(); + stdout.writeln('YouTube cookies updated. Sync your podcast to continue.'); + return; + } + if (path == 'login') { + await Auth.login( + api, + client: 'cli', + openBrowser: (url) => stdout.writeln('Verification URL: $url'), + ); + return; + } + if (path == 'auth logout') { + await Auth.logout(api); + return; + } + if (!api.hasCredential) { + throw StateError('not logged in; run listenbox login'); + } + switch (path) { + case 'auth status': + stdout.writeln(await Auth.status(api)); + return; + case 'import': + final source = options.positionals.single; + final slug = options.value('slug'); + if (isYouTubeSource(source)) { + final result = await _withClient( + api, + (engine) => engine.importPlaylist( + source, + 'video', + requestedSlug: slug, + cancel: cancellation, + onCreated: (show) { + final createdSlug = _string(show, 'slug'); + stderr.writeln( + 'Created podcast ${jsonEncode(createdSlug)}. Resume with shows sync youtube --show $createdSlug', + ); + }, + ), + ); + final show = result.show; + stdout.writeln(_string(show, 'slug')); + stderr.writeln( + '${result.report.added} added, ${result.report.skipped} skipped', + ); + stderr.writeln('100%'); + stderr.writeln( + 'Open in Listenbox: ${config.showUrl(_string(show, 'team_id'), _string(show, 'id'))}', + ); + } else { + await _importRss(api, source, slug); + } + return; + case 'shows list': + for (final show in await api.publicClient.listShows()) { + stdout.writeln(show.slug); + } + return; + case 'shows create': + await _createShow(api, config, options); + return; + case 'shows delete': + final slug = options.required('show'); + final result = await api.publicClient.createShowDeletion(showSlug: slug); + await _deleteEvents( + api, + await api.publicClient.showDeletionEvents( + showDeletionRunId: result.showDeletionRunId, + ), + 'show', + slug, + ); + return; + case 'shows order': + final show = options.required('show'); + final episodeIds = options.values('episode'); + final ids = episodeIds.isEmpty + ? (await api.publicClient.getEpisodeOrder(showSlug: show)).episodeIds + : (await _withClient( + api, + (engine) => + engine.setOrder(show, episodeIds, cancel: cancellation), + ))['episode_ids'] + as List; + for (final id in ids) { + if (id is! String) + throw const FormatException('invalid episode order ID'); + stdout.writeln(id); + } + return; + case 'shows sync youtube': + final show = options.required('show'); + await _withClient(api, (engine) async { + if (options.flag('watch')) { + await for (final report in engine.watch(show, cancel: cancellation)) { + stdout.writeln(report.toString()); + } + } else { + stdout.writeln( + (await engine.sync(show, cancel: cancellation)).toString(), + ); + } + }); + return; + case 'episodes list': + await _listEpisodes( + api, + options.required('show'), + int.parse(options.value('limit') ?? '100'), + ); + return; + case 'episodes create': + final file = File(options.required('file')); + try { + final handle = await file.open(mode: FileMode.read); + await handle.close(); + } on FileSystemException catch (error) { + throw StateError( + 'open --file ${jsonEncode(file.path)}: ${error.message}', + ); + } + await _withClient( + api, + (engine) => engine.createEpisode( + options.required('show'), + options.required('title'), + file, + description: options.value('description'), + publication: options.value('publication') ?? 'draft', + cancel: cancellation, + onProgress: (message) { + if (message.startsWith('Published episode ') || + message.startsWith('Created draft episode ') || + message.startsWith('YouTube (processing): ')) { + stdout.writeln(message); + } else { + stderr.writeln(message); + } + }, + ), + ); + return; + case 'episodes delete': + final episode = options.required('episode'); + final result = await api.publicClient.createEpisodeDeletion( + episodeId: episode, + ); + await _deleteEvents( + api, + await api.publicClient.episodeDeletionEvents( + episodeDeletionRunId: result.episodeDeletionRunId, + ), + 'episode', + episode, + ); + return; + case 'members list': + await _membersList(api, options.value('show')); + return; + case 'members invite': + await _membersInvite(api, options); + return; + case 'members role': + await _membersRole(api, options); + return; + case 'members remove': + await _membersRemove(api, options); + return; + default: + throw _UsageError('unknown command $path'); + } +} + +Future _withClient(Api api, Future Function(Client) operation) async { + final client = Client(api.config, enableHttpLog: api.enableHttpLog); + final printed = {}; + final changes = client.downloads.changes.listen((snapshot) { + for (final item in snapshot.items) { + final bucket = item.total == 0 ? 0 : item.received * 10 ~/ item.total; + final state = (item.phase, bucket); + if (printed[item.id] == state) continue; + printed[item.id] = state; + final title = item.title.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), ''); + stderr.writeln('$title: ${_phaseLabel(item.phase)}'); + } + }); + try { + return await operation(client); + } finally { + await client.close(); + await changes.cancel(); + } +} + +String _phaseLabel(Phase phase) => switch (phase) { + Phase.queued => 'Queued', + Phase.resolving => 'Resolving media', + Phase.downloading => 'Downloading', + Phase.preparing => 'Preparing media', + Phase.uploading => 'Uploading', + Phase.complete => 'Complete', + Phase.skipped => 'Skipped', + Phase.failed => 'Failed', +}; + +Future _importRss(Api api, String source, String? slug) async { + p.CreatedPublicRSSImport created; + try { + created = await api.publicClient.importRSS( + body: p.ImportRSSRequest(sourceUrl: source, slug: slug), + ); + } on ApiHttpException catch (error) { + if (error.statusCode == 409) { + throw StateError( + slug == null + ? 'import choice conflicts' + : 'requested slug ${jsonEncode(slug)} conflicts', + ); + } + rethrow; + } + final events = await EventStream.fromResponse( + api, + await api.publicClient.importRSSRunEvents(importRunId: created.importRunId), + ); + final progress = Progress(); + try { + while (true) { + final event = await events.next(); + switch (_string(event, 'type')) { + case 'progress': + progress.update(p.RSSImportProgressEvent.fromJson(event).percent); + continue; + case 'terminal': + switch (p.PublicRSSImportTerminalEvent.fromJson(event)) { + case p.PublicRSSImportCompletedTerminalEvent completed: + final showSlug = _slug(completed.showSlug); + _id(completed.feedId, 'lb_'); + final location = api.config.showUrl( + completed.teamId, + completed.showId, + ); + progress.update(100); + stdout.writeln(showSlug); + stderr.writeln('Open in Listenbox: $location'); + return; + case p.RSSImportCancelledTerminalEvent(): + throw StateError('RSS import was cancelled'); + case p.RSSImportFailedTerminalEvent failed: + throw StateError( + 'RSS import failed ' + '(${failed.errorCode}): ${failed.errorMessage}', + ); + } + default: + throw FormatException( + 'malformed import event ${jsonEncode(event['type'])}', + ); + } + } + } finally { + await events.close(); + } +} + +Future _deleteEvents( + Api api, + http.StreamedResponse response, + String kind, + String identity, +) async { + final events = await EventStream.fromResponse(api, response); + final progress = Progress(); + try { + while (true) { + final event = await events.next(); + switch (_string(event, 'type')) { + case 'progress': + final percent = kind == 'show' + ? p.ShowDeletionProgressEvent.fromJson(event).percent + : p.EpisodeDeletionProgressEvent.fromJson(event).percent; + progress.update(percent); + continue; + case 'terminal': + if (kind == 'show') { + switch (p.ShowDeletionTerminalEvent.fromJson(event)) { + case p.ShowDeletionCompletedEvent completed: + if (completed.showSlug != identity) { + throw StateError('deletion completed for another show'); + } + case p.ShowDeletionFailedEvent failed: + throw StateError( + 'delete show failed (${failed.errorCode}): ${failed.errorMessage}', + ); + } + } else { + switch (p.EpisodeDeletionTerminalEvent.fromJson(event)) { + case p.EpisodeDeletionCompletedEvent completed: + if (completed.episodeId != identity) { + throw StateError('deletion completed for another episode'); + } + case p.EpisodeDeletionFailedEvent failed: + throw StateError( + 'delete episode failed (${failed.errorCode}): ${failed.errorMessage}', + ); + } + } + progress.update(100); + stdout.writeln('Deleted $kind ${jsonEncode(identity)}'); + return; + default: + throw FormatException( + 'malformed deletion event ${jsonEncode(event['type'])}', + ); + } + } + } finally { + await events.close(); + } +} + +Future _createShow(Api api, Config config, _Options options) async { + final slug = options.required('slug'); + final id = 'shw_${_randomHex(8)}'; + final artwork = options.value('artwork'); + final imageAssetId = artwork == null + ? null + : await _uploadArtwork(api, id, artwork); + p.Show show; + try { + show = await api.publicClient.createShow( + body: p.CreateShow( + id: id, + title: options.required('title'), + slug: slug, + language: options.required('language'), + imageAssetId: imageAssetId, + sourceKind: p.ShowSourceKind.fromJson(options.required('type')), + ), + ); + } on ApiHttpException catch (error) { + if (error.statusCode == 409) { + throw StateError('create show: slug ${jsonEncode(slug)} already exists'); + } + rethrow; + } + stdout.writeln('Created show ${jsonEncode(show.slug)}'); + stdout.writeln('Open in Listenbox: ${config.showUrl(show.teamId, show.id)}'); +} + +Future _uploadArtwork(Api api, String showId, String path) async { + late final Uint8List raw; + try { + raw = await File(path).readAsBytes(); + } on FileSystemException catch (error) { + throw StateError('read artwork $path: $error'); + } + final contentType = _validateArtwork(raw); + final name = Uri.file(path).pathSegments.last; + final presign = await api.publicClient.createImageUploadPresign( + body: p.CreateImageUploadPresign( + showId: showId, + byteLength: raw.length, + contentType: p.CreateImageUploadPresignContentType.fromJson(contentType), + fileName: name, + ), + ); + final upload = http.Request(presign.method, Uri.parse(presign.uploadUrl)); + upload.headers['Content-Type'] = contentType; + upload.bodyBytes = raw; + final response = await api.sendExternal(upload); + await response.stream.drain(); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw StateError('upload artwork: HTTP ${response.statusCode}'); + } + final complete = await api.publicClient.completeImageUpload( + imageAssetId: presign.imageAssetId, + body: p.CompleteImageUpload(objectKey: presign.objectKey), + ); + return complete.id; +} + +String _validateArtwork(Uint8List data) { + final png = img.PngDecoder(); + final jpeg = img.JpegDecoder(); + final img.Decoder decoder; + final String contentType; + if (png.isValidFile(data)) { + decoder = png; + contentType = 'image/png'; + } else if (jpeg.isValidFile(data)) { + decoder = jpeg; + contentType = 'image/jpeg'; + } else { + throw StateError('artwork must be a JPEG or PNG image'); + } + + img.DecodeInfo? info; + try { + info = decoder.startDecode(data); + } catch (_) { + throw StateError('read artwork dimensions: malformed image'); + } + if (info == null) { + throw StateError('read artwork dimensions: malformed image'); + } + final width = info.width; + final height = info.height; + if (width != height || width < 1400 || width > 3000) { + throw StateError( + 'upload a square image between 1400 and 3000 pixels. ' + 'Attempted resolution: $width × $height pixels', + ); + } + + img.Image? decoded; + try { + decoded = decoder.decodeFrame(0); + } catch (_) { + throw StateError('read artwork dimensions: malformed image'); + } + if (decoded == null || decoded.width != width || decoded.height != height) { + throw StateError('read artwork dimensions: malformed image'); + } + return contentType; +} + +Future _listEpisodes(Api api, String show, int limit) async { + String? cursor; + final seen = {}; + while (true) { + final page = await api.publicClient.listEpisodes( + showSlug: show, + limit: limit, + cursor: cursor, + ); + for (final episode in page.episodes) { + stdout.writeln(_id(episode.id, 'ep_')); + } + cursor = page.nextCursor; + if (cursor == null) return; + if (cursor.isEmpty || !seen.add(cursor)) { + throw StateError('empty or repeated episode list cursor'); + } + } +} + +Future _membersList(Api api, String? show) async { + if (show == null) { + final result = await api.publicClient.listTeamMembers(); + for (final member in result.members) { + stdout.writeln( + '${member.role.value}\t${member.user.email}\t${member.user.id}', + ); + } + for (final invite in result.invitations) { + _printInvitation( + invite.role.value, + invite.email, + invite.id, + invite.expiresAt, + ); + } + } else { + final result = await api.publicClient.listShowMembers(showSlug: show); + for (final member in result.members) { + stdout.writeln( + '${member.accessSource.value}\t${member.role.value}\t${member.user.email}\t${member.user.id}', + ); + } + for (final invite in result.invitations) { + _printInvitation( + invite.role.value, + invite.email, + invite.id, + invite.expiresAt, + ); + } + } +} + +void _printInvitation(String role, String email, String id, int expiresAt) { + final expiry = + '${DateTime.fromMillisecondsSinceEpoch(expiresAt, isUtc: true).toIso8601String().substring(0, 19)}Z'; + stdout.writeln('pending\t$role\t$email\t$id\t$expiry'); +} + +Future _membersInvite(Api api, _Options options) async { + final show = options.value('show'); + final email = options.required('email').trim().toLowerCase(); + final role = p.AssignableTeamRole.fromJson(options.required('role')); + String invitedEmail; + p.AssignableTeamRole invitedRole; + if (show == null) { + final result = await api.publicClient.createTeamInvitation( + body: p.CreateTeamInvitation(email: email, role: role), + ); + invitedEmail = result.email; + invitedRole = result.role; + } else { + final result = await api.publicClient.createShowInvitation( + showSlug: show, + body: p.CreateShowInvitation(email: email, role: role), + ); + invitedEmail = result.email; + invitedRole = result.role; + } + stdout.writeln( + 'Invited $invitedEmail${show == null ? '' : ' to $show'} as ${invitedRole.value}.', + ); +} + +Future _membersRole(Api api, _Options options) async { + final show = options.value('show'); + final member = options.required('member'); + final role = options.required('role'); + if (show == null) { + await api.publicClient.updateTeamMemberRole( + userId: member, + body: p.UpdateTeamMemberRole(role: p.AssignableTeamRole.fromJson(role)), + ); + } else { + await api.publicClient.updateShowMemberRole( + showSlug: show, + userId: member, + body: p.UpdateShowMemberRole(role: p.AssignableTeamRole.fromJson(role)), + ); + } + stdout.writeln( + 'Changed ${show == null ? 'member' : 'show member'} $member to $role.', + ); +} + +Future _membersRemove(Api api, _Options options) async { + final show = options.value('show'); + final member = options.required('member'); + if (show == null) { + await api.publicClient.removeTeamMember(userId: member); + } else { + await api.publicClient.removeShowMember(showSlug: show, userId: member); + } + stdout.writeln('Removed ${show == null ? 'member' : 'show member'} $member.'); +} + +String _string(Map object, String key) { + final value = object[key]; + if (value is String) return value; + throw FormatException('missing string $key'); +} + +String _randomHex(int bytes) { + final random = Random.secure(); + return List.generate( + bytes, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); +} + +String _nonblank(String value) { + final trimmed = value.trim(); + if (trimmed.isEmpty) throw _UsageError('must not be blank'); + return trimmed; +} + +String _slug(String value) { + final trimmed = _nonblank(value); + if (!RegExp(r'^[a-z0-9]+(?:-[a-z0-9]+)*$').hasMatch(trimmed)) { + throw _UsageError( + 'must use lowercase letters, numbers, and single hyphens', + ); + } + return trimmed; +} + +String _language(String value) { + final trimmed = _nonblank(value); + if (!RegExp(r'^[a-z]{2}(?:-[A-Z]{2})?$').hasMatch(trimmed)) { + throw _UsageError('must use a language code such as en or en-US'); + } + return trimmed; +} + +String _id(String value, String prefix) { + if (!RegExp('^${RegExp.escape(prefix)}[0-9a-f]{16}\$').hasMatch(value)) { + throw _UsageError( + 'invalid ${prefix == 'ep_' ? 'episode' : 'feed'} ID ${jsonEncode(value)}', + ); + } + return value; +} + +String _choice(String value, List choices) { + if (!choices.contains(value)) { + throw _UsageError( + 'invalid value ${jsonEncode(value)}; choose ${choices.join(', ')}', + ); + } + return value; +} + +class _UsageError implements Exception { + const _UsageError(this.message); + final String message; +} + +class _Options { + _Options(this._values, this._flags, this.positionals); + final Map> _values; + final Set _flags; + final List positionals; + + String? value(String name) => _values[name]?.lastOrNull; + String required(String name) => + value(name) ?? (throw _UsageError('missing required --$name')); + List values(String name) => _values[name] ?? const []; + bool flag(String name) => _flags.contains(name); +} + +class _ParsedCommand { + _ParsedCommand( + this.path, + this.options, + this.configPath, + this.help, + this.version, + ); + final String path; + final _Options options; + final String? configPath; + final bool help; + final bool version; + + static _ParsedCommand parse(List arguments) { + final words = List.from(arguments); + String? config; + var configSeen = false; + var help = false; + var version = false; + for (var i = 0; i < words.length;) { + final word = words[i]; + if (word == '--') break; + if (word == '--help' || word == '-h') { + help = true; + words.removeAt(i); + } else if (word == '--version' || word == '-V') { + version = true; + words.removeAt(i); + } else if (word == '--config' || word.startsWith('--config=')) { + if (configSeen) { + throw const _UsageError('--config may only be provided once'); + } + configSeen = true; + final inline = word.indexOf('='); + if (inline >= 0) { + config = word.substring(inline + 1); + words.removeAt(i); + } else { + if (i + 1 >= words.length || words[i + 1].startsWith('--')) { + throw const _UsageError('missing --config value'); + } + config = words[i + 1]; + words.removeRange(i, i + 2); + } + } else { + i++; + } + } + if (words.isEmpty) { + if (help || version) + return _ParsedCommand('', _Options({}, {}, []), config, help, version); + throw const _UsageError('missing command'); + } + final parts = []; + final top = words.removeAt(0); + parts.add(top); + if ([ + 'auth', + 'youtube-cookies', + 'shows', + 'episodes', + 'members', + ].contains(top)) { + if (words.isEmpty) { + if (help) + return _ParsedCommand( + top, + _Options({}, {}, []), + config, + true, + version, + ); + throw _UsageError('missing $top subcommand'); + } + parts.add(words.removeAt(0)); + if (top == 'shows' && parts[1] == 'sync') { + if (words.isEmpty && help) { + return _ParsedCommand( + 'shows sync', + _Options({}, {}, []), + config, + true, + version, + ); + } + if (words.isEmpty) + throw const _UsageError('missing shows sync subcommand'); + parts.add(words.removeAt(0)); + } + } + final path = parts.join(' '); + final spec = _specs[path]; + if (spec == null) throw _UsageError('unknown command $path'); + if (help || version) + return _ParsedCommand(path, _Options({}, {}, []), config, help, version); + final values = >{}; + final flags = {}; + final positionals = []; + var positionalOnly = false; + for (var i = 0; i < words.length; i++) { + final word = words[i]; + if (!positionalOnly && word == '--') { + positionalOnly = true; + continue; + } + if (positionalOnly || !word.startsWith('--')) { + positionals.add(word); + continue; + } + final split = word.indexOf('='); + final name = word.substring(2, split < 0 ? null : split); + if (spec.flags.contains(name)) { + if (split >= 0) throw _UsageError('--$name does not take a value'); + flags.add(name); + continue; + } + if (!spec.options.containsKey(name)) + throw _UsageError('unknown option --$name'); + if (name != 'episode' && values.containsKey(name)) { + throw _UsageError('--$name may only be provided once'); + } + final value = split >= 0 + ? word.substring(split + 1) + : (i + 1 < words.length + ? words[++i] + : throw _UsageError('missing --$name value')); + if (value.startsWith('--')) throw _UsageError('missing --$name value'); + final validator = spec.options[name]!; + values.putIfAbsent(name, () => []).add(validator(value)); + } + if (positionals.length != spec.positionalCount) { + throw _UsageError( + '$path expects ${spec.positionalCount} positional argument(s)', + ); + } + for (final name in spec.required) { + if (!values.containsKey(name) && !flags.contains(name)) { + throw _UsageError('missing required --$name'); + } + } + if (path == 'episodes list') { + final limit = int.tryParse(values['limit']?.lastOrNull ?? '100'); + if (limit == null || limit < 1 || limit > 500) { + throw const _UsageError('--limit must be between 1 and 500'); + } + } + return _ParsedCommand( + path, + _Options(values, flags, positionals), + config, + false, + false, + ); + } +} + +typedef _Validator = String Function(String); + +class _CommandSpec { + const _CommandSpec( + this.options, { + this.flags = const {}, + this.required = const {}, + this.positionalCount = 0, + }); + final Map options; + final Set flags; + final Set required; + final int positionalCount; +} + +final _specs = { + 'login': const _CommandSpec({}), + 'auth status': const _CommandSpec({}), + 'auth logout': const _CommandSpec({}), + 'import': _CommandSpec({'slug': _slug}, positionalCount: 1), + 'youtube-cookies import': const _CommandSpec({}, positionalCount: 1), + 'youtube-cookies remove': const _CommandSpec({}), + 'shows list': const _CommandSpec({}), + 'shows order': _CommandSpec( + {'show': _slug, 'episode': (value) => _id(value, 'ep_')}, + required: {'show'}, + ), + 'shows sync youtube': _CommandSpec( + {'show': _slug}, + flags: {'watch'}, + required: {'show'}, + ), + 'shows create': _CommandSpec( + { + 'title': _nonblank, + 'slug': _slug, + 'type': (value) => _choice(value, ['audio', 'video']), + 'language': _language, + 'artwork': (value) => value, + }, + required: {'title', 'slug', 'type', 'language'}, + ), + 'shows delete': _CommandSpec( + {'show': _slug}, + flags: {'yes'}, + required: {'show', 'yes'}, + ), + 'episodes list': _CommandSpec( + {'show': _slug, 'limit': (value) => value}, + required: {'show'}, + ), + 'episodes create': _CommandSpec( + { + 'show': _slug, + 'title': _nonblank, + 'description': _nonblank, + 'file': (value) => value, + 'publication': (value) => _choice(value, ['draft', 'publish']), + }, + required: {'show', 'title', 'file'}, + ), + 'episodes delete': _CommandSpec( + {'episode': (value) => _id(value, 'ep_')}, + flags: {'yes'}, + required: {'episode', 'yes'}, + ), + 'members list': _CommandSpec({'show': _slug}), + 'members invite': _CommandSpec( + { + 'email': _nonblank, + 'role': (value) => _choice(value, ['read', 'write']), + 'show': _slug, + }, + required: {'email', 'role'}, + ), + 'members role': _CommandSpec( + { + 'member': _nonblank, + 'role': (value) => _choice(value, ['read', 'write']), + 'show': _slug, + }, + required: {'member', 'role'}, + ), + 'members remove': _CommandSpec( + {'member': _nonblank, 'show': _slug}, + flags: {'yes'}, + required: {'member', 'yes'}, + ), +}; + +String _help(String path) { + if (path.isNotEmpty) { + final spec = _specs[path]; + if (spec == null) { + final commands = + _specs.keys + .where((command) => command.startsWith('$path ')) + .map( + (command) => + command.substring(path.length + 1).split(' ').first, + ) + .toSet() + .toList() + ..sort(); + return 'Usage: listenbox $path \n\nCommands:\n ${commands.join('\n ')}'; + } + final out = StringBuffer('Usage: listenbox $path'); + if (spec.options.isNotEmpty || spec.flags.isNotEmpty) + out.write(' [OPTIONS]'); + if (spec.positionalCount > 0) { + out.write(path == 'import' ? ' ' : ' '); + } + out.writeln(); + out.writeln(); + out.writeln('Options:'); + for (final name in spec.options.keys) { + out.writeln( + ' --$name VALUE${spec.required.contains(name) ? ' (required)' : ''}', + ); + } + for (final name in spec.flags) { + out.writeln( + ' --$name${spec.required.contains(name) ? ' (required)' : ''}', + ); + } + out.writeln(' --config PATH'); + out.write(' -h, --help'); + return out.toString(); + } + return '''Publish and manage podcasts on Listenbox + +Usage: listenbox [--config PATH] + +Commands: + login Authorize this CLI with Listenbox + auth status|logout Show or remove current authorization + import Import an RSS feed or public YouTube video/playlist + youtube-cookies Import or remove a YouTube session + shows List, create, delete, order, or sync podcasts + episodes List, create, or delete episodes + members Manage team or show members + +Options: + --config PATH Path to CLI config file + -h, --help Show help + -V, --version Show version'''; +} diff --git a/packages/cli/moon.yml b/packages/cli/moon.yml new file mode 100644 index 0000000..3217132 --- /dev/null +++ b/packages/cli/moon.yml @@ -0,0 +1,27 @@ +language: dart +layer: application +dependsOn: [client] +toolchains: + default: system +taskOptions: + cache: true + shell: false +tasks: + build: + description: Build the standalone Dart CLI with all pinned native libraries. + deps: [client:prerequisites] + command: dart ../../tool/build.dart cli + inputs: ['project://client?group=sources'] + outputs: [dist/release/bundle/**/*] + build-e2e: + description: Build the CLI with the development profile and request logs for API E2E. + deps: [client:prerequisites] + command: dart ../../tool/build.dart cli-e2e + inputs: ['project://client?group=sources'] + outputs: [dist/e2e/bundle/**/*] + run: + deps: [client:prerequisites] + command: dart run tool/listenbox_dev.dart + preset: utility + options: + runInCI: false diff --git a/packages/cli/pubspec.yaml b/packages/cli/pubspec.yaml index 87c1754..a36dd05 100644 --- a/packages/cli/pubspec.yaml +++ b/packages/cli/pubspec.yaml @@ -6,5 +6,6 @@ environment: sdk: ^3.13.0 dependencies: http: ^1.5.0 + image: ^4.10.1 listenbox_sync_engine: path: ../sync-engine diff --git a/packages/cli/tool/listenbox_dev.dart b/packages/cli/tool/listenbox_dev.dart new file mode 100644 index 0000000..dd604e6 --- /dev/null +++ b/packages/cli/tool/listenbox_dev.dart @@ -0,0 +1,7 @@ +import 'dart:io'; + +import 'package:listenbox_cli/listenbox_cli.dart'; + +Future main(List arguments) async { + exitCode = await runListenbox(arguments, debugProfile: true); +} diff --git a/packages/desktop/.gitignore b/packages/desktop/.gitignore new file mode 100644 index 0000000..79f7eca --- /dev/null +++ b/packages/desktop/.gitignore @@ -0,0 +1,48 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ diff --git a/packages/desktop/.metadata b/packages/desktop/.metadata new file mode 100644 index 0000000..9b4fcbb --- /dev/null +++ b/packages/desktop/.metadata @@ -0,0 +1,36 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: linux + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: macos + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: windows + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/desktop/README.md b/packages/desktop/README.md new file mode 100644 index 0000000..5906601 --- /dev/null +++ b/packages/desktop/README.md @@ -0,0 +1,24 @@ +# Listenbox desktop + +The Flutter desktop interface uses the shared `listenbox_sync_engine` client for +profiles, authentication, imports, downloads, and synchronization. + +Start a standard Flutter session from this directory: + +```sh +flutter run -d macos +``` + +Use `windows` or `linux` on those hosts. Debug sessions load +`../../config/dev.yaml`; set `LISTENBOX_CONFIG` to use another config file. +Press `r` to hot reload Dart edits, or use the repository's VS Code launch +configuration for reload on save. The shared client and admitted work survive +hot reload. + +From the client repository root, `moon run desktop:build` creates the release +bundle and `moon run desktop:test-e2e` runs the headless integrated Flutter +suite with a real shared client and local HTTP fixture. It does not open a +desktop window. + +See [the development guide](../../docs/DEVELOPMENT.md) for toolchain and native +asset details. diff --git a/packages/desktop/assets/icon.png b/packages/desktop/assets/icon.png new file mode 100644 index 0000000..0a96e4e Binary files /dev/null and b/packages/desktop/assets/icon.png differ diff --git a/packages/desktop/assets/tray-macos.png b/packages/desktop/assets/tray-macos.png new file mode 100644 index 0000000..9abb3af Binary files /dev/null and b/packages/desktop/assets/tray-macos.png differ diff --git a/packages/desktop/assets/tray-windows.ico b/packages/desktop/assets/tray-windows.ico new file mode 100644 index 0000000..fe778b8 Binary files /dev/null and b/packages/desktop/assets/tray-windows.ico differ diff --git a/packages/desktop/assets/tray-windows.png b/packages/desktop/assets/tray-windows.png new file mode 100644 index 0000000..2a40001 Binary files /dev/null and b/packages/desktop/assets/tray-windows.png differ diff --git a/packages/desktop/assets/tray.png b/packages/desktop/assets/tray.png new file mode 100644 index 0000000..0a96e4e Binary files /dev/null and b/packages/desktop/assets/tray.png differ diff --git a/packages/desktop/lib/desktop_host.dart b/packages/desktop/lib/desktop_host.dart new file mode 100644 index 0000000..13dc457 --- /dev/null +++ b/packages/desktop/lib/desktop_host.dart @@ -0,0 +1,98 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:tray_manager/tray_manager.dart'; +import 'package:window_manager/window_manager.dart'; + +enum DesktopPlatform { macOS, windows, linux } + +/// The operating-system boundary for the persistent desktop workspace. +abstract class DesktopHost { + DesktopPlatform get platform; + + void attach( + WindowListener windowListener, + TrayListener trayListener, + Future Function() requestQuit, + ); + + void detach(WindowListener windowListener, TrayListener trayListener); + Future installTray(Menu menu); + Future hideWindow(); + Future openWindow(); + Future popUpTrayMenu(); + Future destroyTray(); + void exitProcess(int code); +} + +class NativeDesktopHost implements DesktopHost { + const NativeDesktopHost(); + + @override + DesktopPlatform get platform => Platform.isMacOS + ? DesktopPlatform.macOS + : Platform.isWindows + ? DesktopPlatform.windows + : DesktopPlatform.linux; + + @override + void attach( + WindowListener windowListener, + TrayListener trayListener, + Future Function() requestQuit, + ) { + if (platform == DesktopPlatform.macOS) { + const MethodChannel('listenbox/native') + .setMethodCallHandler((call) async { + if (call.method == 'quitRequested') await requestQuit(); + }); + } + windowManager.addListener(windowListener); + trayManager.addListener(trayListener); + } + + @override + void detach(WindowListener windowListener, TrayListener trayListener) { + if (platform == DesktopPlatform.macOS) { + const MethodChannel('listenbox/native').setMethodCallHandler(null); + } + windowManager.removeListener(windowListener); + trayManager.removeListener(trayListener); + } + + @override + Future installTray(Menu menu) async { + // Match the Rust client's tray.svg renders; the Windows ICO embeds its + // tray-windows.png bytes for Win32 LoadImage. + final asset = switch (platform) { + DesktopPlatform.macOS => 'assets/tray-macos.png', + DesktopPlatform.windows => 'assets/tray-windows.ico', + DesktopPlatform.linux => 'assets/tray.png', + }; + await trayManager.setIcon( + asset, + isTemplate: platform == DesktopPlatform.macOS, + ); + await trayManager.setToolTip('Listenbox — YouTube to podcast sync'); + await trayManager.setContextMenu(menu); + } + + @override + Future hideWindow() => windowManager.hide(); + + @override + Future openWindow() async { + // window_manager.show restores a minimized window before showing it. + await windowManager.show(); + await windowManager.focus(); + } + + @override + Future popUpTrayMenu() => trayManager.popUpContextMenu(); + + @override + Future destroyTray() => trayManager.destroy(); + + @override + void exitProcess(int code) => exit(code); +} diff --git a/packages/desktop/lib/main.dart b/packages/desktop/lib/main.dart new file mode 100644 index 0000000..828a84b --- /dev/null +++ b/packages/desktop/lib/main.dart @@ -0,0 +1,1688 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:listenbox_sync_engine/sync_engine.dart'; +import 'package:tray_manager/tray_manager.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:window_manager/window_manager.dart'; + +import 'desktop_host.dart'; + +/// The client belongs to the running app, so a Flutter hot reload rebuilds the +/// interface without reopening SQLite or cancelling admitted transfers. +Future main(List args) => launchDesktop(args); + +Future launchDesktop(List args) async { + WidgetsFlutterBinding.ensureInitialized(); + final nativeArgs = Platform.isMacOS + ? (await const MethodChannel('listenbox/native') + .invokeListMethod('arguments')) ?? + args + : args; + final configArg = nativeArgs.indexOf('--config'); + if (configArg >= 0 && configArg + 1 >= nativeArgs.length) { + throw const FormatException('--config requires a path'); + } + String? configPath = configArg < 0 ? null : nativeArgs[configArg + 1]; + configPath ??= Platform.environment['LISTENBOX_CONFIG']; + if (configPath == null && !const bool.fromEnvironment('dart.vm.product')) { + final checkoutConfig = File('../../config/dev.yaml'); + if (!checkoutConfig.existsSync()) { + throw const FormatException( + 'Development config not found. Set LISTENBOX_CONFIG to config/dev.yaml.', + ); + } + configPath = checkoutConfig.absolute.path; + } + final config = Config.load(explicitPath: configPath); + if (!const bool.fromEnvironment('dart.vm.product')) { + stderr.writeln('Listenbox desktop profile: ${config.directory}'); + stderr.writeln('Listenbox API: ${config.apiOrigin}'); + } + await windowManager.ensureInitialized(); + await windowManager.setPreventClose(true); + await windowManager.setMinimumSize(const Size(840, 600)); + unawaited( + windowManager.waitUntilReadyToShow( + const WindowOptions( + size: Size(1080, 760), + center: true, + title: 'Listenbox', + ), + () async { + await windowManager.show(); + await windowManager.focus(); + }, + ), + ); + runApp(ListenboxDesktop(client: Client(config))); +} + +class ListenboxDesktop extends StatefulWidget { + const ListenboxDesktop({ + super.key, + required this.client, + this.host = const NativeDesktopHost(), + }); + final Client client; + final DesktopHost host; + @override + State createState() => DesktopWorkspaceState(); +} + +class _Palette { + const _Palette(this.dark); + final bool dark; + Color get background => + dark ? const Color(0xff242424) : const Color(0xfffcfcfc); + Color get rail => dark ? const Color(0xff292929) : const Color(0xfff1f1f1); + Color get sheet => dark ? const Color(0xff2b2b2b) : Colors.white; + Color get ink => dark ? const Color(0xfff8f8f8) : const Color(0xff303030); + Color get muted => dark ? const Color(0xffcccccc) : const Color(0xff656565); + Color get border => dark ? const Color(0xff777777) : const Color(0xff999999); + Color get divider => dark ? const Color(0xff444444) : const Color(0xffe7e7e7); + Color get selected => + dark ? const Color(0xff484848) : const Color(0xffe6e6e6); + Color get action => dark ? const Color(0xff727272) : const Color(0xff303030); + Color get danger => dark ? const Color(0xffef9a8d) : const Color(0xffb44d42); +} + +class _Notice { + const _Notice(this.message, {this.upgradeUrl, this.signIn = false}); + final String message; + final String? upgradeUrl; + final bool signIn; +} + +class DesktopWorkspaceState extends State + with WindowListener, TrayListener { + Catalog? catalog; + String? teamId; + String? selectedSlug; + bool teamPicker = false; + bool importing = false; + bool importOpen = false; + bool importVideo = false; + bool loading = false; + bool authenticating = false; + bool settingsOpen = false; + bool cookieBusy = false; + bool cookieSaved = false; + bool stopping = false; + bool _autoSyncStarted = false; + bool _episodeLoading = false; + String? _episodeCursor; + String? _episodeError; + String? _cookieMessage; + String? _cookieError; + _Notice? notice; + List> episodes = []; + final Map _jobs = {}; + final Map _reports = {}; + final TextEditingController source = TextEditingController(); + final TextEditingController cookieText = TextEditingController(); + CancellationToken _life = CancellationToken(); + CancellationToken? _episodeCancel; + CancellationToken? _importCancel; + StreamSubscription? _downloadSubscription; + DownloadSnapshot? progress; + int _episodeRequest = 0; + bool _trayInstalled = false; + bool _quitRequested = false; + Future? initialLoad; + final Map> syncSettled = {}; + Completer? episodesSettled; + Completer? settingsSettled; + Completer? cookiesSettled; + Completer? importSettled; + Completer? logoutSettled; + Future? windowHiddenSettled; + Future? windowOpenSettled; + Future Function(String)? browserOpener; + + Client get client => widget.client; + DesktopHost get host => widget.host; + bool get loaded => catalog != null; + List> get shows => + catalog?.shows.where(_isImport).toList() ?? const []; + Map? get selectedShow { + for (final show in shows) { + if (show['slug'] == selectedSlug) return show; + } + return null; + } + + static bool _isImport(Map show) { + final youtube = show['youtube']; + return youtube is Map && youtube['kind'] == 'import'; + } + + String _string(Map row, String key) => + row[key] is String ? row[key] as String : ''; + String _teamName(String? id) { + for (final team in catalog?.teams ?? const >[]) { + if (team['id'] == id) return _string(team, 'name'); + } + return 'your authorized team'; + } + + @override + void initState() { + super.initState(); + host.attach(this, this, quit); + progress = client.downloads.snapshot(); + _downloadSubscription = client.downloads.changes.listen((value) { + if (mounted) setState(() => progress = value); + }); + unawaited(_installTray()); + if (client.hasCredentials) initialLoad = reload(); + } + + Future _installTray() async { + try { + await host.installTray( + Menu( + items: [ + MenuItem(key: 'show', label: 'Open Listenbox'), + MenuItem(key: 'quit', label: 'Quit Listenbox'), + ], + ), + ); + _trayInstalled = true; + } catch (error) { + // A missing status item must not prevent the workspace from opening. + stderr.writeln('Listenbox status item unavailable: $error'); + } + } + + @override + void onWindowClose() { + windowHiddenSettled = host.hideWindow(); + } + + @override + void onTrayIconMouseDown() { + if (host.platform == DesktopPlatform.macOS) { + unawaited(host.popUpTrayMenu()); + } else if (host.platform == DesktopPlatform.windows) { + _requestOpenWindow(); + } + } + + @override + void onTrayIconRightMouseDown() { + if (host.platform == DesktopPlatform.macOS || + host.platform == DesktopPlatform.windows) { + unawaited(host.popUpTrayMenu()); + } + } + + void _requestOpenWindow() { + windowOpenSettled = _openWindow(); + } + + Future _openWindow() async { + await host.openWindow(); + } + + @override + void onTrayMenuItemClick(MenuItem item) { + if (item.key == 'show') _requestOpenWindow(); + if (item.key == 'quit') unawaited(quit()); + } + + Future quit() async { + if (_quitRequested) return; + _quitRequested = true; + setState(() => stopping = true); + _life.cancel(); + _episodeCancel?.cancel(); + _importCancel?.cancel(); + for (final token in _jobs.values) { + token.cancel(); + } + try { + await client.close(); + if (_trayInstalled) await host.destroyTray(); + host.exitProcess(0); + } catch (error) { + stderr.writeln('Could not finish shutdown: $error'); + exitCode = 1; + } + } + + Future logout() async { + if (stopping) return; + logoutSettled = Completer(); + setState(() { + stopping = true; + notice = null; + }); + _life.cancel(); + _episodeCancel?.cancel(); + _importCancel?.cancel(); + for (final token in _jobs.values) { + token.cancel(); + } + try { + await client.logout(); + if (!mounted) return; + _life = CancellationToken(); + setState(() { + catalog = null; + teamId = null; + selectedSlug = null; + teamPicker = false; + importOpen = false; + settingsOpen = false; + importing = false; + _autoSyncStarted = false; + _jobs.clear(); + _reports.clear(); + episodes = []; + progress = client.downloads.snapshot(); + stopping = false; + }); + } catch (error) { + if (mounted) + setState(() { + stopping = false; + notice = _Notice('Could not sign out. $error'); + }); + } finally { + logoutSettled?.complete(); + } + } + + Future login() async { + if (authenticating || stopping) return; + setState(() { + authenticating = true; + notice = null; + }); + try { + await client.login((url) => _open(url.toString()), cancel: _life); + await reload(); + } catch (error) { + if (mounted) + setState(() => notice = _Notice('Sign-in did not finish. $error')); + } finally { + if (mounted) setState(() => authenticating = false); + } + } + + Future reload({bool preserveNotice = false}) async { + if (loading || stopping) return; + setState(() { + loading = true; + if (!preserveNotice) notice = null; + }); + try { + final result = await client.catalog(cancel: _life); + if (!mounted || stopping) return; + final filtered = Catalog( + teams: result.teams, + importTeam: result.importTeam, + shows: result.shows.where(_isImport).toList(), + ); + setState(() { + catalog = filtered; + if (!shows.any((show) => show['slug'] == selectedSlug)) { + selectedSlug = + shows + .where( + (show) => teamId == null || show['team_id'] == teamId, + ) + .firstOrNull?['slug'] + as String?; + } + }); + if (selectedSlug != null) unawaited(loadEpisodes()); + _startAutoSync(); + } on AuthenticationRequired { + if (mounted) + setState(() { + catalog = null; + selectedSlug = null; + episodes = []; + }); + } catch (error) { + if (mounted) + setState(() => notice = _Notice('Could not load podcasts. $error')); + } finally { + if (mounted) setState(() => loading = false); + } + } + + void _startAutoSync() { + if (_autoSyncStarted || !client.hasCredentials) return; + _autoSyncStarted = true; + syncAll(onlyNew: true); + unawaited(() async { + while (await client.nextScan(_life)) { + if (!mounted || stopping) break; + syncAll(); + } + }()); + } + + void syncAll({bool onlyNew = false}) { + for (final show in shows) { + final slug = _string(show, 'slug'); + if (show['has_active_subscription'] == true && + (!onlyNew || !_reports.containsKey(slug))) { + unawaited(syncShow(slug)); + } + } + } + + Future syncShow(String slug) async { + if (stopping || !loaded || _jobs.containsKey(slug)) return; + final settled = Completer(); + syncSettled[slug] = settled; + final token = _life.child(); + setState(() { + _jobs[slug] = token; + _reports[slug] = 'Reading YouTube and Listenbox…'; + }); + try { + await client.sync( + slug, + cancel: token, + onReport: (report) { + if (!mounted || stopping) return; + setState(() => _reports[slug] = _reportText(report)); + if (selectedSlug == slug) unawaited(loadEpisodes()); + }, + ); + } on OperationCancelled { + if (mounted && !stopping) + setState( + () => + _reports[slug] = 'Stopped. Progress is saved for the next sync.', + ); + } on SignInRequired { + if (mounted && !stopping) + setState(() { + notice = const _Notice( + 'YouTube is asking you to sign in. Add fresh cookies in Settings, then use Sync now to continue this podcast.', + signIn: true, + ); + _reports[slug] = + 'YouTube sign-in required. Open Settings to add fresh cookies.'; + }); + } catch (error) { + if (mounted && !stopping) + setState(() => _reports[slug] = 'Sync failed. $error'); + } finally { + if (mounted) setState(() => _jobs.remove(slug)); + settled.complete(); + } + } + + String _reportText(Report report) => + '${report.added} added · ${report.removed} removed · ${report.unchanged} unchanged · ${report.skipped} skipped${report.reordered ? ' · Order updated' : ''}'; + + void selectShow(String? slug) { + _episodeCancel?.cancel(); + setState(() { + selectedSlug = slug; + importOpen = false; + settingsOpen = false; + episodes = []; + _episodeCursor = null; + _episodeError = null; + }); + if (slug != null) unawaited(loadEpisodes()); + } + + Future loadEpisodes({bool append = false}) async { + if (append && (_episodeLoading || _episodeCursor == null)) return; + final slug = selectedSlug; + if (slug == null || stopping || !loaded) return; + final settled = Completer(); + episodesSettled = settled; + _episodeCancel?.cancel(); + final request = ++_episodeRequest; + final token = _life.child(); + _episodeCancel = token; + setState(() { + _episodeLoading = true; + _episodeError = null; + if (!append) { + episodes = []; + _episodeCursor = null; + } + }); + try { + final page = await client.episodes( + slug, + cursor: append ? _episodeCursor : null, + cancel: token, + ); + if (!mounted || request != _episodeRequest || stopping) return; + final incoming = (page['episodes'] as List).cast>(); + final next = page['next_cursor'] as String?; + setState(() { + final previous = append ? episodes : >[]; + final ids = previous.map((row) => row['id']).toSet(); + episodes = [ + ...previous, + ...incoming.where((row) => ids.add(row['id'])), + ]; + _episodeError = append && next != null && next == _episodeCursor + ? 'Could not load the next page. Reload the podcast to try again.' + : null; + _episodeCursor = _episodeError == null ? next : null; + }); + } on OperationCancelled { + // A newer selection or refresh owns the episode list. + } catch (error) { + if (mounted && request == _episodeRequest) + setState(() => _episodeError = 'Could not load episodes. $error'); + } finally { + if (mounted && request == _episodeRequest) + setState(() => _episodeLoading = false); + settled.complete(); + } + } + + Future importPlaylist() async { + if (!loaded || importing || stopping) return; + final settled = Completer(); + importSettled = settled; + late final String sourceUrl; + try { + sourceUrl = playlistSource(source.text); + } catch (error) { + setState(() => notice = _Notice(error.toString())); + settled.complete(); + return; + } + final token = _life.child(); + _importCancel = token; + String? createdSlug; + setState(() { + importing = true; + notice = null; + }); + try { + final result = await client.importPlaylist( + sourceUrl, + importVideo ? 'video' : 'audio', + cancel: token, + onCreated: (show) { + if (!mounted || stopping) return; + final slug = _string(show, 'slug'); + createdSlug = slug; + setState(() { + catalog = Catalog( + teams: catalog!.teams, + importTeam: catalog!.importTeam, + shows: [...catalog!.shows, show], + ); + teamId = _string(show, 'team_id'); + selectedSlug = slug; + importOpen = false; + _jobs[slug] = token; + _reports[slug] = 'Importing the first episodes…'; + }); + }, + ); + if (!mounted || stopping) return; + setState(() { + source.clear(); + selectedSlug = _string(result.show, 'slug'); + _reports[selectedSlug!] = _reportText(result.report); + }); + unawaited(loadEpisodes()); + } catch (error) { + if (!mounted || stopping) return; + String? upgrade; + if (error is PaymentRequired) { + final importTeam = catalog?.importTeam; + if (importTeam != null) { + upgrade = client.upgradeUrl(importTeam); + if (importVideo) upgrade = '$upgrade?family=video_hd'; + } + } + setState(() { + if (createdSlug != null) + _reports[createdSlug!] = 'Import stopped. Use Sync now to continue.'; + notice = error is SignInRequired + ? const _Notice( + 'YouTube is asking you to sign in. Add fresh cookies in Settings, then use Sync now to continue this podcast.', + signIn: true, + ) + : _Notice( + error is PaymentRequired + ? '${createdSlug == null ? 'Could not create podcast.' : 'Podcast created, but the import did not finish.'} ${error.message.isEmpty ? 'Payment is required to continue.' : error.message}' + : 'Import did not finish. $error', + upgradeUrl: upgrade, + ); + }); + unawaited(reload(preserveNotice: true)); + } finally { + if (mounted) + setState(() { + importing = false; + _importCancel = null; + if (createdSlug != null) _jobs.remove(createdSlug); + }); + settled.complete(); + } + } + + Future openSettings() async { + if (settingsOpen || stopping) return; + final settled = Completer(); + settingsSettled = settled; + cookieText.clear(); + setState(() { + settingsOpen = true; + importOpen = false; + _cookieMessage = null; + _cookieError = null; + cookieBusy = true; + }); + try { + final saved = await client.cookieJar.isEnabled(); + if (mounted) setState(() => cookieSaved = saved); + } catch (error) { + if (mounted) setState(() => _cookieError = error.toString()); + } finally { + if (mounted) setState(() => cookieBusy = false); + settled.complete(); + } + } + + Future saveCookies({bool remove = false}) async { + if (cookieBusy || stopping) return; + final settled = Completer(); + cookiesSettled = settled; + setState(() { + cookieBusy = true; + _cookieMessage = null; + _cookieError = null; + }); + try { + if (remove) { + await client.cookieJar.remove(); + } else { + await client.cookieJar.importText(cookieText.text); + } + if (!mounted) return; + setState(() { + cookieSaved = !remove; + cookieText.clear(); + _cookieMessage = remove + ? 'Cookies removed. Future requests will use anonymous access.' + : 'Cookies saved. Return to your podcast and choose Sync now.'; + }); + } catch (error) { + if (mounted) setState(() => _cookieError = error.toString()); + } finally { + if (mounted) setState(() => cookieBusy = false); + settled.complete(); + } + } + + Future _open(String raw) async { + final url = Uri.parse(raw); + if ((url.scheme != 'https' && url.scheme != 'http') || !url.hasAuthority) { + throw FormatException('Invalid browser link: $raw'); + } + if (browserOpener != null) { + await browserOpener!(raw); + return; + } + if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { + throw StateError('Could not open $raw'); + } + } + + @override + void dispose() { + host.detach(this, this); + _life.cancel(); + _episodeCancel?.cancel(); + _downloadSubscription?.cancel(); + source.dispose(); + cookieText.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final t = _Palette( + MediaQuery.platformBrightnessOf(context) == Brightness.dark, + ); + final theme = ThemeData( + brightness: t.dark ? Brightness.dark : Brightness.light, + useMaterial3: true, + fontFamily: Platform.isMacOS ? '.SF NS Text' : null, + scaffoldBackgroundColor: t.background, + colorScheme: ColorScheme.fromSeed( + seedColor: t.action, + brightness: t.dark ? Brightness.dark : Brightness.light, + surface: t.sheet, + onSurface: t.ink, + primary: t.action, + onPrimary: Colors.white, + ), + textTheme: Theme.of(context).textTheme + .apply(bodyColor: t.ink, displayColor: t.ink), + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: t.ink, + textStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + backgroundColor: t.action, + foregroundColor: Colors.white, + textStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + minimumSize: const Size(0, 36), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + ), + inputDecorationTheme: InputDecorationTheme( + isDense: true, + filled: true, + fillColor: t.sheet, + hintStyle: TextStyle(color: t.muted), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 12, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: t.border), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: t.border), + ), + ), + ); + return MaterialApp( + title: 'Listenbox', + debugShowCheckedModeBanner: false, + theme: theme, + home: Scaffold( + body: Stack( + children: [ + Row( + children: [ + SizedBox(width: 240, child: _sidebar(t)), + Expanded(child: _mainPane(t)), + ], + ), + if (stopping) _quitNotice(t), + ], + ), + ), + ); + } + + Widget _sidebar(_Palette t) { + final scoped = shows + .where((show) => teamId == null || show['team_id'] == teamId) + .toList(); + return Container( + decoration: BoxDecoration( + color: t.rail, + border: Border(right: BorderSide(color: t.divider)), + ), + child: Column( + children: [ + Container( + height: 56, + padding: const EdgeInsets.symmetric(horizontal: 16), + alignment: Alignment.centerLeft, + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: t.divider)), + ), + child: const Text( + 'Listenbox', + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 12), + child: Column( + children: [ + TextButton( + key: const Key('team-picker'), + onPressed: loaded + ? () => setState(() => teamPicker = !teamPicker) + : null, + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + minimumSize: const Size.fromHeight(36), + ), + child: Row( + children: [ + Expanded( + child: Text( + teamId == null ? 'All teams' : _teamName(teamId), + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: t.ink, + ), + ), + ), + Icon( + teamPicker + ? Icons.keyboard_arrow_up + : Icons.keyboard_arrow_down, + size: 19, + color: t.muted, + ), + ], + ), + ), + if (teamPicker) + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 180), + child: SingleChildScrollView( + child: Column( + children: [ + _teamChoice(t, 'All teams', null), + for (final team + in catalog?.teams ?? + const >[]) + _teamChoice( + t, + _string(team, 'name'), + _string(team, 'id'), + ), + ], + ), + ), + ), + const SizedBox(height: 12), + FilledButton( + key: const Key('new-import'), + onPressed: loaded && !importing && !stopping + ? () => setState(() { + importOpen = true; + settingsOpen = false; + notice = null; + }) + : null, + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 12), + minimumSize: const Size.fromHeight(36), + ), + child: const Row( + children: [ + Expanded( + child: Text( + 'Import playlist', + textAlign: TextAlign.left, + ), + ), + Icon(Icons.add, size: 18), + ], + ), + ), + ], + ), + ), + Expanded( + child: ListView.builder( + key: const Key('podcasts'), + padding: const EdgeInsets.symmetric(horizontal: 8), + itemCount: scoped.isEmpty && loaded ? 1 : scoped.length, + itemBuilder: (context, index) { + if (scoped.isEmpty) + return Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), + child: Text( + 'Your imported playlists will appear here.', + style: TextStyle(fontSize: 12, color: t.muted), + ), + ); + final show = scoped[index], slug = _string(show, 'slug'); + final status = _jobs.containsKey(slug) + ? 'Syncing' + : show['has_active_subscription'] == true + ? 'Automatic sync' + : 'Plan required'; + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Material( + color: !importOpen && selectedSlug == slug + ? t.selected + : Colors.transparent, + borderRadius: BorderRadius.circular(10), + child: InkWell( + key: Key('show-$slug'), + borderRadius: BorderRadius.circular(10), + onTap: () => selectShow(slug), + child: Padding( + padding: const EdgeInsets.all(8), + child: Row( + children: [ + _artwork(show['image_url'] as String?, 44, t), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _string(show, 'title'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 3), + Text( + status, + style: TextStyle( + fontSize: 12, + color: t.muted, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + 'YouTube → Listenbox', + style: TextStyle(fontSize: 12, color: t.muted), + ), + ), + ), + ], + ), + ); + } + + Widget _teamChoice(_Palette t, String label, String? id) => TextButton( + key: Key(id == null ? 'all-teams' : 'team-$id'), + onPressed: () { + setState(() { + teamId = id; + teamPicker = false; + }); + final first = shows + .where((show) => id == null || show['team_id'] == id) + .firstOrNull; + selectShow(first?['slug'] as String?); + }, + style: TextButton.styleFrom( + minimumSize: const Size.fromHeight(36), + padding: const EdgeInsets.symmetric(horizontal: 8), + ), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.ink), + ), + ), + ); + + Widget _artwork(String? url, double size, _Palette t) { + final imageUrl = url?.trim(); + final uri = imageUrl == null ? null : Uri.tryParse(imageUrl); + final validUrl = + uri != null && + (uri.scheme == 'https' || uri.scheme == 'http') && + uri.host.isNotEmpty; + final decodeSize = (size * MediaQuery.devicePixelRatioOf(context)) + .ceil() + .clamp(1, 512); + return ClipRRect( + borderRadius: BorderRadius.circular(size == 44 ? 8 : 14), + child: SizedBox( + width: size, + height: size, + child: !validUrl + ? _artworkFallback(t) + : Image( + image: ResizeImage( + NetworkImage(imageUrl!), + width: decodeSize, + height: decodeSize, + policy: ResizeImagePolicy.fit, + ), + width: size, + height: size, + fit: BoxFit.cover, + filterQuality: FilterQuality.medium, + loadingBuilder: (_, image, progress) => + progress == null ? image : _artworkFallback(t), + errorBuilder: (_, _, _) => _artworkFallback(t), + ), + ), + ); + } + + Widget _artworkFallback(_Palette t) => Container( + color: t.selected, + child: Icon(Icons.headphones, color: t.muted, size: 22), + ); + + Widget _mainPane(_Palette t) => Column( + children: [ + Container( + height: 56, + padding: const EdgeInsets.symmetric(horizontal: 24), + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: t.divider)), + ), + child: Row( + children: [ + Expanded( + child: Text( + settingsOpen ? 'Settings' : 'YouTube imports', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: t.muted, + ), + ), + ), + if (loaded) + TextButton( + key: const Key('reload'), + onPressed: loading || stopping ? null : reload, + child: const Text('Reload'), + ), + if (loaded) const SizedBox(width: 12), + if (loaded) + TextButton( + key: const Key('settings'), + onPressed: stopping ? null : openSettings, + child: const Text('Settings'), + ), + const SizedBox(width: 12), + TextButton( + key: const Key('account'), + onPressed: authenticating || stopping + ? null + : (loaded ? logout : login), + child: Text( + authenticating + ? 'Finish in your browser…' + : loaded + ? 'Log out' + : 'Sign in', + ), + ), + ], + ), + ), + Expanded( + child: SingleChildScrollView( + key: const Key('workspace-content'), + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (notice != null && !settingsOpen) _errorNotice(t), + if (settingsOpen) + _settings(t) + else if (importOpen) + _importForm(t) + else + _detail(t), + if (loaded && !settingsOpen && !importOpen) _episodeList(t), + if (loaded && !settingsOpen) _transfers(t), + ], + ), + ), + ), + ], + ); + + Widget _errorNotice(_Palette t) => Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + key: const Key('error-notice'), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(notice!.message, style: TextStyle(color: t.danger)), + if (notice!.signIn) + TextButton( + key: const Key('youtube-sign-in-settings'), + onPressed: openSettings, + child: const Text('Open YouTube settings'), + ), + if (notice!.upgradeUrl != null) + TextButton( + key: const Key('upgrade-plan'), + onPressed: () => _open(notice!.upgradeUrl!), + child: const Text('Upgrade plan'), + ), + ], + ), + ); + + Widget _importForm(_Palette t) { + final team = _teamName(catalog?.importTeam); + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 620), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Import a YouTube playlist', + style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 12), + Text( + 'Give your playlist a podcast home. Import it once, then keep new episodes coming with Listenbox.', + style: TextStyle(fontSize: 14, color: t.muted), + ), + const SizedBox(height: 24), + const Text( + 'Playlist URL', + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + TextField( + key: const Key('playlist-url'), + controller: source, + enabled: !importing && !stopping, + decoration: const InputDecoration( + hintText: 'https://www.youtube.com/playlist?list=…', + ), + ), + const SizedBox(height: 8), + Text( + 'Use a public playlist. Its title becomes your podcast’s name.', + style: TextStyle(fontSize: 12, color: t.muted), + ), + const SizedBox(height: 24), + const Text( + 'Podcast format', + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + Row( + children: [ + _formatChoice(t, 'Audio', Icons.headphones, false), + const SizedBox(width: 8), + _formatChoice(t, 'Video', Icons.videocam_outlined, true), + ], + ), + const SizedBox(height: 24), + Divider(color: t.divider), + const SizedBox(height: 16), + Text('Creates a new podcast in $team.'), + const SizedBox(height: 8), + Text( + importVideo + ? 'A video plan with enough storage for the playlist is required. Playlist order is preserved. On later syncs, videos removed from the playlist are removed from the podcast.' + : 'A paid podcast plan is required. Playlist order is preserved. On later syncs, videos removed from the playlist are removed from the podcast.', + style: TextStyle(fontSize: 12, color: t.muted), + ), + const SizedBox(height: 16), + Wrap( + spacing: 12, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + FilledButton( + key: const Key('start-import'), + onPressed: importing || stopping ? null : importPlaylist, + child: Text( + importing + ? 'Checking playlist and plan…' + : 'Create podcast & import', + ), + ), + if (importing) + const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + if (!importing && selectedShow != null) + TextButton( + key: const Key('cancel-import'), + onPressed: () => setState(() { + importOpen = false; + notice = null; + }), + child: const Text('Cancel'), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _formatChoice(_Palette t, String label, IconData icon, bool video) { + final selected = importVideo == video; + return selected + ? FilledButton( + key: Key('import-${label.toLowerCase()}'), + onPressed: importing || stopping + ? null + : () => setState(() => importVideo = video), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 18), + const SizedBox(width: 8), + Text(label), + ], + ), + ) + : OutlinedButton( + key: Key('import-${label.toLowerCase()}'), + onPressed: importing || stopping + ? null + : () => setState(() => importVideo = video), + style: OutlinedButton.styleFrom( + foregroundColor: t.ink, + side: BorderSide(color: t.border), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 18), + const SizedBox(width: 8), + Text(label), + ], + ), + ); + } + + Widget _detail(_Palette t) { + if (!loaded) + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 48), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Your playlists. Your podcast.', + style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 24), + Text( + 'Bring a public YouTube playlist to Listenbox, then keep your podcast in sync from this desktop.', + style: TextStyle(color: t.muted), + ), + const SizedBox(height: 24), + FilledButton( + key: const Key('welcome-sign-in'), + onPressed: authenticating ? null : login, + child: const Text('Sign in to Listenbox'), + ), + ], + ), + ), + ); + final show = selectedShow; + if (show == null) + return Text( + 'Choose a podcast, or import your first playlist.', + style: TextStyle(color: t.muted), + ); + final youtube = show['youtube'] as Map; + final sourceUrl = youtube['source_url'] as String; + final slug = _string(show, 'slug'); + final running = _jobs.containsKey(slug); + final active = show['has_active_subscription'] == true; + final isPlaylist = + Uri.tryParse(sourceUrl)?.queryParameters.containsKey('list') ?? false; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _artwork(show['image_url'] as String?, 120, t), + const SizedBox(width: 24), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _string(show, 'title'), + style: const TextStyle( + fontSize: 30, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + Text( + show['source_kind'] == 'video' + ? 'Video podcast' + : 'Audio podcast', + style: TextStyle(color: t.muted), + ), + const SizedBox(height: 10), + TextButton( + key: const Key('open-show'), + onPressed: () => _open(client.showUrl(show)), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.open_in_new, size: 16), + SizedBox(width: 6), + Text('Open in Listenbox'), + ], + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 24), + Divider(color: t.divider), + const SizedBox(height: 24), + const Text( + 'YouTube source', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 12), + TextButton( + key: const Key('open-playlist'), + onPressed: () => _open(sourceUrl), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.open_in_new, size: 16), + const SizedBox(width: 8), + Flexible(child: Text(sourceUrl, overflow: TextOverflow.ellipsis)), + ], + ), + ), + const SizedBox(height: 12), + Text( + isPlaylist + ? 'Episodes follow the playlist’s order. Removed videos leave this podcast on the next sync.' + : 'This podcast imports a YouTube video. Sync again to resume unfinished transfers.', + style: TextStyle(fontSize: 12, color: t.muted), + ), + if (!active) + Padding( + padding: const EdgeInsets.only(top: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Choose a paid audio or video plan to resume syncing.', + ), + TextButton( + key: const Key('choose-plan'), + onPressed: () => + _open(client.upgradeUrl(_string(show, 'team_id'))), + child: const Text('Upgrade plan'), + ), + ], + ), + ), + const SizedBox(height: 24), + Row( + children: [ + FilledButton( + key: const Key('sync-now'), + onPressed: active && !running && !stopping + ? () => syncShow(slug) + : null, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.sync, size: 18), + SizedBox(width: 8), + Text('Sync now'), + ], + ), + ), + if (running) ...[ + const SizedBox(width: 8), + OutlinedButton( + key: const Key('stop-sync'), + onPressed: () => _jobs[slug]?.cancel(), + child: const Text('Stop'), + ), + ], + ], + ), + const SizedBox(height: 16), + Text( + _reports[slug] ?? + 'Syncs automatically every hour while Listenbox is running.', + key: const Key('sync-status'), + style: TextStyle(color: t.muted), + ), + ], + ); + } + + Widget _episodeList(_Palette t) { + if (selectedShow == null) return const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.only(top: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Divider(color: t.divider), + const SizedBox(height: 24), + const Text( + 'Episodes', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + for (final episode in episodes) + Container( + padding: const EdgeInsets.symmetric(vertical: 12), + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: t.divider)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_string(episode, 'title')), + const SizedBox(height: 4), + Text( + [ + if (episode['duration_seconds'] case final int duration + when duration > 0) + _duration(duration), + episode['status'] == 'published' ? 'Published' : 'Draft', + ].join(' · '), + style: TextStyle(fontSize: 12, color: t.muted), + ), + ], + ), + ), + if (_episodeLoading) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Text( + 'Loading episodes…', + style: TextStyle(color: t.muted), + ), + ), + if (!_episodeLoading && _episodeError != null) ...[ + Text(_episodeError!, style: TextStyle(color: t.danger)), + TextButton( + key: const Key('retry-episodes'), + onPressed: loadEpisodes, + child: const Text('Reload episodes'), + ), + ], + if (!_episodeLoading && _episodeError == null && episodes.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Text( + 'No episodes synced yet.', + style: TextStyle(color: t.muted), + ), + ), + if (_episodeCursor != null) + TextButton( + key: const Key('more-episodes'), + onPressed: _episodeLoading + ? null + : () => loadEpisodes(append: true), + child: const Text('Load more episodes'), + ), + ], + ), + ); + } + + String _duration(int seconds) => seconds >= 3600 + ? '${seconds ~/ 3600}:${((seconds ~/ 60) % 60).toString().padLeft(2, '0')}:${(seconds % 60).toString().padLeft(2, '0')}' + : '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}'; + + Widget _transfers(_Palette t) { + final transfers = + progress?.items.reversed.take(100).toList() ?? const []; + return Padding( + padding: const EdgeInsets.only(top: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Divider(color: t.divider), + const SizedBox(height: 24), + const Text( + 'Transfers', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + if (transfers.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Text( + 'New episodes will appear here as they sync.', + style: TextStyle(color: t.muted), + ), + ), + for (final item in transfers) + Container( + padding: const EdgeInsets.symmetric(vertical: 12), + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: t.divider)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(item.title), + const SizedBox(height: 4), + Text( + item.durationSeconds == null + ? item.sourceTitle + : '${item.sourceTitle} · ${_duration(item.durationSeconds!)}', + style: TextStyle(fontSize: 12, color: t.muted), + ), + ], + ), + ), + const SizedBox(width: 16), + Text( + _phase(item.phase), + style: TextStyle( + color: item.phase == Phase.failed + ? t.danger + : t.muted, + ), + ), + ], + ), + if (item.phase == Phase.downloading && item.total > 0) ...[ + const SizedBox(height: 8), + LinearProgressIndicator( + value: (item.received / item.total).clamp(0, 1), + backgroundColor: t.selected, + color: t.action, + minHeight: 5, + borderRadius: BorderRadius.circular(5), + ), + const SizedBox(height: 6), + Text( + '${(item.received / 1000000).toStringAsFixed(1)} / ${(item.total / 1000000).toStringAsFixed(1)} MB', + style: TextStyle(fontSize: 12, color: t.muted), + ), + ], + if (item.reason != null) + Text(item.reason!, style: TextStyle(color: t.muted)), + if (item.error != null) + Text(item.error!, style: TextStyle(color: t.danger)), + ], + ), + ), + ], + ), + ); + } + + String _phase(Phase phase) => switch (phase) { + Phase.queued => 'Queued', + Phase.resolving => 'Reading source', + Phase.downloading => 'Downloading', + Phase.preparing => 'Preparing media', + Phase.uploading => 'Uploading', + Phase.complete => 'Complete', + Phase.skipped => 'Skipped', + Phase.failed => 'Failed', + }; + + Widget _settings(_Palette t) => ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 720), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Expanded( + child: Text( + 'Settings', + style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), + ), + ), + TextButton( + key: const Key('close-settings'), + onPressed: cookieBusy + ? null + : () => setState(() { + settingsOpen = false; + cookieText.clear(); + }), + child: const Text('Done'), + ), + ], + ), + const SizedBox(height: 24), + const Text( + 'YouTube', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + const Text( + 'If YouTube asks you to sign in, add cookies from a private browser session to continue importing.', + ), + const SizedBox(height: 8), + Text( + 'Cookies stay on this computer and are shared with the Listenbox CLI. Keep them private, like a password.', + style: TextStyle(color: t.muted), + ), + TextButton( + key: const Key('cookie-guide'), + onPressed: () => _open(youtubeCookieGuideUrl), + child: const Text('How to export YouTube cookies'), + ), + const SizedBox(height: 24), + const Text( + 'YouTube cookies', + style: TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + Text( + cookieSaved + ? 'A session is saved. Pasting a new export replaces it.' + : 'Paste a Netscape cookies.txt export, including the header line.', + style: TextStyle(color: t.muted), + ), + const SizedBox(height: 8), + TextField( + key: const Key('cookie-export'), + controller: cookieText, + enabled: !cookieBusy && !stopping, + maxLines: 6, + minLines: 6, + decoration: const InputDecoration( + hintText: 'Paste the complete Netscape cookies.txt export here', + ), + ), + if (_cookieError != null) + Text(_cookieError!, style: TextStyle(color: t.danger)), + if (_cookieMessage != null) Text(_cookieMessage!), + const SizedBox(height: 12), + Wrap( + spacing: 12, + children: [ + FilledButton( + key: const Key('save-cookies'), + onPressed: cookieBusy || stopping ? null : saveCookies, + child: Text(cookieBusy ? 'Please wait…' : 'Save cookies'), + ), + TextButton( + key: const Key('remove-cookies'), + onPressed: cookieBusy || stopping || !cookieSaved + ? null + : () => saveCookies(remove: true), + child: const Text('Remove cookies'), + ), + ], + ), + ], + ), + ); + + Widget _quitNotice(_Palette t) => IgnorePointer( + child: Center( + child: Container( + width: 280, + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: t.action.withValues(alpha: 0.96), + borderRadius: BorderRadius.circular(20), + ), + child: const Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Saving progress', + style: TextStyle(color: Colors.white, fontSize: 18), + ), + SizedBox(height: 12), + Text( + 'Finishing current work…', + style: TextStyle(color: Colors.white), + ), + ], + ), + ), + ), + ); +} diff --git a/packages/desktop/linux/.gitignore b/packages/desktop/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/packages/desktop/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/desktop/linux/CMakeLists.txt b/packages/desktop/linux/CMakeLists.txt new file mode 100644 index 0000000..431f05c --- /dev/null +++ b/packages/desktop/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "listenbox_desktop") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "app.listenbox.listenbox_desktop") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/desktop/linux/flutter/CMakeLists.txt b/packages/desktop/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/packages/desktop/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/desktop/linux/flutter/generated_plugin_registrant.cc b/packages/desktop/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..51123ac --- /dev/null +++ b/packages/desktop/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,27 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin"); + screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar); + g_autoptr(FlPluginRegistrar) tray_manager_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "TrayManagerPlugin"); + tray_manager_plugin_register_with_registrar(tray_manager_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); + g_autoptr(FlPluginRegistrar) window_manager_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "WindowManagerPlugin"); + window_manager_plugin_register_with_registrar(window_manager_registrar); +} diff --git a/packages/desktop/linux/flutter/generated_plugin_registrant.h b/packages/desktop/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/packages/desktop/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/desktop/linux/flutter/generated_plugins.cmake b/packages/desktop/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..9bd5c11 --- /dev/null +++ b/packages/desktop/linux/flutter/generated_plugins.cmake @@ -0,0 +1,28 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + screen_retriever_linux + tray_manager + url_launcher_linux + window_manager +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + client_youtubei +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/desktop/linux/runner/CMakeLists.txt b/packages/desktop/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/packages/desktop/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/packages/desktop/linux/runner/main.cc b/packages/desktop/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/packages/desktop/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/desktop/linux/runner/my_application.cc b/packages/desktop/linux/runner/my_application.cc new file mode 100644 index 0000000..25445de --- /dev/null +++ b/packages/desktop/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "listenbox_desktop"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "listenbox_desktop"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/packages/desktop/linux/runner/my_application.h b/packages/desktop/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/packages/desktop/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/desktop/macos/.gitignore b/packages/desktop/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/packages/desktop/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/packages/desktop/macos/Flutter/Flutter-Debug.xcconfig b/packages/desktop/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/packages/desktop/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/desktop/macos/Flutter/Flutter-Release.xcconfig b/packages/desktop/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/packages/desktop/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/desktop/macos/Flutter/GeneratedPluginRegistrant.swift b/packages/desktop/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..ee2b0ec --- /dev/null +++ b/packages/desktop/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import screen_retriever_macos +import tray_manager +import url_launcher_macos +import window_manager + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin")) + TrayManagerPlugin.register(with: registry.registrar(forPlugin: "TrayManagerPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) + WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin")) +} diff --git a/packages/desktop/macos/Runner.xcodeproj/project.pbxproj b/packages/desktop/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7b5eb57 --- /dev/null +++ b/packages/desktop/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,607 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* listenbox_desktop.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "listenbox_desktop.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* listenbox_desktop.app */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* listenbox_desktop.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/packages/desktop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/desktop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/packages/desktop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/desktop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/desktop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..3ec52bf --- /dev/null +++ b/packages/desktop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/desktop/macos/Runner.xcworkspace/contents.xcworkspacedata b/packages/desktop/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/packages/desktop/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/packages/desktop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/desktop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/packages/desktop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/desktop/macos/Runner/AppDelegate.swift b/packages/desktop/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..3a4057a --- /dev/null +++ b/packages/desktop/macos/Runner/AppDelegate.swift @@ -0,0 +1,27 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return false + } + + override func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + if let controller = mainFlutterWindow?.contentViewController as? FlutterViewController { + let channel = FlutterMethodChannel(name: "listenbox/native", binaryMessenger: controller.engine.binaryMessenger) + channel.invokeMethod("quitRequested", arguments: nil) + } + return .terminateCancel + } + + override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { + mainFlutterWindow?.makeKeyAndOrderFront(sender) + sender.activate(ignoringOtherApps: true) + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/packages/desktop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/packages/desktop/macos/Runner/Base.lproj/MainMenu.xib b/packages/desktop/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/packages/desktop/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/desktop/macos/Runner/Configs/AppInfo.xcconfig b/packages/desktop/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..6e7368c --- /dev/null +++ b/packages/desktop/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = listenbox_desktop + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = app.listenbox.listenboxDesktop + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 app.listenbox. All rights reserved. diff --git a/packages/desktop/macos/Runner/Configs/Debug.xcconfig b/packages/desktop/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/packages/desktop/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/packages/desktop/macos/Runner/Configs/Release.xcconfig b/packages/desktop/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/packages/desktop/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/packages/desktop/macos/Runner/Configs/Warnings.xcconfig b/packages/desktop/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/packages/desktop/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/packages/desktop/macos/Runner/DebugProfile.entitlements b/packages/desktop/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..78c36cf --- /dev/null +++ b/packages/desktop/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,14 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + com.apple.security.network.client + + + diff --git a/packages/desktop/macos/Runner/Info.plist b/packages/desktop/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/packages/desktop/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/packages/desktop/macos/Runner/MainFlutterWindow.swift b/packages/desktop/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..be279f2 --- /dev/null +++ b/packages/desktop/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,26 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + let channel = FlutterMethodChannel( + name: "listenbox/native", + binaryMessenger: flutterViewController.engine.binaryMessenger) + channel.setMethodCallHandler { call, result in + if call.method == "arguments" { + result(Array(ProcessInfo.processInfo.arguments.dropFirst())) + } else { + result(FlutterMethodNotImplemented) + } + } + + super.awakeFromNib() + } +} diff --git a/packages/desktop/macos/Runner/Release.entitlements b/packages/desktop/macos/Runner/Release.entitlements new file mode 100644 index 0000000..08ba3a3 --- /dev/null +++ b/packages/desktop/macos/Runner/Release.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + + diff --git a/packages/desktop/moon.yml b/packages/desktop/moon.yml new file mode 100644 index 0000000..ba3f502 --- /dev/null +++ b/packages/desktop/moon.yml @@ -0,0 +1,40 @@ +language: dart +layer: application +dependsOn: [client] +toolchains: + default: system +taskOptions: + cache: true + shell: false +tasks: + dev: + description: Start a standard Flutter session; r reloads, R restarts, and IDEs can attach. + deps: [client:prerequisites] + command: dart ../../tool/flutter.dart run + args: + - --no-pub + - --device-id=$os + inputs: [] + env: + LISTENBOX_CONFIG: $projectRoot/../../config/dev.yaml + preset: server + options: + interactive: true + cache: false + runInCI: false + build: + description: Build the release desktop bundle for the host OS and architecture. + deps: [client:prerequisites] + command: dart ../../tool/build.dart desktop + inputs: ['project://client?group=sources'] + outputs: [dist/release/**/*] + test-e2e: + description: Exercise desktop flows headlessly with the real shared client and local HTTP fixtures. + deps: [client:prerequisites] + command: dart ../../tool/flutter.dart test + args: + - --no-pub + - test/desktop_e2e_test.dart + inputs: ['project://client?group=sources'] + options: + cache: false diff --git a/packages/desktop/pubspec.yaml b/packages/desktop/pubspec.yaml index fa478e3..bdd6958 100644 --- a/packages/desktop/pubspec.yaml +++ b/packages/desktop/pubspec.yaml @@ -8,6 +8,8 @@ resolution: workspace dependencies: flutter: sdk: flutter + client_youtubei: + path: ../youtubei listenbox_sync_engine: path: ../sync-engine window_manager: ^0.5.1 @@ -16,10 +18,9 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter - integration_test: - sdk: flutter flutter: uses-material-design: true assets: - assets/tray.png - - assets/tray.ico + - assets/tray-macos.png + - assets/tray-windows.ico diff --git a/packages/desktop/test/desktop_e2e_test.dart b/packages/desktop/test/desktop_e2e_test.dart new file mode 100644 index 0000000..5115c7b --- /dev/null +++ b/packages/desktop/test/desktop_e2e_test.dart @@ -0,0 +1,372 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:listenbox_desktop/desktop_host.dart'; +import 'package:listenbox_desktop/main.dart'; +import 'package:listenbox_sync_engine/sync_engine.dart'; +import 'package:tray_manager/tray_manager.dart'; +import 'package:window_manager/window_manager.dart'; + +void main() { + _LoopbackTestBinding(); + testWidgets('workspace uses its real client and isolated profile', ( + tester, + ) async { + tester.view.physicalSize = const Size(1080, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final service = (await tester.runAsync(_DesktopFixture.start))!; + final host = _HeadlessDesktopHost(); + final key = GlobalKey(); + try { + await tester.pumpWidget( + ListenboxDesktop(key: key, client: service.client, host: host), + ); + final state = key.currentState!; + expect(state.initialLoad, isNotNull); + await tester.runAsync(() => state.initialLoad!); + expect(state.episodesSettled, isNotNull); + await tester.runAsync(() => state.episodesSettled!.future); + await tester.pump(); + await tester.runAsync(() => service.artworkServed.future); + await tester.pumpAndSettle(); + expect(find.byKey(Key('show-${service.firstSlug}')), findsOneWidget); + expect(find.byKey(Key('show-${service.secondSlug}')), findsOneWidget); + expect(find.text('Ordinary podcast'), findsNothing); + expect(find.text('No episodes synced yet.'), findsOneWidget); + expect(service.requests, contains('GET /artwork.png')); + expect( + find.descendant( + of: find.byKey(Key('show-${service.firstSlug}')), + matching: find.byIcon(Icons.headphones), + ), + findsNothing, + ); + expect( + service.requests, + containsAll([ + 'GET /s/teams', + 'GET /s/shows', + 'GET /s/whoami', + 'GET /s/shows/${service.firstSlug}/episodes', + ]), + ); + + expect(host.menu?.items?.map((item) => item.label), [ + 'Open Listenbox', + 'Quit Listenbox', + ]); + state.onWindowClose(); + expect(state.windowHiddenSettled, isNotNull); + await state.windowHiddenSettled!; + expect(host.hidden, isTrue); + expect(state.mounted, isTrue); + expect(identical(state.client, service.client), isTrue); + final catalogRequestsBefore = service.requests + .where((request) => request == 'GET /s/shows') + .length; + await tester.runAsync(state.reload); + expect( + service.requests.where((request) => request == 'GET /s/shows').length, + greaterThan(catalogRequestsBefore), + ); + state.onTrayIconMouseDown(); + expect(host.popups, 1); + state.onTrayIconRightMouseDown(); + expect(host.popups, 2); + state.onTrayMenuItemClick(host.menu!.getMenuItem('show')!); + expect(state.windowOpenSettled, isNotNull); + await state.windowOpenSettled!; + expect(host.hidden, isFalse); + expect(host.opens, 1); + + await tester.tap(find.byKey(const Key('team-picker'))); + await tester.pump(); + await tester.tap(find.byKey(Key('team-${service.secondTeam}'))); + await tester.runAsync(() => state.episodesSettled!.future); + await tester.pump(); + expect(find.byKey(Key('show-${service.firstSlug}')), findsNothing); + expect(find.byKey(Key('show-${service.secondSlug}')), findsOneWidget); + expect(state.selectedShow?['slug'], service.secondSlug); + expect( + service.requests, + contains('GET /s/shows/${service.secondSlug}/episodes'), + ); + + String? opened; + state.browserOpener = (url) async { + opened = url; + }; + await tester.tap(find.byKey(const Key('open-playlist'))); + await tester.pump(); + expect(opened, service.sourceUrl); + + await tester.tap(find.byKey(const Key('new-import'))); + await tester.pump(); + await tester.enterText( + find.byKey(const Key('playlist-url')), + 'not a playlist', + ); + await tester.ensureVisible(find.byKey(const Key('start-import'))); + await tester.tap(find.byKey(const Key('start-import'))); + expect(state.importSettled, isNotNull); + await tester.runAsync(() => state.importSettled!.future); + await tester.pump(); + expect(find.byKey(const Key('error-notice')), findsOneWidget); + expect( + service.requests.where((request) => request.startsWith('POST ')), + isEmpty, + ); + expect(state.selectedShow?['slug'], service.secondSlug); + + expect(File(service.client.config.authPath).existsSync(), isTrue); + await tester.tap(find.byKey(const Key('account'))); + expect(state.logoutSettled, isNotNull); + await tester.runAsync(() => state.logoutSettled!.future); + await tester.pump(); + expect(service.client.hasCredentials, isFalse); + expect(File(service.client.config.authPath).existsSync(), isFalse); + expect(find.byKey(const Key('welcome-sign-in')), findsOneWidget); + expect(service.unexpected, isEmpty); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(service.close); + } + }, timeout: const Timeout(Duration(seconds: 30))); + + testWidgets('Windows tray routes clicks and Quit closes the client', ( + tester, + ) async { + final service = (await tester.runAsync(_DesktopFixture.start))!; + final host = _HeadlessDesktopHost(DesktopPlatform.windows); + final key = GlobalKey(); + try { + await tester.pumpWidget( + ListenboxDesktop(key: key, client: service.client, host: host), + ); + final state = key.currentState!; + expect(state.initialLoad, isNotNull); + await tester.runAsync(() => state.initialLoad!); + state.onTrayIconMouseDown(); + expect(state.windowOpenSettled, isNotNull); + await state.windowOpenSettled!; + expect(host.opens, 1); + state.onTrayIconRightMouseDown(); + expect(host.popups, 1); + expect(host.menu?.getMenuItem('quit'), isNotNull); + state.onTrayMenuItemClick(host.menu!.getMenuItem('quit')!); + await tester.runAsync(() => host.exited.future); + expect(host.trayDestroyed, isTrue); + expect(host.exitCode, 0); + expect(state.stopping, isTrue); + final requestsBefore = service.requests.length; + await expectLater(service.client.catalog(), throwsA(isA())); + expect(service.requests.length, requestsBefore); + expect(service.unexpected, isEmpty); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(service.close); + } + }, timeout: const Timeout(Duration(seconds: 30))); +} + +class _LoopbackTestBinding extends LiveTestWidgetsFlutterBinding { + // The fixture owns every URL used by this scenario, including artwork. + @override + bool get overrideHttpClient => false; +} + +class _HeadlessDesktopHost implements DesktopHost { + _HeadlessDesktopHost([this.platform = DesktopPlatform.macOS]); + + @override + final DesktopPlatform platform; + + Menu? menu; + bool hidden = false; + bool trayDestroyed = false; + int popups = 0; + int opens = 0; + int? exitCode; + final exited = Completer(); + + @override + void attach( + WindowListener windowListener, + TrayListener trayListener, + Future Function() requestQuit, + ) {} + + @override + void detach(WindowListener windowListener, TrayListener trayListener) {} + + @override + Future installTray(Menu menu) async { + this.menu = menu; + } + + @override + Future hideWindow() async { + hidden = true; + } + + @override + Future openWindow() async { + opens++; + hidden = false; + } + + @override + Future popUpTrayMenu() async { + popups++; + } + + @override + Future destroyTray() async { + trayDestroyed = true; + } + + @override + void exitProcess(int code) { + exitCode = code; + exited.complete(); + } +} + +/// HTTP and OS window/tray calls are substituted: widgets use the production +/// Client, generated API, profile files, and cancellation/shutdown paths. +class _DesktopFixture { + _DesktopFixture( + this.profile, + this.server, + this.firstTeam, + this.secondTeam, + this.firstSlug, + this.secondSlug, + this.credential, + ); + final Directory profile; + final HttpServer server; + final String firstTeam; + final String secondTeam; + final String firstSlug; + final String secondSlug; + final String credential; + final requests = []; + final unexpected = []; + final artworkServed = Completer(); + late final Client client; + final sourceUrl = 'https://www.youtube.com/playlist?list=PLdesktopFixture'; + String get artworkUrl => 'http://localhost:${server.port}/artwork.png'; + + static Future<_DesktopFixture> start() async { + final random = Random.secure(); + String suffix() => List.generate( + 8, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + final profile = await Directory.systemTemp.createTemp('listenbox-flutter-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final fixture = _DesktopFixture( + profile, + server, + 'team_${suffix()}', + 'team_${suffix()}', + 'first-${suffix()}', + 'second-${suffix()}', + 'desktop-${suffix()}', + ); + await File('${profile.path}/config.yaml').writeAsString( + 'api_origin: http://localhost:${server.port}\n' + 'dashboard_origin: http://localhost:${server.port}\n', + ); + final config = Config.loadIn(profile.path); + await File(config.authPath) + .writeAsString(jsonEncode({'api_key': fixture.credential})); + fixture.client = Client(config); + server.listen(fixture.respond); + return fixture; + } + + Map show( + String slug, + String team, + String title, { + bool imported = true, + }) => { + 'has_active_subscription': false, + 'id': 'shw_${team.substring(5)}', + 'language': 'en', + 'slug': slug, + 'source_kind': 'audio', + 'team_id': team, + 'title': title, + if (slug == firstSlug) 'image_url': artworkUrl, + 'youtube': imported + ? {'kind': 'import', 'source_url': sourceUrl} + : {'kind': 'none'}, + }; + + Future respond(HttpRequest request) async { + final route = '${request.method} ${request.uri.path}'; + requests.add(route); + await request.drain(); + if (route == 'GET /artwork.png') { + request.response.headers.contentType = ContentType('image', 'png'); + request.response.add( + base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNIaev/DwAFRAJ5mTYR+gAAAABJRU5ErkJggg==', + ), + ); + await request.response.close(); + if (!artworkServed.isCompleted) artworkServed.complete(); + return; + } + Object response; + if (request.headers.value(HttpHeaders.authorizationHeader) != + 'Bearer $credential') { + unexpected.add('Missing profile authorization on $route'); + request.response.statusCode = HttpStatus.unauthorized; + response = {'message': 'missing fixture authorization'}; + } else if (route == 'GET /s/teams') { + response = [ + {'id': firstTeam, 'name': 'First team'}, + {'id': secondTeam, 'name': 'Second team'}, + ]; + } else if (route == 'GET /s/shows') { + response = [ + show(firstSlug, firstTeam, 'First playlist'), + show(secondSlug, secondTeam, 'Second playlist'), + show('ordinary', firstTeam, 'Ordinary podcast', imported: false), + ]; + } else if (route == 'GET /s/whoami') { + response = { + 'id': 'apk_${firstTeam.substring(5)}', + 'email': 'desktop@example.test', + 'team_id': firstTeam, + 'scopes': ['team:read', 'show:read', 'show:create'], + }; + } else if (route == 'GET /s/shows/$firstSlug/episodes' || + route == 'GET /s/shows/$secondSlug/episodes') { + response = {'episodes': []}; + } else { + unexpected.add(route); + request.response.statusCode = HttpStatus.notFound; + response = {'message': 'unexpected fixture request'}; + } + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode(response)); + await request.response.close(); + } + + Future close() async { + await client.close(); + await server.close(force: true); + await profile.delete(recursive: true); + } +} diff --git a/packages/desktop/windows/.gitignore b/packages/desktop/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/packages/desktop/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/desktop/windows/CMakeLists.txt b/packages/desktop/windows/CMakeLists.txt new file mode 100644 index 0000000..bea80f9 --- /dev/null +++ b/packages/desktop/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(listenbox_desktop LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "listenbox_desktop") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/desktop/windows/flutter/CMakeLists.txt b/packages/desktop/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/packages/desktop/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/desktop/windows/flutter/generated_plugin_registrant.cc b/packages/desktop/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..f8f02a1 --- /dev/null +++ b/packages/desktop/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi")); + TrayManagerPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("TrayManagerPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); + WindowManagerPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("WindowManagerPlugin")); +} diff --git a/packages/desktop/windows/flutter/generated_plugin_registrant.h b/packages/desktop/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/packages/desktop/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/desktop/windows/flutter/generated_plugins.cmake b/packages/desktop/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..97653a6 --- /dev/null +++ b/packages/desktop/windows/flutter/generated_plugins.cmake @@ -0,0 +1,28 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + screen_retriever_windows + tray_manager + url_launcher_windows + window_manager +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + client_youtubei +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/desktop/windows/runner/CMakeLists.txt b/packages/desktop/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/packages/desktop/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/desktop/windows/runner/Runner.rc b/packages/desktop/windows/runner/Runner.rc new file mode 100644 index 0000000..295dc83 --- /dev/null +++ b/packages/desktop/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "app.listenbox" "\0" + VALUE "FileDescription", "listenbox_desktop" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "listenbox_desktop" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 app.listenbox. All rights reserved." "\0" + VALUE "OriginalFilename", "listenbox_desktop.exe" "\0" + VALUE "ProductName", "listenbox_desktop" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/desktop/windows/runner/flutter_window.cpp b/packages/desktop/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/packages/desktop/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/desktop/windows/runner/flutter_window.h b/packages/desktop/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/packages/desktop/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/desktop/windows/runner/main.cpp b/packages/desktop/windows/runner/main.cpp new file mode 100644 index 0000000..adc238f --- /dev/null +++ b/packages/desktop/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"listenbox_desktop", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/desktop/windows/runner/resource.h b/packages/desktop/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/packages/desktop/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/desktop/windows/runner/resources/app_icon.ico b/packages/desktop/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/packages/desktop/windows/runner/resources/app_icon.ico differ diff --git a/packages/desktop/windows/runner/runner.exe.manifest b/packages/desktop/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/packages/desktop/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/packages/desktop/windows/runner/utils.cpp b/packages/desktop/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/packages/desktop/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/desktop/windows/runner/utils.h b/packages/desktop/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/packages/desktop/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/desktop/windows/runner/win32_window.cpp b/packages/desktop/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/packages/desktop/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/desktop/windows/runner/win32_window.h b/packages/desktop/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/packages/desktop/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/sync-engine/hook/build.dart b/packages/sync-engine/hook/build.dart new file mode 100644 index 0000000..0cf5955 --- /dev/null +++ b/packages/sync-engine/hook/build.dart @@ -0,0 +1,181 @@ +import 'dart:io'; + +import 'package:archive/archive.dart'; +import 'package:code_assets/code_assets.dart'; +import 'package:crypto/crypto.dart'; +import 'package:hooks/hooks.dart'; + +import 'ffmpeg_artifacts.dart'; + +Future main(List args) async { + await build(args, (input, output) async { + if (!input.config.buildCodeAssets) return; + final target = + '${input.config.code.targetOS.name}-' + '${input.config.code.targetArchitecture.name}'; + final artifact = ffmpegArtifacts[target]; + if (artifact == null) { + throw UnsupportedError( + 'No pinned native FFmpegKit artifact for $target. ' + 'Publish and pin a compatible native bundle before building this target.', + ); + } + output.dependencies.add( + File.fromUri(input.packageRoot.resolve('hook/ffmpeg_artifacts.dart')).uri, + ); + final cache = Directory.fromUri( + input.outputDirectoryShared.resolve('ffmpegkit/'), + ); + await cache.create(recursive: true); + final archive = File.fromUri(cache.uri.resolve(artifact.sha256)); + await _verifiedArchive(archive, artifact); + + final bytes = await archive.readAsBytes(); + final zip = ZipDecoder().decodeBytes(bytes); + final entry = zip.find(artifact.entry); + if (entry == null || !entry.isFile || entry.size < 1000000) { + throw StateError('Pinned FFmpegKit archive lacks ${artifact.entry}'); + } + final outputPath = switch (input.config.code.targetOS) { + OS.macOS => 'ffmpegkit.framework/Versions/A/ffmpegkit', + OS.linux => 'libffmpegkit.so', + OS.windows => 'libffmpegkit.dll', + _ => throw UnsupportedError('Unsupported FFmpegKit target $target'), + }; + final library = File.fromUri(input.outputDirectory.resolve(outputPath)); + await library.parent.create(recursive: true); + await library.writeAsBytes(entry.readBytes()!, flush: true); + await entry.close(); + if (input.config.code.targetOS == OS.macOS) { + // Dart's native asset bundler rewrites a single Mach-O install name. + // The pinned archive is universal, so select the requested target slice. + final slice = input.config.code.targetArchitecture.name == 'arm64' + ? 'arm64' + : 'x86_64'; + final thinned = File('${library.path}.thin'); + final result = await Process.run('lipo', [ + library.path, + '-thin', + slice, + '-output', + thinned.path, + ]); + if (result.exitCode != 0) { + throw StateError('Could not select FFmpegKit $slice: ${result.stderr}'); + } + await thinned.rename(library.path); + final framework = Directory.fromUri( + input.outputDirectory.resolve('ffmpegkit.framework/'), + ); + final current = Link.fromUri(framework.uri.resolve('Versions/Current')); + final executable = Link.fromUri(framework.uri.resolve('ffmpegkit')); + if (await current.exists()) await current.delete(); + if (await executable.exists()) await executable.delete(); + await current.create('A'); + await executable.create('Versions/Current/ffmpegkit'); + final plist = File.fromUri( + framework.uri.resolve('Versions/A/Resources/Info.plist'), + ); + await plist.parent.create(recursive: true); + await plist.writeAsString(''' + +CFBundleExecutableffmpegkit +CFBundleIdentifierapp.listenbox.ffmpegkit +CFBundlePackageTypeFMWK +'''); + } + output.assets.code.add( + CodeAsset( + package: input.packageName, + name: 'ffmpegkit', + linkMode: DynamicLoadingBundled(), + file: library.uri, + ), + ); + + // The Windows ARM64 publication recipe places every non-system import + // beside the main DLL. Register those files individually so Dart and + // Flutter copy them next to libffmpegkit.dll, where the platform loader + // resolves its imports. The pinned macOS, Linux, and Windows x64 archives + // currently have no additional native libraries. + final nativeLibraryName = RegExp( + r'\.(?:dll|dylib|so(?:\.\d+)*)$', + caseSensitive: false, + ); + final directoryInArchive = artifact.entry.substring( + 0, + artifact.entry.lastIndexOf('/') + 1, + ); + final dependencies = zip.files.where( + (candidate) => + candidate.isFile && + candidate.name != artifact.entry && + nativeLibraryName.hasMatch(candidate.name), + ); + var dependencyIndex = 0; + for (final dependency in dependencies) { + if (!dependency.name.startsWith(directoryInArchive) || + dependency.name.substring(directoryInArchive.length).contains('/')) { + throw StateError( + 'Pinned FFmpegKit archive has a native dependency outside ' + 'the main library directory: ${dependency.name}', + ); + } + final name = dependency.name.substring(directoryInArchive.length); + if (dependency.size == 0) { + throw StateError('Pinned FFmpegKit dependency is empty: $name'); + } + final file = File.fromUri(input.outputDirectory.resolve(name)); + await file.writeAsBytes(dependency.readBytes()!, flush: true); + await dependency.close(); + output.assets.code.add( + CodeAsset( + package: input.packageName, + name: 'ffmpegkit-dependency-${dependencyIndex++}', + linkMode: DynamicLoadingBundled(), + file: file.uri, + ), + ); + } + }); +} + +Future _verifiedArchive(File archive, FfmpegArtifact artifact) async { + if (await archive.exists()) { + if (await _sha256(archive) == artifact.sha256) return; + await archive.delete(); + } + final partial = File('${archive.path}.partial'); + if (await partial.exists()) await partial.delete(); + final client = HttpClient(); + try { + final request = await client.getUrl(Uri.parse(artifact.url)); + request.headers.set( + HttpHeaders.userAgentHeader, + 'listenbox-client2-native-artifacts', + ); + final response = await request.close(); + if (response.statusCode != HttpStatus.ok) { + throw HttpException( + 'FFmpegKit download returned ${response.statusCode}', + uri: Uri.parse(artifact.url), + ); + } + final sink = partial.openWrite(); + await response.pipe(sink); + await sink.close(); + final actual = await _sha256(partial); + if (actual != artifact.sha256) { + throw StateError( + 'FFmpegKit SHA-256 mismatch: expected ${artifact.sha256}, got $actual', + ); + } + await partial.rename(archive.path); + } finally { + client.close(force: true); + if (await partial.exists()) await partial.delete(); + } +} + +Future _sha256(File file) async => + (await sha256.bind(file.openRead()).first).toString(); diff --git a/packages/sync-engine/hook/ffmpeg_artifacts.dart b/packages/sync-engine/hook/ffmpeg_artifacts.dart new file mode 100644 index 0000000..cbce9c8 --- /dev/null +++ b/packages/sync-engine/hook/ffmpeg_artifacts.dart @@ -0,0 +1,33 @@ +/// FFmpegKit Extended 0.11.1, FFmpeg 9.0.1, LGPL small base bundle. +/// Each SHA-256 is the release asset digest, independently checked by download. +/// Source: https://github.com/akashskypatel/ffmpeg-kit-builders/releases +class FfmpegArtifact { + const FfmpegArtifact(this.url, this.sha256, this.entry); + + final String url; + final String sha256; + final String entry; +} + +const ffmpegArtifacts = { + 'macos-arm64': FfmpegArtifact( + 'https://github.com/akashskypatel/ffmpeg-kit-builders/releases/download/v0.11.1-macos/bundle-base-macos-universal-small-lgpl.xcframework.zip', + '08c4639a4e8e3d5cb26d75cbf71b508017880b4d94b3cbde63c6cb571e66c910', + 'bundle-base-macos-universal-small-lgpl.xcframework/macos-arm64_x86_64/ffmpegkit.framework/ffmpegkit', + ), + 'macos-x64': FfmpegArtifact( + 'https://github.com/akashskypatel/ffmpeg-kit-builders/releases/download/v0.11.1-macos/bundle-base-macos-universal-small-lgpl.xcframework.zip', + '08c4639a4e8e3d5cb26d75cbf71b508017880b4d94b3cbde63c6cb571e66c910', + 'bundle-base-macos-universal-small-lgpl.xcframework/macos-arm64_x86_64/ffmpegkit.framework/ffmpegkit', + ), + 'linux-x64': FfmpegArtifact( + 'https://github.com/akashskypatel/ffmpeg-kit-builders/releases/download/v0.11.1-linux/bundle-base-linux-x86_64-shared-small-lgpl.zip', + '7a011ac0fe5b8e0a57a5dd1320560b1af2079bf78cf5a32114bde9e24e6070c7', + 'bundle-base-linux-x86_64-shared-small-lgpl/lib/libffmpegkit.so', + ), + 'windows-x64': FfmpegArtifact( + 'https://github.com/akashskypatel/ffmpeg-kit-builders/releases/download/v0.11.1-windows/bundle-base-windows-x86_64-shared-small-lgpl.zip', + '0a69736f01b8d2c1b49f12618da17fc2cc9134adfeaaaa58a2ba9e6693359a4b', + 'bundle-base-windows-x86_64-shared-small-lgpl/bin/libffmpegkit.dll', + ), +}; diff --git a/packages/sync-engine/lib/src/api.dart b/packages/sync-engine/lib/src/api.dart new file mode 100644 index 0000000..6f73b45 --- /dev/null +++ b/packages/sync-engine/lib/src/api.dart @@ -0,0 +1,259 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:http/io_client.dart'; + +import 'cancellation.dart'; +import 'config.dart'; +import 'publicapi/api.dart'; +import 'validation.dart'; + +class AuthenticationRequired implements Exception { + const AuthenticationRequired(); + @override + String toString() => 'Sign in to Listenbox to continue.'; +} + +class PaymentRequired implements Exception { + const PaymentRequired(this.message); + final String message; + @override + String toString() => 'HTTP 402: $message'; +} + +class ApiHttpException implements Exception { + const ApiHttpException(this.statusCode, this.message); + final int statusCode; + final String message; + @override + String toString() => 'HTTP $statusCode: $message'; +} + +/// Authenticates only requests to the configured API origin. Signed object and +/// media URLs must use [sendExternal] or [requestExternal]. +class Api { + Api._( + this.config, + this.cancel, + this.httpClient, + this._credential, + this.enableHttpLog, + ); + + final Config config; + final CancellationToken cancel; + final http.Client httpClient; + final bool enableHttpLog; + String? _credential; + int _credentialVersion = 0; + + String? get credential => _credential; + bool get hasCredential => _credential != null; + int get credentialVersion => _credentialVersion; + late final PublicApiClient publicClient = PublicApiClient( + baseUri: Uri.parse(config.apiOrigin), + send: send, + responseError: responseError, + readBody: readBounded, + ); + + static Future open( + Config config, { + CancellationToken? cancel, + http.Client? client, + bool? enableHttpLog, + }) async { + String? credential; + final file = File(config.authPath); + if (file.existsSync()) { + try { + if (file.lengthSync() <= 64 << 10) { + final decoded = jsonDecode(file.readAsStringSync()); + if (decoded is Map && + decoded.length == 1 && + decoded['api_key'] is String && + credentialValid(decoded['api_key'] as String)) { + credential = decoded['api_key'] as String; + } + } + } on FormatException { + // A damaged local credential is treated as signed out. + } on FileSystemException { + // The API boundary will report authentication required. + } + } + return Api._( + config, + cancel ?? CancellationToken(), + client ?? _createHttpClient(), + credential, + enableHttpLog ?? !const bool.fromEnvironment('dart.vm.product'), + ); + } + + void setCredential(String? value) { + if (value != null && !credentialValid(value)) { + throw const FormatException('invalid API credential'); + } + _credential = value; + _credentialVersion++; + } + + void close() => httpClient.close(); + + Future send(http.BaseRequest request) async { + final expected = Uri.parse(config.apiOrigin); + if (request.url.origin != expected.origin) { + throw const FormatException( + 'API request origin does not match configured API', + ); + } + request.headers.remove('Authorization'); + request.headers.remove('Cookie'); + if (_credential != null) { + request.headers['Authorization'] = 'Bearer $_credential'; + } + request.followRedirects = false; + return _send(request, apiRequest: true); + } + + Future sendExternal(http.BaseRequest request) { + request.headers.remove('Authorization'); + request.headers.remove('Cookie'); + return _send(request, apiRequest: false); + } + + /// Allows the YouTube session signature only on HTTPS YouTube hosts. + Future sendYouTube(http.BaseRequest request) { + final host = request.url.host.toLowerCase(); + if (request.url.scheme != 'https' || + (host != 'youtube.com' && !host.endsWith('.youtube.com'))) { + throw const FormatException( + 'YouTube authorization destination is invalid', + ); + } + request.followRedirects = false; + return _send(request, apiRequest: false); + } + + Future _send( + http.BaseRequest request, { + required bool apiRequest, + }) async { + cancel.throwIfCancelled(); + final watch = Stopwatch()..start(); + final diagnostic = apiRequest + ? '${request.method} ${config.apiOrigin}${request.url.path.startsWith('/cli/authorizations/') ? '/cli/authorizations/{code}/events' : request.url.path}' + : '${request.method} ${request.url.origin}'; + try { + final response = await cancel.race(httpClient.send(request)); + if (enableHttpLog) { + final trace = response.headers['x-trace-id']; + stderr.writeln( + 'HTTP $diagnostic -> ${response.statusCode} (${watch.elapsedMilliseconds}ms) trace_id=${trace != null && validTraceId(trace) ? trace : '-'}', + ); + } + final eventStream = + response.headers['content-type']?.startsWith('text/event-stream') ?? + false; + return http.StreamedResponse( + _controlledStream( + response.stream, + limit: apiRequest && !eventStream ? 4 << 20 : null, + ), + response.statusCode, + contentLength: response.contentLength, + request: response.request, + headers: response.headers, + isRedirect: response.isRedirect, + persistentConnection: response.persistentConnection, + reasonPhrase: response.reasonPhrase, + ); + } catch (error) { + if (enableHttpLog) { + stderr.writeln( + 'HTTP $diagnostic -> failed (${watch.elapsedMilliseconds}ms): ${error.runtimeType}', + ); + } + rethrow; + } + } + + Stream> _controlledStream( + Stream> source, { + int? limit, + }) async* { + final iterator = StreamIterator(source); + var received = 0; + try { + while (await cancel.race(iterator.moveNext())) { + final chunk = iterator.current; + if (limit != null && chunk.length > limit - received) { + throw FormatException('HTTP response exceeds $limit bytes'); + } + received += chunk.length; + yield chunk; + } + } finally { + await iterator.cancel(); + } + } + + Future responseError(http.StreamedResponse response) async { + final status = response.statusCode; + if (status == 401) return const AuthenticationRequired(); + final raw = await readBounded( + response, + 64 << 10, + ).catchError((_) => []); + String message; + try { + final decoded = jsonDecode(utf8.decode(raw)); + message = decoded is Map && decoded['message'] is String + ? decoded['message'] as String + : utf8.decode(raw, allowMalformed: true).trim(); + } catch (_) { + message = utf8.decode(raw, allowMalformed: true).trim(); + } + if (status == 402) return PaymentRequired(message); + return ApiHttpException( + status, + status == 403 ? 'permission denied' : redact(message), + ); + } + + Future> readBounded( + http.StreamedResponse response, + int limit, + ) async { + if (response.contentLength != null && response.contentLength! > limit) { + throw FormatException('HTTP response exceeds $limit bytes'); + } + final bytes = []; + final iterator = StreamIterator(response.stream); + try { + while (await cancel.race(iterator.moveNext())) { + final chunk = iterator.current; + if (chunk.length > limit - bytes.length) { + throw FormatException('HTTP response exceeds $limit bytes'); + } + bytes.addAll(chunk); + } + } finally { + await iterator.cancel(); + } + return bytes; + } +} + +http.Client _createHttpClient() { + final context = SecurityContext(withTrustedRoots: true); + final pem = Platform.environment['SSL_CERT_FILE']; + if (pem != null && pem.isNotEmpty) context.setTrustedCertificates(pem); + final client = HttpClient(context: context) + ..connectionTimeout = const Duration(seconds: 30) + ..findProxy = HttpClient.findProxyFromEnvironment; + return IOClient(client); +} diff --git a/packages/sync-engine/lib/src/audio.dart b/packages/sync-engine/lib/src/audio.dart new file mode 100644 index 0000000..76626fd --- /dev/null +++ b/packages/sync-engine/lib/src/audio.dart @@ -0,0 +1,122 @@ +import 'dart:io'; +import 'dart:math'; + +import 'native_media/ffmpeg_kit.dart'; + +/// Remuxes AAC or converts other audio (including Opus and Vorbis) to AAC. +/// The output is a new fast-start M4A file and is removed on any failure. +Future prepareM4a( + File input, + File output, { + bool Function()? isCancelled, + void Function(double fraction)? onProgress, +}) async { + if (input.absolute.path == output.absolute.path || await output.exists()) { + throw ArgumentError('Audio output must be a new file'); + } + if (isCancelled?.call() ?? false) throw const MediaOperationCancelled(); + try { + final sourceInfo = await probeMedia(input.path, isCancelled: isCancelled); + final codec = sourceInfo.firstStream('audio')?.codec ?? ''; + if (codec.isEmpty) throw NativeMediaException('Source has no audio stream'); + final duration = _validDuration(sourceInfo.duration); + final arguments = [ + '-hide_banner', + '-nostdin', + '-loglevel', + 'error', + '-y', + '-i', + input.path, + '-map', + '0:a:0', + '-vn', + '-sn', + '-dn', + '-c:a', + codec == 'aac' ? 'copy' : 'aac', + ]; + if (codec != 'aac') { + arguments.addAll(['-ar', '48000', '-ac', '2', '-b:a', '128k']); + } + arguments.addAll(['-movflags', '+faststart', '-f', 'ipod', output.path]); + await runMediaCommand( + arguments, + isCancelled: isCancelled, + expectedDurationSeconds: duration, + onProgress: onProgress, + ); + final bytes = await output.length(); + if (bytes == 0 || !await hasFastStart(output)) { + throw NativeMediaException('Prepared M4A is empty or lacks fast start'); + } + await preparedDuration(output); + return bytes; + } catch (_) { + if (await output.exists()) await output.delete(); + rethrow; + } +} + +/// Whole seconds used for remote admission, with the media contract's bounds. +Future preparedDuration(File file, {bool Function()? isCancelled}) async { + final seconds = await _probeDuration(file, isCancelled); + if (!seconds.isFinite || seconds < 0 || seconds > 604800) { + throw NativeMediaException('Invalid prepared media duration'); + } + final rounded = seconds.ceil(); + if (rounded < 1 || rounded > 604800) { + throw NativeMediaException('Invalid prepared media duration'); + } + return rounded; +} + +Future _probeDuration(File file, bool Function()? isCancelled) async { + final info = await probeMedia(file.path, isCancelled: isCancelled); + return _validDuration(info.duration); +} + +double _validDuration(double seconds) { + if (!seconds.isFinite || seconds <= 0) { + throw NativeMediaException('Invalid media duration: $seconds'); + } + return seconds; +} + +/// Checks the top-level ISO BMFF boxes; `moov` must precede `mdat`. +Future hasFastStart(File file) async { + final reader = await file.open(); + try { + final total = await reader.length(); + var offset = 0; + while (offset + 8 <= total) { + await reader.setPosition(offset); + final header = await reader.read(8); + if (header.length != 8) return false; + var size = 0; + for (var index = 0; index < 4; index++) { + size = (size << 8) | header[index]; + } + var headerSize = 8; + if (size == 1) { + final extended = await reader.read(8); + if (extended.length != 8) return false; + size = 0; + for (final byte in extended) { + size = (size << 8) | byte; + } + headerSize = 16; + } else if (size == 0) { + size = total - offset; + } + if (size < headerSize || size > total - offset) return false; + final kind = String.fromCharCodes(header.sublist(4, 8)); + if (kind == 'moov') return true; + if (kind == 'mdat') return false; + offset += max(size, headerSize); + } + return false; + } finally { + await reader.close(); + } +} diff --git a/packages/sync-engine/lib/src/auth.dart b/packages/sync-engine/lib/src/auth.dart new file mode 100644 index 0000000..8aa8088 --- /dev/null +++ b/packages/sync-engine/lib/src/auth.dart @@ -0,0 +1,136 @@ +import 'dart:async'; + +import 'api.dart'; +import 'config.dart'; +import 'events.dart'; +import 'publicapi/models.dart' as p; +import 'validation.dart'; + +class Auth { + static const scopes = [ + p.ApiKeyScope.teamRead, + p.ApiKeyScope.teamManage, + p.ApiKeyScope.showRead, + p.ApiKeyScope.showCreate, + p.ApiKeyScope.showUpdate, + p.ApiKeyScope.episodeCreate, + p.ApiKeyScope.episodeDelete, + p.ApiKeyScope.episodeUpdate, + p.ApiKeyScope.episodePublish, + ]; + + static Future login( + Api api, { + String client = 'cli', + required FutureOr Function(Uri url) openBrowser, + }) async { + if (client != 'cli' && client != 'desktop') { + throw const FormatException('invalid authorization client'); + } + final body = p.CreateCLIAuthorization( + client: client == 'cli' + ? p.AuthorizationClient.cli + : p.AuthorizationClient.desktop, + scopes: scopes, + ); + p.CreatedCLIAuthorization pending; + try { + pending = await api.publicClient.createCLIAuthorization(body: body); + } on AuthenticationRequired { + if (!api.hasCredential) rethrow; + api.setCredential(null); + pending = await api.publicClient.createCLIAuthorization(body: body); + } + final version = api.credentialVersion; + if (!credentialValid(pending.credential)) { + throw const FormatException('invalid pending credential'); + } + final verifiedUrl = Uri.parse(pending.verificationUrl); + if ((verifiedUrl.scheme != 'http' && verifiedUrl.scheme != 'https') || + !verifiedUrl.hasAuthority || + verifiedUrl.host.isEmpty || + verifiedUrl.userInfo.isNotEmpty || + verifiedUrl.hasFragment) { + throw const FormatException('invalid verification URL'); + } + final dashboard = Uri.parse(api.config.dashboardOrigin); + final verification = Uri( + scheme: dashboard.scheme, + host: dashboard.host, + port: dashboard.hasPort ? dashboard.port : null, + path: verifiedUrl.path, + query: verifiedUrl.hasQuery ? verifiedUrl.query : null, + ); + await openBrowser(verification); + final stream = await EventStream.fromResponse( + api, + await api.publicClient.cliAuthorizationEvents(code: pending.code), + ); + try { + final event = await stream.next(); + switch (jsonString(event, 'type')) { + case 'cli.authorization.approved': + final approved = p.CLIAuthorizationApprovedEvent.fromJson(event); + if (api.credentialVersion != version) { + throw StateError('authorization changed while signing in'); + } + api.setCredential(pending.credential); + final pendingVersion = api.credentialVersion; + try { + final identity = await api.publicClient.whoami(); + if (api.credentialVersion != pendingVersion) { + throw StateError('authorization changed while signing in'); + } + if (identity.teamId != approved.teamId) { + throw const FormatException( + 'approved credential team does not match approved team', + ); + } + for (final scope in scopes) { + if (!identity.scopes.contains(scope)) { + throw FormatException( + 'approved credential missing scope $scope', + ); + } + } + if (api.credentialVersion != pendingVersion) { + throw StateError('authorization changed while signing in'); + } + writePrivateJson(api.config.authPath, { + 'api_key': pending.credential, + }); + } catch (_) { + if (api.credentialVersion == pendingVersion) + api.setCredential(null); + rethrow; + } + case 'cli.authorization.denied': + p.CLIAuthorizationDeniedEvent.fromJson(event); + throw const FormatException('Authorization was denied'); + case 'cli.authorization.expired': + p.CLIAuthorizationExpiredEvent.fromJson(event); + throw const FormatException('Authorization expired'); + default: + throw FormatException( + 'unexpected authorization event ${event['type']}', + ); + } + } finally { + await stream.close(); + } + } + + /// Call after stopping admission and awaiting all application-owned work. + static Future logout(Api api) async { + api.setCredential(null); + removePrivateFile(api.config.authPath); + } + + static Future status(Api api) async { + final identity = await api.publicClient.whoami(); + final email = identity.email.trim(); + if (email.isEmpty) throw const FormatException('identity email is empty'); + final name = identity.name?.trim().split(RegExp(r'\s+')).join(' ') ?? ''; + return name.isEmpty ? 'Logged in as $email' : 'Logged in as $name <$email>'; + } +} diff --git a/packages/sync-engine/lib/src/cancellation.dart b/packages/sync-engine/lib/src/cancellation.dart new file mode 100644 index 0000000..7955002 --- /dev/null +++ b/packages/sync-engine/lib/src/cancellation.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +/// Cooperative cancellation for a tree of application-owned async operations. +class CancellationToken { + CancellationToken._(this._parent) { + if (_parent != null) { + _parent._children.add(this); + if (_parent.isCancelled) cancel(); + } + } + + factory CancellationToken() => CancellationToken._(null); + + final CancellationToken? _parent; + final Set _children = {}; + final Completer _cancelled = Completer(); + + bool get isCancelled => _cancelled.isCompleted; + Future get whenCancelled => _cancelled.future; + CancellationToken child() => CancellationToken._(this); + + void cancel() { + if (isCancelled) return; + _cancelled.complete(); + for (final child in _children.toList()) { + child.cancel(); + } + _children.clear(); + _parent?._children.remove(this); + } + + void throwIfCancelled() { + if (isCancelled) throw const OperationCancelled(); + } + + Future race(Future work) async { + throwIfCancelled(); + return Future.any([ + work, + whenCancelled.then((_) => throw const OperationCancelled()), + ]); + } +} + +class OperationCancelled implements Exception { + const OperationCancelled(); + @override + String toString() => + 'operation interrupted; resumable source upload state preserved'; +} diff --git a/packages/sync-engine/lib/src/client.dart b/packages/sync-engine/lib/src/client.dart new file mode 100644 index 0000000..9777d8f --- /dev/null +++ b/packages/sync-engine/lib/src/client.dart @@ -0,0 +1,214 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'api.dart'; +import 'auth.dart'; +import 'cancellation.dart'; +import 'config.dart'; +import 'cookies.dart'; +import 'downloads.dart'; +import 'episodes.dart' as episode_upload; +import 'sync.dart' as synchronization; +import 'validation.dart' as validation; +import 'youtube.dart' as youtube; + +class Catalog { + const Catalog({ + required this.teams, + required this.importTeam, + required this.shows, + }); + final List> teams; + final String? importTeam; + final List> shows; +} + +class Client { + Client(this.config, {this.enableHttpLog}) + : cookieJar = CookieJar(config.directory), + _engine = synchronization.Engine(cookies: CookieJar(config.directory)); + final Config config; + final bool? enableHttpLog; + final CookieJar cookieJar; + final synchronization.Engine _engine; + final Set _tokens = {}; + final Set> _operations = {}; + bool _closed = false; + + DownloadManager get downloads => _engine.downloads; + bool get hasCredentials { + final file = File(config.authPath); + if (!file.existsSync()) return false; + try { + final raw = jsonDecode(file.readAsStringSync()); + return raw is Map && + raw.length == 1 && + raw['api_key'] is String && + validation.credentialValid(raw['api_key'] as String); + } catch (_) { + return false; + } + } + + String upgradeUrl(String team) => config.upgradeUrl(team); + String showUrl(Map show) => + config.showUrl(show['team_id'] as String, show['id'] as String); + + Future _run( + CancellationToken? requested, + Future Function(Api) action, + ) async { + if (_closed) throw StateError('Client is closed'); + final token = requested?.child() ?? CancellationToken(); + _tokens.add(token); + final completed = Completer(); + _operations.add(completed.future); + Api? api; + try { + api = await Api.open(config, cancel: token, enableHttpLog: enableHttpLog); + return await action(api); + } finally { + api?.close(); + _tokens.remove(token); + token.cancel(); + completed.complete(); + _operations.remove(completed.future); + } + } + + Future catalog({CancellationToken? cancel}) => _run(cancel, ( + api, + ) async { + if (!api.hasCredential) throw const AuthenticationRequired(); + final teams = await api.publicClient.listClientTeams(); + final shows = await api.publicClient.listShows(); + final account = await api.publicClient.whoami(); + return Catalog( + teams: [for (final team in teams) team.toJson().cast()], + importTeam: account.teamId, + shows: [for (final show in shows) show.toJson().cast()], + ); + }); + + Future> episodes( + String slug, { + String? cursor, + CancellationToken? cancel, + }) => _run(cancel, (api) async { + if (!api.hasCredential) throw const AuthenticationRequired(); + final value = await api.publicClient.listEpisodes( + showSlug: slug, + limit: 50, + cursor: cursor, + ); + return value.toJson().cast(); + }); + + Future login( + FutureOr Function(Uri) openBrowser, { + CancellationToken? cancel, + String client = 'desktop', + }) => _run( + cancel, + (api) => Auth.login(api, client: client, openBrowser: openBrowser), + ); + + Future logout() async { + for (final token in _tokens.toList()) token.cancel(); + await Future.wait(_operations.toList()); + await _engine.downloads.drain(); + final api = await Api.open(config); + try { + await Auth.logout(api); + } finally { + api.close(); + } + downloads.clear(); + } + + Future<({Map show, synchronization.Report report})> + importPlaylist( + String source, + String kind, { + String? requestedSlug, + String? teamId, + void Function(Map)? onCreated, + CancellationToken? cancel, + }) => _run( + cancel, + (api) => youtube.importPlaylist( + api, + _engine, + source, + kind, + requestedSlug: requestedSlug, + onCreated: onCreated, + ), + ); + + Future sync( + String slug, { + CancellationToken? cancel, + void Function(synchronization.Report)? onReport, + }) => _run(cancel, (api) async { + final result = await _engine.once(api, slug); + onReport?.call(result); + return result; + }); + + Stream watch( + String slug, { + CancellationToken? cancel, + }) async* { + if (_closed) throw StateError('Client is closed'); + final token = cancel?.child() ?? CancellationToken(); + _tokens.add(token); + try { + while (!token.isCancelled) { + yield await sync(slug, cancel: token); + if (!await nextScan(token)) break; + } + } finally { + _tokens.remove(token); + token.cancel(); + } + } + + Future nextScan(CancellationToken cancel) => _engine.nextScan(cancel); + + Future> setOrder( + String slug, + List episodeIds, { + CancellationToken? cancel, + }) => _run(cancel, (api) => synchronization.setOrder(api, slug, episodeIds)); + + Future createEpisode( + String show, + String title, + File file, { + String? description, + String publication = 'publish', + CancellationToken? cancel, + void Function(String)? onProgress, + }) => _run( + cancel, + (api) => episode_upload.createEpisode( + api, + show: show, + title: title, + file: file, + description: description, + publication: publication, + onProgress: onProgress, + ), + ); + + Future close() async { + if (_closed) return; + _closed = true; + for (final token in _tokens.toList()) token.cancel(); + await Future.wait(_operations.toList()); + await _engine.close(); + } +} diff --git a/packages/sync-engine/lib/src/config.dart b/packages/sync-engine/lib/src/config.dart new file mode 100644 index 0000000..212c6f0 --- /dev/null +++ b/packages/sync-engine/lib/src/config.dart @@ -0,0 +1,278 @@ +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:math'; + +import 'package:ffi/ffi.dart'; +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; + +import 'validation.dart'; + +/// The whole client profile is shared by CLI and desktop. +class Config { + const Config._({ + required this.directory, + required this.apiOrigin, + required this.dashboardOrigin, + }); + + final String directory; + final String apiOrigin; + final String dashboardOrigin; + + String get configPath => p.join(directory, 'config.yaml'); + String get authPath => p.join(directory, 'auth.json'); + String get sqlitePath => p.join(directory, 'sync.sqlite'); + String get downloadDirectory => p.join(directory, 'downloads'); + + static Config load({ + String? explicitPath, + String? profileDirectory, + bool? debugProfile, + }) { + final directory = _profileDirectory(profileDirectory, debugProfile); + return _loadIn(directory, explicitPath: explicitPath); + } + + static Config _loadIn(String directory, {String? explicitPath}) { + final path = explicitPath ?? p.join(directory, 'config.yaml'); + if (path.isEmpty) + throw const FormatException('explicit config path is empty'); + Map values; + final file = File(path); + if (!file.existsSync() && explicitPath == null) { + values = { + 'api_origin': 'https://v1.listenbox.app', + 'dashboard_origin': 'https://web.listenbox.app', + }; + } else { + String contents; + try { + contents = file.readAsStringSync(); + } on FileSystemException catch (error) { + throw FormatException('load client config $path: ${error.message}'); + } + try { + final parsed = loadYaml(contents); + if (parsed is! YamlMap) + throw const FormatException('config must be a map'); + values = {}; + for (final key in parsed.keys) { + if (key is! String || + !{'api_origin', 'dashboard_origin'}.contains(key)) { + throw FormatException('unknown field $key'); + } + final value = parsed[key]; + if (value is! String) throw FormatException('$key must be a string'); + values[key] = value; + } + if (values.length != 2) { + throw const FormatException( + 'api_origin and dashboard_origin are required', + ); + } + } on YamlException catch (error) { + throw FormatException('decode client config $path: $error'); + } on FormatException catch (error) { + if (error.message.startsWith('unknown field')) rethrow; + throw FormatException('decode client config $path: ${error.message}'); + } + } + return Config._( + directory: directory, + apiOrigin: _origin(values['api_origin'] as String, 'api_origin'), + dashboardOrigin: _origin( + values['dashboard_origin'] as String, + 'dashboard_origin', + ), + ); + } + + static Config loadIn(String directory, {String? explicitPath}) => + _loadIn(directory, explicitPath: explicitPath); + + String upgradeUrl(String team) { + if (!validId(team, 'team_')) { + throw const FormatException('invalid upgrade team identifier'); + } + return '$dashboardOrigin/$team/upgrade'; + } + + String showUrl(String team, String show) { + if (!validId(team, 'team_') || !validId(show, 'shw_')) { + throw const FormatException('invalid show management identifiers'); + } + return '$dashboardOrigin/$team/shows/$show'; + } +} + +String _profileDirectory(String? explicit, bool? debugProfile) { + final override = Platform.environment['LISTENBOX_PROFILE_DIR']; + if (override != null) { + if (override.isEmpty) { + throw const FormatException('LISTENBOX_PROFILE_DIR is empty'); + } + return override; + } + if (explicit != null) { + if (explicit.isEmpty) + throw const FormatException('profile directory is empty'); + return explicit; + } + final home = + Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; + if (home == null || home.isEmpty) { + throw const FormatException('resolve user home directory'); + } + final debug = debugProfile ?? !const bool.fromEnvironment('dart.vm.product'); + if (debug) return p.join(home, '.cache', 'listenbox', 'dev'); + if (Platform.isMacOS) { + return p.join(home, 'Library', 'Application Support', 'Listenbox'); + } + if (Platform.isWindows) { + final local = Platform.environment['LOCALAPPDATA']; + if (local == null || local.isEmpty) { + throw const FormatException('resolve user application data directory'); + } + return p.join(local, 'Listenbox'); + } + final xdg = Platform.environment['XDG_DATA_HOME']; + return p.join( + xdg == null || xdg.isEmpty ? p.join(home, '.local', 'share') : xdg, + 'listenbox', + ); +} + +String _origin(String raw, String field) { + try { + final value = raw.trim(); + final separator = value.indexOf('://'); + if (separator < 0) throw const FormatException('missing HTTP(S) authority'); + final authorityAndPath = value.substring(separator + 3); + if (authorityAndPath.isEmpty || + authorityAndPath.startsWith('/') || + authorityAndPath.contains(RegExp(r'[@\\?#]'))) { + throw const FormatException( + 'origin must contain only a host and optional port', + ); + } + final slash = authorityAndPath.indexOf('/'); + if (slash >= 0 && slash != authorityAndPath.length - 1) { + throw const FormatException('origin must not include a path'); + } + final authority = slash < 0 + ? authorityAndPath + : authorityAndPath.substring(0, slash); + // Uri.parse percent-encodes spaces in an authority, so inspect the raw + // authority before parsing rather than accepting a normalized host. + if (authority.contains('%') || + authority.codeUnits.any((code) => code <= 0x20 || code == 0x7f) || + RegExp(r'\s').hasMatch(authority)) { + throw const FormatException('invalid origin authority'); + } + final uri = Uri.parse(value); + if ((uri.scheme != 'http' && uri.scheme != 'https') || + !uri.hasAuthority || + uri.host.isEmpty || + uri.userInfo.isNotEmpty || + uri.pathSegments.where((s) => s.isNotEmpty).isNotEmpty || + uri.hasQuery || + uri.hasFragment || + uri.port < 0 || + uri.port > 65535) { + throw const FormatException('invalid origin URL'); + } + return uri.origin; + } on FormatException catch (error) { + throw FormatException('validate $field: ${error.message}'); + } +} + +/// Atomically replaces a private profile file after flushing its contents. +void writePrivateJson(String path, Object value) { + final directory = p.dirname(path); + ensurePrivateDirectory(directory); + final random = Random.secure(); + final suffix = List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + final temporary = '$path.$suffix.tmp'; + final file = File(temporary); + try { + file.createSync(exclusive: true); + _setMode(temporary, 0x180); // 0600 + final writer = file.openSync(mode: FileMode.writeOnly); + try { + writer.writeStringSync( + '${const JsonEncoder.withIndent(' ').convert(value)}\n', + ); + writer.flushSync(); + } finally { + writer.closeSync(); + } + file.renameSync(path); + _syncDirectory(directory); + } finally { + if (file.existsSync()) file.deleteSync(); + } +} + +void ensurePrivateDirectory(String path) { + Directory(path).createSync(recursive: true); + _setMode(path, 0x1c0); // 0700 +} + +void setPrivateFileMode(String path) => _setMode(path, 0x180); // 0600 + +typedef _ChmodNative = Int32 Function(Pointer, Int32); +typedef _ChmodDart = int Function(Pointer, int); +typedef _OpenNative = Int32 Function(Pointer, Int32); +typedef _OpenDart = int Function(Pointer, int); +typedef _FdNative = Int32 Function(Int32); +typedef _FdDart = int Function(int); + +final DynamicLibrary _process = DynamicLibrary.process(); +final _ChmodDart _chmod = _process.lookupFunction<_ChmodNative, _ChmodDart>( + 'chmod', +); +final _OpenDart _open = _process.lookupFunction<_OpenNative, _OpenDart>('open'); +final _FdDart _fsync = _process.lookupFunction<_FdNative, _FdDart>('fsync'); +final _FdDart _close = _process.lookupFunction<_FdNative, _FdDart>('close'); + +void _setMode(String path, int mode) { + if (Platform.isWindows) return; + final native = path.toNativeUtf8(); + try { + if (_chmod(native, mode) != 0) { + throw FileSystemException('set private file permissions', path); + } + } finally { + calloc.free(native); + } +} + +void _syncDirectory(String path) { + if (Platform.isWindows) return; + final native = path.toNativeUtf8(); + try { + final fd = _open(native, 0); + if (fd < 0) throw FileSystemException('open private directory', path); + try { + if (_fsync(fd) != 0) + throw FileSystemException('flush private directory', path); + } finally { + _close(fd); + } + } finally { + calloc.free(native); + } +} + +void removePrivateFile(String path) { + final file = File(path); + if (!file.existsSync()) return; + file.deleteSync(); + _syncDirectory(p.dirname(path)); +} diff --git a/packages/sync-engine/lib/src/cookies.dart b/packages/sync-engine/lib/src/cookies.dart new file mode 100644 index 0000000..fc1a3e6 --- /dev/null +++ b/packages/sync-engine/lib/src/cookies.dart @@ -0,0 +1,497 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:path/path.dart' as p; + +import 'config.dart'; + +const youtubeCookieGuideUrl = + 'https://listenbox.app/guides/import-youtube-as-a-podcast/#when-youtube-asks-you-to-sign-in'; +const _maxBytes = 1 << 20; +const _maxCookies = 1024; + +class SignInRequired implements Exception { + const SignInRequired([this.reason]); + final String? reason; + + @override + String toString() { + final supplied = reason?.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), ' ').trim(); + final detail = supplied == null || supplied.isEmpty + ? 'YouTube needs a signed-in session.' + : supplied.length > 256 + ? supplied.substring(0, 256) + : supplied; + final sentence = detail.endsWith('.') ? detail : '$detail.'; + return '$sentence Open Settings → YouTube to paste fresh cookies, or run listenbox youtube-cookies import , then sync again.'; + } +} + +class _Cookie { + _Cookie({ + required this.domain, + required this.hostOnly, + required this.path, + required this.secure, + required this.httpOnly, + required this.expires, + required this.name, + required this.value, + required this.revision, + }); + + final String domain; + final bool hostOnly; + final String path; + final bool secure; + final bool httpOnly; + final int? expires; + final String name; + final String value; + final String revision; + + String get key => '$domain\u0000$path\u0000$name'; + bool get expired => + expires != null && + expires! <= DateTime.now().millisecondsSinceEpoch ~/ 1000; + + bool matches(Uri url) { + if (secure && url.scheme != 'https') return false; + final host = url.host.toLowerCase(); + if (hostOnly + ? host != domain + : (host != domain && !host.endsWith('.$domain'))) { + return false; + } + final targetPath = url.path.isEmpty ? '/' : url.path; + return targetPath == path || + (targetPath.startsWith(path) && + (path.endsWith('/') || + (targetPath.length > path.length && + targetPath[path.length] == '/'))); + } + + Map toJson() => { + 'domain': domain, + 'host_only': hostOnly, + 'path': path, + 'secure': secure, + 'http_only': httpOnly, + 'expires': expires, + 'name': name, + 'value': value, + 'revision': revision, + }; + + factory _Cookie.fromJson(Object? value) { + if (value is! Map) + throw const FormatException('invalid cookie'); + final domain = value['domain']; + final hostOnly = value['host_only']; + final path = value['path']; + final secure = value['secure']; + final httpOnly = value['http_only']; + final expires = value['expires']; + final name = value['name']; + final cookieValue = value['value']; + final revision = value['revision']; + if (domain is! String || + !_validDomain(domain) || + hostOnly is! bool || + path is! String || + !_validPath(path) || + secure is! bool || + httpOnly is! bool || + (expires != null && (expires is! int || expires < 0)) || + name is! String || + cookieValue is! String || + !_validPair(name, cookieValue) || + revision is! String || + revision.isEmpty || + !_validPrefixes(name, secure, hostOnly, path)) { + throw const FormatException('invalid cookie'); + } + return _Cookie( + domain: domain, + hostOnly: hostOnly, + path: path, + secure: secure, + httpOnly: httpOnly, + expires: expires as int?, + name: name, + value: cookieValue, + revision: revision, + ); + } +} + +class CookieSnapshot { + CookieSnapshot._(this.generation, this.enabled, this._entries); + final String generation; + final bool enabled; + final List<_Cookie> _entries; + + String headerFor(Uri url) { + if (!enabled || + url.scheme != 'https' || + !_youtubeDomain(url.host.toLowerCase())) { + return ''; + } + final matches = _entries + .where((entry) => !entry.expired && entry.matches(url)) + .toList(); + matches.sort((a, b) { + final pathOrder = b.path.length.compareTo(a.path.length); + return pathOrder == 0 ? a.name.compareTo(b.name) : pathOrder; + }); + return matches.map((entry) => '${entry.name}=${entry.value}').join('; '); + } + + String? _revision(String key) { + for (final entry in _entries) { + if (entry.key == key) return entry.revision; + } + return null; + } + + Map toJson() => { + 'generation': generation, + 'enabled': enabled, + 'entries': _entries.map((entry) => entry.toJson()).toList(), + }; + + factory CookieSnapshot.fromJson(Object? value) { + if (value is! Map || + value['generation'] is! String || + value['enabled'] is! bool || + value['entries'] is! List) { + throw const FormatException('invalid cookie snapshot'); + } + final raw = value['entries'] as List; + if (raw.length > _maxCookies) + throw const FormatException('too many cookies'); + final entries = raw.map(_Cookie.fromJson).toList(); + if (entries.map((entry) => entry.key).toSet().length != entries.length) { + throw const FormatException('duplicate saved cookies'); + } + return CookieSnapshot._( + value['generation'] as String, + value['enabled'] as bool, + entries, + ); + } +} + +/// Shared cross-process cookie store. Readers observe an atomic snapshot; +/// writers compare revisions while holding an OS file lock. +class CookieJar { + CookieJar(String profileDirectory) + : directory = p.join(profileDirectory, 'youtube-cookies'); + + final String directory; + String get path => p.join(directory, 'jar.json'); + String get _lockPath => p.join(directory, 'write.lock'); + + Future snapshot() async { + final file = File(path); + if (!await file.exists()) return CookieSnapshot._('', false, []); + try { + if (await file.length() > _maxBytes) + throw const FormatException('oversized jar'); + return CookieSnapshot.fromJson(jsonDecode(await file.readAsString())); + } catch (_) { + throw const FormatException( + 'Saved YouTube cookies are invalid. Replace them in Settings or with youtube-cookies import.', + ); + } + } + + Future isEnabled() async => (await snapshot()).enabled; + + Future importFile(String sourcePath) async { + final file = File(sourcePath); + if (await file.length() > _maxBytes) { + throw const FormatException('Cookie file is too large (maximum 1 MiB)'); + } + final bytes = await file.readAsBytes(); + String text; + try { + text = utf8.decode(bytes); + } on FormatException { + throw const FormatException('Cookie export must be UTF-8 text'); + } + await importText(text); + } + + Future importText(String text) async { + final entries = _parseNetscape(text); + final saved = CookieSnapshot._(_revision(), true, entries); + await _withLock(() async => _save(saved)); + } + + Future remove() async { + await _withLock( + () async => _save(CookieSnapshot._(_revision(), false, [])), + ); + } + + Future update( + CookieSnapshot base, + Uri url, + Iterable setCookieHeaders, + ) async { + if (!base.enabled || + url.scheme != 'https' || + !_youtubeDomain(url.host.toLowerCase())) + return; + final updates = {}; + var received = 0; + for (final folded in setCookieHeaders) { + // package:http folds repeated response headers with commas. A cookie + // value cannot contain a comma; an Expires date can, but is not followed + // by a cookie-name and equals sign. + for (final header in folded.split( + RegExp(r',\s*(?=[A-Za-z0-9!#\$%&\x27*+.^_`|~-]+=)'), + )) { + if (++received > _maxCookies) break; + if (header.length > 16 << 10) continue; + final cookie = _parseSetCookie(url, header); + if (cookie != null) updates[cookie.key] = cookie; + } + if (received > _maxCookies) break; + } + if (updates.isEmpty) return; + await _withLock(() async { + final current = await snapshot(); + if (!current.enabled || current.generation != base.generation) return; + final entries = current._entries.toList(); + var changed = false; + for (final cookie in updates.values) { + if (current._revision(cookie.key) != base._revision(cookie.key)) + continue; + final index = entries.indexWhere((entry) => entry.key == cookie.key); + if (index >= 0) { + entries[index] = cookie; + } else { + if (entries.length >= _maxCookies) { + throw const FormatException( + 'YouTube cookie jar is full; import a fresh export', + ); + } + entries.add(cookie); + } + changed = true; + } + if (changed) + await _save(CookieSnapshot._(current.generation, true, entries)); + }); + } + + Future _save(CookieSnapshot saved) async { + final bytes = utf8.encode(jsonEncode(saved.toJson())); + if (bytes.length >= _maxBytes) { + throw const FormatException( + 'YouTube cookie jar is too large; export a smaller YouTube session', + ); + } + writePrivateJson(path, saved.toJson()); + } + + Future _withLock(Future Function() operation) async { + ensurePrivateDirectory(directory); + final lock = File(_lockPath); + if (!lock.existsSync()) { + lock.createSync(); + setPrivateFileMode(_lockPath); + } + final handle = await lock.open(mode: FileMode.append); + try { + await handle.lock(FileLock.exclusive); + return await operation(); + } finally { + await handle.unlock(); + await handle.close(); + } + } +} + +List<_Cookie> _parseNetscape(String input) { + if (utf8.encode(input).length > _maxBytes) { + throw const FormatException('Cookie export is too large (maximum 1 MiB)'); + } + final lines = input.replaceFirst('\uFEFF', '').split(RegExp(r'\r?\n')); + if (lines.isEmpty || + !{ + '# Netscape HTTP Cookie File', + '# HTTP Cookie File', + }.contains(lines.first.trim())) { + throw const FormatException( + 'Paste the entire Netscape cookies.txt export, including its header. JSON is not supported.', + ); + } + final entries = <_Cookie>[]; + final keys = {}; + for (var index = 1; index < lines.length; index++) { + var line = lines[index]; + var httpOnly = false; + if (line.startsWith('#HttpOnly_')) { + line = line.substring('#HttpOnly_'.length); + httpOnly = true; + } else if (line.startsWith('#') || line.trim().isEmpty) { + continue; + } + final fields = line.split('\t'); + FormatException invalid() => FormatException( + 'Invalid cookies.txt row ${index + 1}. Export cookies in Netscape format again.', + ); + if (fields.length != 7) throw invalid(); + final host = fields[0].replaceFirst(RegExp(r'^\.'), '').toLowerCase(); + if (!_youtubeDomain(host)) continue; + final subdomains = fields[1]; + final cookiePath = fields[2]; + final secure = fields[3]; + final expires = int.tryParse(fields[4]); + final name = fields[5]; + final value = fields[6]; + if (!{'TRUE', 'FALSE'}.contains(subdomains) || + !{'TRUE', 'FALSE'}.contains(secure) || + !_validPath(cookiePath) || + !_validPair(name, value) || + expires == null || + expires < 0 || + !_validDomain(host) || + !_validPrefixes( + name, + secure == 'TRUE', + subdomains == 'FALSE', + cookiePath, + )) { + throw invalid(); + } + if (expires != 0 && + expires <= DateTime.now().millisecondsSinceEpoch ~/ 1000) + continue; + final cookie = _Cookie( + domain: host, + hostOnly: subdomains == 'FALSE', + path: cookiePath, + secure: secure == 'TRUE', + httpOnly: httpOnly, + expires: expires == 0 ? null : expires, + name: name, + value: value, + revision: _revision(), + ); + if (!keys.add(cookie.key)) { + throw FormatException( + 'Duplicate cookie in row ${index + 1}; export cookies again', + ); + } + entries.add(cookie); + if (entries.length > _maxCookies) { + throw const FormatException('Too many YouTube cookies in this export'); + } + } + if (entries.isEmpty) { + throw const FormatException( + 'No unexpired YouTube cookies found. Export a fresh YouTube session.', + ); + } + return entries; +} + +_Cookie? _parseSetCookie(Uri url, String header) { + final parts = header.split(';'); + final separator = parts.first.indexOf('='); + if (separator < 1) return null; + final name = parts.first.substring(0, separator).trim(); + final value = parts.first.substring(separator + 1).trim(); + if (!_validPair(name, value)) return null; + var domain = url.host.toLowerCase(); + var hostOnly = true; + var cookiePath = '/'; + var secure = false; + var httpOnly = false; + int? expires; + for (final raw in parts.skip(1)) { + final separator = raw.indexOf('='); + final key = (separator < 0 ? raw : raw.substring(0, separator)) + .trim() + .toLowerCase(); + final attribute = separator < 0 ? '' : raw.substring(separator + 1).trim(); + switch (key) { + case 'domain': + domain = attribute.replaceFirst(RegExp(r'^\.'), '').toLowerCase(); + hostOnly = false; + case 'path': + cookiePath = attribute; + case 'secure': + secure = true; + case 'httponly': + httpOnly = true; + case 'max-age': + final age = int.tryParse(attribute); + if (age == null) return null; + expires = age <= 0 + ? 1 + : DateTime.now().millisecondsSinceEpoch ~/ 1000 + age; + case 'expires': + if (expires == null) { + try { + expires = HttpDate.parse(attribute).millisecondsSinceEpoch ~/ 1000; + } on FormatException { + return null; + } + } + } + } + if (!_validDomain(domain) || + !(url.host.toLowerCase() == domain || + url.host.toLowerCase().endsWith('.$domain')) || + !_validPath(cookiePath) || + !_validPrefixes(name, secure, hostOnly, cookiePath)) + return null; + return _Cookie( + domain: domain, + hostOnly: hostOnly, + path: cookiePath, + secure: secure, + httpOnly: httpOnly, + expires: expires, + name: name, + value: value, + revision: _revision(), + ); +} + +bool _youtubeDomain(String domain) => + domain == 'youtube.com' || domain.endsWith('.youtube.com'); +bool _validDomain(String domain) => + RegExp(r'^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*youtube\.com$') + .hasMatch(domain); +bool _validPath(String path) => + path.startsWith('/') && + path.codeUnits.every((c) => c > 0x20 && c < 0x7f && c != 0x3b); +bool _validPair(String name, String value) => + RegExp(r"^[A-Za-z0-9!#\$%&'*+.^_`|~-]+$").hasMatch(name) && + value.codeUnits.every( + (c) => + c >= 0x21 && + c <= 0x7e && + c != 0x22 && + c != 0x3b && + c != 0x2c && + c != 0x5c, + ); +bool _validPrefixes(String name, bool secure, bool hostOnly, String path) => + (!name.startsWith('__Secure-') || secure) && + (!name.startsWith('__Host-') || (secure && hostOnly && path == '/')); + +String _revision() { + final random = Random.secure(); + return List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); +} diff --git a/packages/sync-engine/lib/src/database.dart b/packages/sync-engine/lib/src/database.dart new file mode 100644 index 0000000..f8200f3 --- /dev/null +++ b/packages/sync-engine/lib/src/database.dart @@ -0,0 +1,243 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:sqlite_async/native.dart'; +import 'package:sqlite_async/sqlite_async.dart'; +import 'package:uuid/uuid.dart'; + +/// The local journal owns resumable effects; the API owns published state. +/// sqlite_async keeps its writer and reader pool off the application isolate. +class Database { + Database._(this.root, this._connection); + + final Directory root; + final SqliteDatabase _connection; + + static Future open(Directory profile) async { + await profile.create(recursive: true); + final lock = await File(p.join(profile.path, 'sync-schema.lock')) + .open(mode: FileMode.append); + await lock.lock(FileLock.blockingExclusive); + SqliteDatabase? connection; + try { + connection = SqliteDatabase.withFactory( + _DurableOpenFactory(p.join(profile.path, 'sync.sqlite')), + ); + await connection.initialize(); + await connection.writeTransaction((tx) async { + final version = + (await tx.get('PRAGMA user_version')).columnAt(0) as int; + if (version != 0 && version != 1) { + throw StateError('Unsupported sync journal version $version'); + } + if (version == 0) { + await tx.executeMultiple(''' +CREATE TABLE transfers ( + origin TEXT NOT NULL, show_slug TEXT NOT NULL, source_url TEXT NOT NULL, + collection_url TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, + manifest TEXT, upload_session_id TEXT, + PRIMARY KEY(origin, show_slug, source_url, collection_url) +); +CREATE TABLE parts ( + operation_id TEXT NOT NULL REFERENCES transfers(operation_id) ON DELETE CASCADE, + object_index INTEGER NOT NULL CHECK(object_index >= 0), + part_number INTEGER NOT NULL CHECK(part_number > 0), + PRIMARY KEY(operation_id, object_index, part_number) +); +CREATE TABLE downloads ( + operation_id TEXT NOT NULL REFERENCES transfers(operation_id) ON DELETE CASCADE, + name TEXT NOT NULL, identity TEXT NOT NULL, + PRIMARY KEY(operation_id, name) +); +CREATE TABLE download_ranges ( + operation_id TEXT NOT NULL, name TEXT NOT NULL, + start INTEGER NOT NULL CHECK(start >= 0), sha256 TEXT NOT NULL, + PRIMARY KEY(operation_id, name, start), + FOREIGN KEY(operation_id, name) REFERENCES downloads(operation_id, name) ON DELETE CASCADE +); +CREATE TABLE source_items ( + origin TEXT NOT NULL, show_slug TEXT NOT NULL, collection_url TEXT NOT NULL, + source_url TEXT NOT NULL, position INTEGER NOT NULL CHECK(position >= 0), + PRIMARY KEY(origin, show_slug, source_url) +); +PRAGMA user_version=1; +'''); + } + }); + return Database._( + Directory(p.join(profile.path, 'transfers')), + connection, + ); + } catch (_) { + await connection?.close(); + rethrow; + } finally { + await lock.unlock(); + await lock.close(); + } + } + + Future close() => _connection.close(); + + Future snapshot( + String origin, + String show, + String collection, + List urls, + ) => _connection.writeTransaction((tx) async { + await tx.execute( + 'DELETE FROM source_items WHERE origin IS ? AND show_slug IS ?', + [origin, show], + ); + for (var i = 0; i < urls.length; i++) { + await tx.execute( + 'INSERT INTO source_items VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING', + [origin, show, collection, urls[i], i], + ); + } + }); + + Future operation( + String origin, + String show, + String source, + String collection, + ) => _connection.writeTransaction((tx) async { + await tx.execute( + 'INSERT INTO transfers (origin,show_slug,source_url,collection_url,operation_id) VALUES (?,?,?,?,?) ON CONFLICT DO NOTHING', + [origin, show, source, collection, const Uuid().v4()], + ); + final row = await tx.get( + 'SELECT operation_id FROM transfers WHERE origin IS ? AND show_slug IS ? AND source_url IS ? AND collection_url IS ?', + [origin, show, source, collection], + ); + return row['operation_id'] as String; + }); + + Future directory(String operation) async { + if (!Uuid.isValidUUID(fromString: operation)) + throw const FormatException('Invalid transfer operation'); + final result = Directory(p.join(root.path, operation)); + await result.create(recursive: true); + return result; + } + + Future?> prepared(String operation) async { + final row = await _connection.getOptional( + 'SELECT manifest FROM transfers WHERE operation_id IS ?', + [operation], + ); + if (row == null || row['manifest'] == null) return null; + return jsonDecode(row['manifest'] as String) as Map; + } + + Future savePrepared(String operation, Map manifest) => + _connection.writeTransaction((tx) async { + await tx.execute( + 'UPDATE transfers SET manifest=? WHERE operation_id IS ?', + [jsonEncode(manifest), operation], + ); + if ((await tx.get('SELECT changes()')).columnAt(0) != 1) + throw StateError('Missing transfer operation'); + }); + + Future session(String operation, String session) => + _connection.writeTransaction((tx) async { + await tx.execute( + 'DELETE FROM parts WHERE operation_id IS ? AND NOT EXISTS (SELECT 1 FROM transfers WHERE operation_id IS ? AND upload_session_id IS ?)', + [operation, operation, session], + ); + await tx.execute( + 'UPDATE transfers SET upload_session_id=? WHERE operation_id IS ?', + [session, operation], + ); + if ((await tx.get('SELECT changes()')).columnAt(0) != 1) + throw StateError('Missing transfer operation'); + }); + + Future hasPart(String operation, int object, int part) async => + await _connection.getOptional( + 'SELECT 1 FROM parts WHERE operation_id IS ? AND object_index IS ? AND part_number IS ?', + [operation, object, part], + ) != + null; + + Future savePart(String operation, int object, int part) async { + await _connection.execute( + 'INSERT INTO parts VALUES (?,?,?) ON CONFLICT DO NOTHING', + [operation, object, part], + ); + } + + Future download(String operation, String name, String identity) => + _connection.writeTransaction((tx) async { + await tx.execute( + 'DELETE FROM downloads WHERE operation_id IS ? AND name IS ? AND identity IS NOT ?', + [operation, name, identity], + ); + await tx.execute( + 'INSERT INTO downloads VALUES (?,?,?) ON CONFLICT DO NOTHING', + [operation, name, identity], + ); + }); + + Future rangeHash(String operation, String name, int start) async { + final row = await _connection.getOptional( + 'SELECT sha256 FROM download_ranges WHERE operation_id IS ? AND name IS ? AND start IS ?', + [operation, name, start], + ); + return row?['sha256'] as String?; + } + + Future saveRange( + String operation, + String name, + int start, + String hash, + ) async { + await _connection.execute( + 'INSERT INTO download_ranges VALUES (?,?,?,?) ON CONFLICT DO UPDATE SET sha256=excluded.sha256', + [operation, name, start, hash], + ); + } + + Future forget(String origin, String show, String source) async { + final rows = await _connection.getAll( + 'SELECT operation_id FROM transfers WHERE origin IS ? AND show_slug IS ? AND source_url IS ?', + [origin, show, source], + ); + for (final row in rows) { + final directory = await this.directory(row['operation_id'] as String); + if (await directory.exists()) await directory.delete(recursive: true); + } + await _connection.execute( + 'DELETE FROM transfers WHERE origin IS ? AND show_slug IS ? AND source_url IS ?', + [origin, show, source], + ); + } +} + +base class _DurableOpenFactory extends NativeSqliteOpenFactory { + _DurableOpenFactory(String path) + : super( + path: path, + sqliteOptions: const SqliteOptions( + journalMode: SqliteJournalMode.wal, + synchronous: SqliteSynchronous.full, + lockTimeout: Duration(seconds: 5), + maxReaders: 5, + ), + ); + + @override + List pragmaStatements(SqliteOpenOptions options) => [ + ...super.pragmaStatements(options), + 'PRAGMA fullfsync=ON', + 'PRAGMA checkpoint_fullfsync=ON', + 'PRAGMA foreign_keys=ON', + 'PRAGMA cache_size=-2000', + 'PRAGMA wal_autocheckpoint=1000', + 'PRAGMA temp_store=MEMORY', + ]; +} diff --git a/packages/sync-engine/lib/src/download.dart b/packages/sync-engine/lib/src/download.dart new file mode 100644 index 0000000..9977de6 --- /dev/null +++ b/packages/sync-engine/lib/src/download.dart @@ -0,0 +1,160 @@ +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:http/http.dart' as http; +import 'package:path/path.dart' as p; + +import 'api.dart'; +import 'cancellation.dart'; +import 'database.dart'; +import 'downloads.dart'; + +class MediaUnavailable implements Exception { + @override + String toString() => + 'YouTube did not allow playback of this video. It will be checked again at the next sync.'; +} + +class MediaStream { + const MediaStream({ + required this.url, + required this.identity, + required this.userAgent, + }); + final Uri url; + final String identity; + final String userAgent; +} + +Future downloadMedia( + Api api, + MediaStream source, + File path, { + required CancellationToken cancel, + Transfer? transfer, + Database? journal, + String? operation, +}) async { + cancel.throwIfCancelled(); + http.Request request(int start, int end, String? validator) { + final result = http.Request('GET', source.url); + result.headers.addAll({ + 'Range': 'bytes=$start-$end', + 'Origin': 'https://youtube.com', + 'User-Agent': source.userAgent, + if (validator != null) 'If-Range': validator, + }); + return result; + } + + final first = await api.sendExternal(request(0, 0, null)); + if (first.statusCode == 403) throw MediaUnavailable(); + if (first.statusCode != 206) + throw StateError('Resolve download length: HTTP ${first.statusCode}'); + final contentRange = first.headers['content-range']; + final match = RegExp(r'^bytes 0-0/(\d+)$').firstMatch(contentRange ?? ''); + if (match == null) throw StateError('Invalid initial media range'); + final total = int.parse(match[1]!); + if (total <= 0 || total > 5000000000000) + throw StateError('Invalid media length'); + final etag = first.headers['etag']; + final validator = etag != null && !etag.startsWith('W/') + ? etag + : first.headers['last-modified']; + final revision = validator ?? source.url.queryParameters['lmt']; + await api.readBounded(first, 64 << 10); + final identity = + '${source.identity}:$total:${revision ?? DateTime.now().microsecondsSinceEpoch}'; + if (journal != null && operation != null) + await journal.download(operation, p.basename(path.path), identity); + await path.parent.create(recursive: true); + final resized = await path.open( + mode: path.existsSync() ? FileMode.append : FileMode.write, + ); + try { + await resized.truncate(total); + } finally { + await resized.close(); + } + transfer?.startDownload(total); + + Future one(int start) async { + cancel.throwIfCancelled(); + final end = (start + rangeBytes).clamp(0, total) - 1; + final length = end - start + 1; + final file = await path.open(mode: FileMode.append); + try { + final savedHash = journal == null + ? null + : await journal.rangeHash(operation!, p.basename(path.path), start); + if (savedHash != null) { + await file.setPosition(start); + final saved = await file.read(length); + if (saved.length == length && + sha256.convert(saved).toString() == savedHash) { + transfer?.range(start, length, RangePhase.complete); + return; + } + } + final response = await api.sendExternal(request(start, end, validator)); + if (response.statusCode == 403) throw MediaUnavailable(); + if (response.statusCode != 206) + throw StateError( + 'Download range returned HTTP ${response.statusCode}; source may have changed', + ); + if (response.headers['content-range'] != 'bytes $start-$end/$total') + throw StateError('Media range differs from the requested bytes'); + final bytes = []; + await for (final chunk in response.stream) { + cancel.throwIfCancelled(); + if (bytes.length + chunk.length > length) + throw StateError('Media range exceeded its declared length'); + bytes.addAll(chunk); + transfer?.range(start, bytes.length, RangePhase.active); + } + if (bytes.length != length) throw StateError('Media range was truncated'); + await file.setPosition(start); + await file.writeFrom(bytes); + await file.flush(); + if (journal != null) + await journal.saveRange( + operation!, + p.basename(path.path), + start, + sha256.convert(bytes).toString(), + ); + transfer?.range(start, length, RangePhase.complete); + } finally { + await file.close(); + } + } + + Object? firstError; + StackTrace? firstStack; + for (var base = 0; base < total; base += rangeBytes * rangesPerTransfer) { + if (firstError != null) break; + final work = >[]; + for (var index = 0; index < rangesPerTransfer; index++) { + final start = base + index * rangeBytes; + if (start < total) work.add(one(start)); + } + final settled = await Future.wait( + work.map((future) async { + try { + await future; + return null; + } catch (error, stack) { + return (error, stack); + } + }), + ); + for (final result in settled) { + if (result != null) { + firstError ??= result.$1; + firstStack ??= result.$2; + } + } + } + if (firstError != null) + Error.throwWithStackTrace(firstError, firstStack ?? StackTrace.current); +} diff --git a/packages/sync-engine/lib/src/downloads.dart b/packages/sync-engine/lib/src/downloads.dart new file mode 100644 index 0000000..ed1d763 --- /dev/null +++ b/packages/sync-engine/lib/src/downloads.dart @@ -0,0 +1,206 @@ +import 'dart:async'; + +import 'cancellation.dart'; + +const rangeBytes = 1024 * 1024; +const rangesPerTransfer = 4; +const initialTransfers = 2; +const maxTransfers = 16; + +enum Phase { + queued, + resolving, + downloading, + preparing, + uploading, + complete, + skipped, + failed, +} + +enum RangePhase { waiting, active, complete } + +class ByteRange { + ByteRange(this.start, this.end); + final int start; + final int end; + int received = 0; + RangePhase phase = RangePhase.waiting; +} + +class Download { + Download({ + required this.id, + required this.sourceId, + required this.sourceTitle, + required this.title, + }); + final String id; + final String sourceId; + final String sourceTitle; + String title; + int? durationSeconds; + String? reason; + String? error; + Phase phase = Phase.queued; + int total = 0; + List ranges = []; + int get received => ranges.fold(0, (sum, range) => sum + range.received); +} + +class DownloadSnapshot { + DownloadSnapshot(List items, this.slotLimit) + : items = List.unmodifiable(items); + final List items; + final int slotLimit; +} + +/// One isolate owns the queue and every projection update. Slots cover the +/// complete resolve, download, preparation, and upload lifecycle. +class DownloadManager { + final List _items = []; + final StreamController _changes = + StreamController.broadcast(sync: true); + final List> _waiters = []; + int _active = 0; + int slotLimit = initialTransfers; + + Stream get changes => _changes.stream; + DownloadSnapshot snapshot() => DownloadSnapshot(_items, slotLimit); + void _notify() => _changes.add(snapshot()); + + void clear() { + if (_active != 0) throw StateError('Downloads are still active'); + _items.clear(); + _notify(); + } + + void removeSource(String sourceId) { + _items.removeWhere((item) => item.sourceId == sourceId); + _notify(); + } + + List enqueue( + String sourceId, + String sourceTitle, + List<({String id, String title})> episodes, + ) { + removeSource(sourceId); + final result = []; + for (final episode in episodes) { + final item = Download( + id: '$sourceId/${episode.id}', + sourceId: sourceId, + sourceTitle: sourceTitle, + title: episode.title, + ); + _items.add(item); + result.add(Transfer._(this, item)); + } + _notify(); + return result; + } + + Future drain() async { + while (_active > 0) { + final waiter = Completer(); + _waiters.add(waiter); + await waiter.future; + } + } + + Future acquire( + Transfer transfer, + CancellationToken cancel, + ) async { + while (_active >= slotLimit) { + cancel.throwIfCancelled(); + final waiter = Completer(); + _waiters.add(waiter); + await cancel.race(waiter.future); + } + cancel.throwIfCancelled(); + _active++; + transfer.phase(Phase.resolving); + return ActiveTransfer._(this, transfer); + } + + void _release() { + _active--; + for (final waiter in _waiters) { + if (!waiter.isCompleted) waiter.complete(); + } + _waiters.clear(); + } +} + +class Transfer { + Transfer._(this._manager, this.item); + final DownloadManager _manager; + final Download item; + Future acquire(CancellationToken cancel) => + _manager.acquire(this, cancel); + void phase(Phase value) { + item.phase = value; + _manager._notify(); + } + + void title(String value) { + item.title = value; + _manager._notify(); + } + + void duration(int? value) { + if (value != null) item.durationSeconds = value; + _manager._notify(); + } + + void skipped(String reason) { + item.phase = Phase.skipped; + item.reason = reason; + _manager._notify(); + } + + void error(Object error) { + item.phase = Phase.failed; + item.error = error.toString(); + _manager._notify(); + } + + void startDownload(int total) { + item.phase = Phase.downloading; + item.total = total; + item.ranges = [ + for (var start = 0; start < total; start += rangeBytes) + ByteRange(start, (start + rangeBytes).clamp(0, total) - 1), + ]; + _manager._notify(); + } + + void range(int start, int received, RangePhase phase) { + final entry = item.ranges + .where((range) => range.start == start) + .firstOrNull; + if (entry == null) throw StateError('Unknown download range'); + entry.received = received; + entry.phase = phase; + _manager._notify(); + } +} + +class ActiveTransfer { + ActiveTransfer._(this._manager, this.transfer); + final DownloadManager _manager; + final Transfer transfer; + bool _finished = false; + void finish([Object? error]) { + if (_finished) return; + _finished = true; + if (error != null) { + transfer.error(error); + } else if (transfer.item.phase != Phase.skipped) { + transfer.phase(Phase.complete); + } + _manager._release(); + } +} diff --git a/packages/sync-engine/lib/src/episodes.dart b/packages/sync-engine/lib/src/episodes.dart new file mode 100644 index 0000000..bb683b6 --- /dev/null +++ b/packages/sync-engine/lib/src/episodes.dart @@ -0,0 +1,233 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as p; + +import 'api.dart'; +import 'config.dart'; +import 'events.dart'; +import 'publicapi/models.dart' as publicapi; +import 'validation.dart'; +import 'youtube.dart' show fileHash, uploadPart; + +Future createEpisode( + Api api, { + required String show, + required String title, + required File file, + String? description, + String publication = 'publish', + void Function(String)? onProgress, +}) async { + if (!{'draft', 'publish'}.contains(publication)) + throw const FormatException('invalid publication'); + final path = file.absolute; + final (length, hash) = await fileHash(path); + final extension = p.extension(path.path).toLowerCase(); + final contentType = switch (extension) { + '.mp3' => 'audio/mpeg', + '.m4a' => 'audio/mp4', + '.wav' => 'audio/wav', + '.flac' => 'audio/flac', + '.mp4' || '.m4v' => 'video/mp4', + '.mov' => 'video/quicktime', + _ => throw const FormatException( + 'unsupported media upload file; accepted extensions: .mp3, .m4a, .wav, .flac, .mp4, .m4v, .mov', + ), + }; + final key = sha256.convert(utf8.encode('$show\u0000$hash')).toString(); + final resumePath = p.join( + api.config.directory, + 'episode-resume', + '$key.json', + ); + Map record; + final resume = File(resumePath); + if (resume.existsSync()) { + final raw = jsonDecode(resume.readAsStringSync()); + if (raw is! Map || + raw['version'] != 1 || + raw['file_sha256'] != hash || + raw['file_byte_length'] != length) { + throw const FormatException('invalid episode resume record'); + } + record = raw; + final expires = record['expires_at']; + if (expires is! int || + (expires != 0 && + expires <= DateTime.now().millisecondsSinceEpoch && + !{ + 'finalizing', + 'processing', + 'completed', + }.contains(record['phase']))) { + throw FormatException( + 'resumable upload expired; remove $resumePath to restart explicitly', + ); + } + } else { + record = { + 'version': 1, + 'episode_id': '', + 'upload_session_id': '', + 'team_id': '', + 'show_id': '', + 'management_url': '', + 'file_path': path.path, + 'file_sha256': hash, + 'file_byte_length': length, + 'completed_parts': [], + 'expires_at': 0, + 'phase': 'prepared', + }; + } + if (!{'finalizing', 'processing', 'completed'}.contains(record['phase'])) { + final response = await api.publicClient.createEpisodeUploadSession( + body: publicapi.CreateEpisodeUploadSession( + showSlug: show, + title: title, + fileName: p.basename(path.path), + contentType: publicapi.EpisodeUploadContentType.fromJson(contentType), + byteLength: length, + sourceSha256: hash, + description: description, + ), + ); + record['upload_session_id'] = response.uploadSessionId; + record['team_id'] = response.teamId; + record['show_id'] = response.showId; + record['episode_id'] = response.episodeId ?? ''; + record['expires_at'] = response.expiresAt; + record['phase'] = response.phase.value; + record['completed_parts'] = response.completedParts + .map((part) => part.toJson()) + .toList(); + writePrivateJson(resumePath, record); + if (record['phase'] != 'finalizing') { + final partSize = response.partSize; + if (partSize < 5 << 20) + throw StateError('invalid upload part size $partSize'); + final count = (length + partSize - 1) ~/ partSize; + if (count > 10000) + throw StateError('episode source requires too many parts'); + final completed = (record['completed_parts'] as List) + .cast>(); + final accepted = completed.map((part) => part['part_number']).toSet(); + final missing = [ + for (var number = 1; number <= count; number++) + if (!accepted.contains(number)) number, + ]; + _progress(record, onProgress); + if (missing.isNotEmpty) { + final signed = await api.publicClient.presignEpisodeUploadSessionParts( + uploadSessionId: response.uploadSessionId, + body: publicapi.PresignEpisodeUploadSessionParts( + partNumbers: missing, + ), + ); + final pending = missing.toSet(); + for (final part in signed.parts) { + final number = part.partNumber; + if (!pending.remove(number)) + throw StateError('unexpected or duplicate signed part $number'); + final offset = (number - 1) * partSize; + final size = (length - offset).clamp(0, partSize); + final etag = await uploadPart( + api, + path, + offset, + size, + Uri.parse(part.uploadUrl), + method: part.method, + ); + completed.add({'part_number': number, 'etag': etag, 'size': size}); + completed.sort( + (a, b) => + (a['part_number'] as int).compareTo(b['part_number'] as int), + ); + record['phase'] = 'uploading'; + writePrivateJson(resumePath, record); + _progress(record, onProgress); + } + if (pending.isNotEmpty) + throw const FormatException('signed response omitted upload parts'); + } + } + record['phase'] = 'finalizing'; + writePrivateJson(resumePath, record); + } + final episode = await api.publicClient.completeEpisodeUploadSession( + uploadSessionId: record['upload_session_id'] as String, + body: publicapi.CompleteEpisodeUploadSession( + publication: publicapi.EpisodePublication.fromJson(publication), + ), + ); + record['episode_id'] = episode.id; + record['show_id'] = episode.showId; + final episodeId = record['episode_id'] as String; + if (!validId(episodeId, 'ep_')) + throw const FormatException('invalid episode management identifier'); + record['management_url'] = + '${api.config.showUrl(record['team_id'] as String, record['show_id'] as String)}/episodes/$episodeId/edit'; + record['phase'] = 'processing'; + writePrivateJson(resumePath, record); + final eventResponse = await api.publicClient.episodeUploadSessionEvents( + uploadSessionId: record['upload_session_id'] as String, + ); + final events = await EventStream.fromResponse(api, eventResponse); + try { + while (true) { + final event = await events.next(); + switch (jsonString(event, 'type')) { + case 'episode.processing.progress': + final progress = publicapi.EpisodeProcessingProgressEvent.fromJson( + event, + ); + final percent = progress.percent; + if (percent < 0 || percent > 100) + throw const FormatException('invalid processing progress'); + onProgress?.call('Episode processing: $percent%'); + case 'episode.processing.safe_handoff': + record['phase'] = 'completed'; + writePrivateJson(resumePath, record); + onProgress?.call( + '${publication == 'publish' ? 'Published episode' : 'Created draft episode'} "$title"\nOpen in Listenbox: ${record['management_url']}', + ); + final handoff = publicapi.EpisodeProcessingSafeHandoffEvent.fromJson( + event, + ); + final video = handoff.youtubeVideoId; + if (video is String && video.isNotEmpty) + onProgress?.call( + 'YouTube (processing): https://www.youtube.com/watch?v=$video', + ); + return; + case 'episode.processing.failed': + final failure = publicapi.EpisodeProcessingFailedEvent.fromJson( + event, + ); + throw StateError( + 'episode processing failed (${failure.errorCode}): ${failure.errorMessage}', + ); + default: + throw FormatException( + 'unknown episode processing event ${event['type']}', + ); + } + } + } finally { + await events.close(); + } +} + +void _progress(Map record, void Function(String)? callback) { + final completed = record['completed_parts'] as List; + final saved = completed.fold( + 0, + (sum, part) => sum + ((part as Map)['size'] as int), + ); + callback?.call( + 'Source upload: ${(saved * 100 ~/ (record['file_byte_length'] as int)).clamp(0, 100)}% saved', + ); +} diff --git a/packages/sync-engine/lib/src/events.dart b/packages/sync-engine/lib/src/events.dart new file mode 100644 index 0000000..6b02163 --- /dev/null +++ b/packages/sync-engine/lib/src/events.dart @@ -0,0 +1,90 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; + +import 'api.dart'; +import 'validation.dart'; + +/// Bounded parser for API terminal event streams. +class EventStream { + EventStream._(this._api, this._iterator); + + final Api _api; + final StreamIterator> _iterator; + final List _buffer = []; + final StringBuffer _data = StringBuffer(); + bool _closed = false; + + static Future fromResponse( + Api api, + http.StreamedResponse response, + ) async { + if (response.statusCode != 200) throw await api.responseError(response); + if (!(response.headers['content-type']?.startsWith('text/event-stream') ?? + false)) { + throw const FormatException('expected an event stream'); + } + return EventStream._(api, StreamIterator(response.stream)); + } + + Future> next() async { + if (_closed) throw StateError('event stream is closed'); + while (true) { + final end = _buffer.indexOf(0x0a); + if (end >= 0) { + final line = _buffer.sublist(0, end); + _buffer.removeRange(0, end + 1); + if (line.isNotEmpty && line.last == 0x0d) line.removeLast(); + final text = utf8.decode(line); + if (text.isEmpty && _data.isNotEmpty) { + final data = _data.toString(); + _data.clear(); + return jsonObject(jsonDecode(data), 'event'); + } + if (text.startsWith('data:')) { + if (_data.isNotEmpty) _data.write('\n'); + final payload = text.substring(5); + _data.write(payload.startsWith(' ') ? payload.substring(1) : payload); + } + if (_data.length > 1 << 20) { + throw const FormatException('event exceeds size limit'); + } + continue; + } + final hasNext = await _api.cancel.race(_iterator.moveNext()); + if (!hasNext) { + throw const FormatException( + 'event stream ended before a terminal event', + ); + } + final chunk = _iterator.current; + if (chunk.length > (1 << 20) - _buffer.length) { + throw const FormatException('event line exceeds size limit'); + } + _buffer.addAll(chunk); + } + } + + Future close() async { + if (_closed) return; + _closed = true; + await _iterator.cancel(); + } +} + +class Progress { + int? _last; + + /// Returns whether the visible progress advanced. + bool update(int percent) { + if (percent < 0 || percent > 100) { + throw FormatException('malformed progress percent $percent'); + } + if (_last != null && percent <= _last!) return false; + _last = percent; + stderr.writeln('Import progress: $percent%'); + return true; + } +} diff --git a/packages/sync-engine/lib/src/innertube.dart b/packages/sync-engine/lib/src/innertube.dart new file mode 100644 index 0000000..f4003a9 --- /dev/null +++ b/packages/sync-engine/lib/src/innertube.dart @@ -0,0 +1,379 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:client_youtubei/client_youtubei.dart'; +import 'package:crypto/crypto.dart'; +import 'package:http/http.dart' as http; + +import 'api.dart'; +import 'cancellation.dart'; +import 'cookies.dart'; +import 'download.dart'; + +class Video { + const Video(this.id, this.title, this.durationSeconds); + final String id; + final String title; + final int? durationSeconds; +} + +class PlaylistSnapshot { + const PlaylistSnapshot({ + required this.title, + required this.present, + required this.estimatedSeconds, + required this.canRemove, + }); + final String title; + final List