From efbe8f275774e5cadfffa2544a8505be74b9dee1 Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Thu, 3 Dec 2026 15:14:39 +0530 Subject: [PATCH 01/11] Add bundled Linux playback, read-only comments, and 0.26.0 release groundwork --- .github/dependabot.yml | 27 + .github/workflows/ci.yml | 53 ++ .github/workflows/release-linux.yml | 105 +++- .github/workflows/security.yml | 137 ++++- .gitleaks.toml | 21 + INSTALL.md | 47 +- README.md | 13 +- SECURITY.md | 2 +- buildSrc/src/main/kotlin/ProjectConfig.kt | 2 +- buildSrc/src/main/kotlin/VlcBundleTask.kt | 24 +- desktopApp/build.gradle.kts | 8 +- .../kotlin/net/newpipe/app/DesktopVersions.kt | 2 +- .../src/main/kotlin/net/newpipe/app/Main.kt | 5 +- packaging/flatpak/build-flatpak.sh | 117 ++++ packaging/linux/build-vlc-runtime.sh | 187 ++++++ packaging/linux/smoke-test-vlc.sh | 53 ++ packaging/linux/smoke/VlcBundleSmoke.java | 55 ++ shared/build.gradle.kts | 1 + .../app/service/AndroidContentRepository.kt | 13 + .../composeResources/drawable/ic_comment.xml | 15 + .../drawable/ic_expand_less.xml | 15 + .../drawable/ic_expand_more.xml | 15 + .../composeResources/drawable/ic_favorite.xml | 15 + .../composeResources/drawable/ic_push_pin.xml | 15 + .../composeResources/drawable/ic_thumb_up.xml | 15 + .../composeResources/drawable/ic_verified.xml | 15 + .../kotlin/net/newpipe/app/model/Comment.kt | 47 ++ .../net/newpipe/app/platform/UpdateActions.kt | 6 + .../screen/settings/UpdateSettingsScreen.kt | 2 + .../newpipe/app/screen/stream/StreamScreen.kt | 25 + .../newpipe/app/screen/stream/WatchPage.kt | 545 +++++++++++++++++- .../newpipe/app/service/ContentRepository.kt | 23 + .../app/viewmodel/stream/StreamViewModel.kt | 244 ++++++++ .../app/service/IosContentRepository.kt | 11 + .../app/di/settings/DesktopSettings.kt | 25 +- .../net/newpipe/app/platform/AppFileLogger.kt | 4 +- .../net/newpipe/app/platform/DesktopPaths.kt | 98 ++++ .../app/service/DownloadLocation.jvm.kt | 68 ++- .../app/service/ExtractorContentRepository.kt | 222 +++++++ .../net/newpipe/app/service/UpdateService.kt | 16 + .../newpipe/app/service/VlcNativeLocator.kt | 123 ++-- .../app/service/VlcPlaybackController.kt | 13 +- .../net/newpipe/app/service/YtSession.kt | 27 +- .../newpipe/app/service/CommentMappingTest.kt | 127 ++++ .../stream/StreamViewModelCommentsTest.kt | 246 ++++++++ 45 files changed, 2693 insertions(+), 156 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .gitleaks.toml create mode 100755 packaging/flatpak/build-flatpak.sh create mode 100755 packaging/linux/build-vlc-runtime.sh create mode 100755 packaging/linux/smoke-test-vlc.sh create mode 100644 packaging/linux/smoke/VlcBundleSmoke.java create mode 100644 shared/src/commonMain/composeResources/drawable/ic_comment.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_expand_less.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_expand_more.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_favorite.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_push_pin.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_thumb_up.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_verified.xml create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/model/Comment.kt create mode 100644 shared/src/jvmMain/kotlin/net/newpipe/app/platform/DesktopPaths.kt create mode 100644 shared/src/jvmTest/kotlin/net/newpipe/app/service/CommentMappingTest.kt create mode 100644 shared/src/jvmTest/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModelCommentsTest.kt diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..2ad143cba --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,27 @@ +version: 2 +updates: + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + groups: + kotlin: + patterns: + - "org.jetbrains.kotlin*" + compose: + patterns: + - "org.jetbrains.compose*" + - "androidx.compose*" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 3 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b8a4b3dd..c99b267a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,3 +46,56 @@ jobs: - name: Run JVM tests run: ./gradlew :shared:jvmTest --stacktrace + + linux-bundle: + # Builds the portable libVLC runtime and proves that the packaged app extracts and plays + # it on a machine that has no VLC installed. The runtime is built on Ubuntu 22.04, the + # oldest supported glibc, and the clean-container test runs on Ubuntu 24.04. + runs-on: ubuntu-22.04 + + permissions: + contents: read + + steps: + - uses: actions/checkout@v6 + + - name: set up JDK + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: "temurin" + cache: 'gradle' + + - name: Install libVLC build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + libvlc5 libvlccore9 vlc-plugin-base patchelf file ffmpeg + curl -fsSL -o /tmp/patchelf.tar.gz \ + "https://github.com/NixOS/patchelf/releases/download/0.19.3/patchelf-0.19.3-x86_64.tar.gz" + mkdir -p /tmp/patchelf + tar -xzf /tmp/patchelf.tar.gz -C /tmp/patchelf + echo "/tmp/patchelf/bin" >> "$GITHUB_PATH" + + - name: Build the portable libVLC runtime + run: packaging/linux/build-vlc-runtime.sh build/vlc-runtime + + - name: Build the app image with the bundled runtime + run: | + ./gradlew :desktopApp:createReleaseDistributable \ + -PvlcPrefix="$PWD/build/vlc-runtime" --no-daemon + + - name: Smoke test the bundled runtime + run: | + app=$(find desktopApp/build/compose/binaries/main-release/app -maxdepth 1 -mindepth 1 -type d | head -n 1) + packaging/linux/smoke-test-vlc.sh "$app" + + - name: Smoke test in a clean Ubuntu container without VLC + run: | + app=$(find desktopApp/build/compose/binaries/main-release/app -maxdepth 1 -mindepth 1 -type d | head -n 1) + docker run --rm -v "$PWD:/work" -w /work ubuntu:24.04 bash -c " + set -e + apt-get update >/dev/null + apt-get install -y --no-install-recommends openjdk-21-jre-headless ffmpeg >/dev/null + packaging/linux/smoke-test-vlc.sh '$app' + " diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index dc4f88be5..56ac90711 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: tag: - description: 'Tag to build and release (e.g. v0.25.5)' + description: 'Tag to build and release (e.g. v0.26.0)' required: true type: string @@ -16,11 +16,13 @@ permissions: env: JAVA_VERSION: '21' + PATCHELF_VERSION: '0.19.3' jobs: build-linux: - name: Build Linux Deb and Portable Packages - runs-on: ubuntu-latest + name: Build Linux Deb, Portable and Flatpak Packages + # Ubuntu 22.04 keeps the bundled libVLC compatible with Debian 12, Ubuntu 22.04 and newer. + runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v4 @@ -35,13 +37,35 @@ jobs: java-version: ${{ env.JAVA_VERSION }} cache: 'gradle' + - name: Install the libVLC runtime build dependencies + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + libvlc5 libvlccore9 vlc-plugin-base \ + patchelf file ffmpeg flatpak + # Ubuntu 22.04 ships patchelf 0.14, which corrupts the RELR relocations of modern + # libraries. Use the current upstream static build for the runtime. + curl -fsSL -o /tmp/patchelf.tar.gz \ + "https://github.com/NixOS/patchelf/releases/download/${PATCHELF_VERSION}/patchelf-${PATCHELF_VERSION}-x86_64.tar.gz" + mkdir -p /tmp/patchelf + tar -xzf /tmp/patchelf.tar.gz -C /tmp/patchelf + echo "/tmp/patchelf/bin" >> "$GITHUB_PATH" + /tmp/patchelf/bin/patchelf --version + - name: Grant execute permission for gradlew run: chmod +x gradlew shell: bash + - name: Build the portable libVLC runtime + shell: bash + run: packaging/linux/build-vlc-runtime.sh build/vlc-runtime + - name: Build Deb package and portable app image - run: ./gradlew :desktopApp:packageReleaseDeb :desktopApp:createReleaseDistributable --no-daemon shell: bash + run: | + ./gradlew :desktopApp:packageReleaseDeb :desktopApp:createReleaseDistributable \ + -PvlcPrefix="$PWD/build/vlc-runtime" --no-daemon - name: Locate artifacts id: locate @@ -57,6 +81,11 @@ jobs: echo "No app image found in build output" >&2 exit 1 fi + # The package must not depend on a system VLC anymore. + if dpkg-deb -f "$deb" Depends | tr ',' '\n' | grep -qE '^ *vlc( |$)'; then + echo "The Debian package still depends on the system VLC" >&2 + exit 1 + fi echo "Found deb: $deb ($(du -h "$deb" | cut -f1))" echo "Found app image: $app ($(du -sh "$app" | cut -f1))" echo "DEB_PATH=$deb" >> "$GITHUB_OUTPUT" @@ -72,22 +101,47 @@ jobs: tarball="np-desktop-${version}-linux-x64.tar.gz" tar -czf "$tarball" -C "${{ steps.locate.outputs.APP_DIR }}" . echo "Found tarball: $tarball ($(du -h "$tarball" | cut -f1))" + echo "VERSION=$version" >> "$GITHUB_OUTPUT" echo "TARBALL_PATH=$tarball" >> "$GITHUB_OUTPUT" echo "TARBALL_NAME=$tarball" >> "$GITHUB_OUTPUT" - - name: Add VLC runtime dependency + - name: Smoke test the bundled runtime + shell: bash + run: packaging/linux/smoke-test-vlc.sh "${{ steps.locate.outputs.APP_DIR }}" + + - name: Smoke test in a clean Ubuntu container without VLC shell: bash run: | - deb="${{ steps.locate.outputs.DEB_PATH }}" - work=$(mktemp -d) - dpkg-deb -R "$deb" "$work" - if grep -q '^Depends:' "$work/DEBIAN/control"; then - sed -i 's/^Depends: /Depends: vlc, /' "$work/DEBIAN/control" - else - sed -i '/^Package:/a Depends: vlc' "$work/DEBIAN/control" - fi - dpkg-deb -b "$work" "$deb" - rm -rf "$work" + docker run --rm -v "$PWD:/work" -w /work ubuntu:24.04 bash -c ' + set -e + apt-get update >/dev/null + apt-get install -y --no-install-recommends openjdk-21-jre-headless ffmpeg >/dev/null + packaging/linux/smoke-test-vlc.sh "${{ steps.locate.outputs.APP_DIR }}" + ' + + - name: Import the Flatpak signing key + if: env.FLATPAK_GPG_PRIVATE_KEY != '' + env: + FLATPAK_GPG_PRIVATE_KEY: ${{ secrets.FLATPAK_GPG_PRIVATE_KEY }} + shell: bash + run: | + export FLATPAK_GPG_HOME="$PWD/.gnupg" + mkdir -p "$FLATPAK_GPG_HOME" + chmod 700 "$FLATPAK_GPG_HOME" + printf '%s\n' "$FLATPAK_GPG_PRIVATE_KEY" | \ + gpg --homedir "$FLATPAK_GPG_HOME" --batch --import + echo "FLATPAK_GPG_HOME=$FLATPAK_GPG_HOME" >> "$GITHUB_ENV" + + - name: Build the Flatpak bundle + shell: bash + env: + FLATPAK_GPG_KEY_ID: ${{ secrets.FLATPAK_GPG_KEY_ID }} + FLATPAK_GPG_HOME: ${{ github.workspace }}/.gnupg + run: | + packaging/flatpak/build-flatpak.sh \ + "${{ steps.locate.outputs.APP_DIR }}" \ + "${{ steps.portable.outputs.VERSION }}" \ + build/flatpak - name: Generate SHA-256 checksums id: checksum @@ -95,9 +149,14 @@ jobs: run: | deb="${{ steps.locate.outputs.DEB_PATH }}" tarball="${{ steps.portable.outputs.TARBALL_PATH }}" + version="${{ steps.portable.outputs.VERSION }}" + flatpak="build/flatpak/np-desktop-${version}-x86_64.flatpak" { echo "$(sha256sum "$deb" | cut -d' ' -f1) $(basename "$deb")" echo "$(sha256sum "$tarball" | cut -d' ' -f1) $(basename "$tarball")" + if [ -f "$flatpak" ]; then + echo "$(sha256sum "$flatpak" | cut -d' ' -f1) $(basename "$flatpak")" + fi } > checksums-linux-sha256.txt cat checksums-linux-sha256.txt @@ -108,6 +167,8 @@ jobs: path: | ${{ steps.locate.outputs.DEB_PATH }} ${{ steps.portable.outputs.TARBALL_PATH }} + build/flatpak/*.flatpak + build/flatpak/*.flatpakrepo checksums-linux-sha256.txt retention-days: 7 @@ -121,10 +182,14 @@ jobs: gh release create "$tag" --title "NP Desktop $tag" \ --notes "Automated build for $tag" || true fi - gh release upload "$tag" \ - "${{ steps.locate.outputs.DEB_PATH }}" \ - "${{ steps.portable.outputs.TARBALL_PATH }}" \ - checksums-linux-sha256.txt \ - --clobber + assets=( + "${{ steps.locate.outputs.DEB_PATH }}" + "${{ steps.portable.outputs.TARBALL_PATH }}" + checksums-linux-sha256.txt + ) + for file in build/flatpak/*.flatpak build/flatpak/*.flatpakrepo; do + [ -f "$file" ] && assets+=("$file") + done + gh release upload "$tag" "${assets[@]}" --clobber env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 0517fba13..210f4c196 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -1,48 +1,123 @@ name: Security on: - push: - branches: [main] pull_request: - branches: [main] + branches: + - main + push: + branches: + - main + schedule: + # Weekly, so a new CVE in a dependency is reported even without a code change. + - cron: '0 4 * * 1' workflow_dispatch: permissions: contents: read + security-events: write + actions: read jobs: - secret-scan: - runs-on: ubuntu-latest + codeql: + name: CodeQL (Java/Kotlin) + runs-on: ubuntu-22.04 + permissions: + security-events: write + contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 + - uses: github/codeql-action/init@v3 with: - fetch-depth: 0 - - name: Gitleaks scan - uses: gitleaks/gitleaks-action@v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }} + languages: java-kotlin + queries: security-and-quality + - uses: github/codeql-action/autobuild@v3 + - uses: github/codeql-action/analyze@v3 - dependency-review: - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write + dependency-check: + name: Dependency-Check, Trivy and SBOM + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 - - uses: actions/dependency-review-action@v4 + - uses: actions/checkout@v6 - gradle-build-test: - runs-on: ubuntu-latest - permissions: - contents: read + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: temurin + cache: gradle + + - name: Cache the NVD data + uses: actions/cache@v4 + with: + path: ~/.dependency-check/data + key: dependency-check-${{ runner.os }}-${{ hashFiles('gradle/libs.versions.toml') }} + restore-keys: | + dependency-check-${{ runner.os }}- + + - name: Build the desktop app image + run: ./gradlew :desktopApp:createReleaseDistributable --no-daemon + + - name: Locate the app image + id: locate + run: | + app=$(find desktopApp/build/compose/binaries/main-release/app -maxdepth 1 -mindepth 1 -type d | head -n 1) + test -n "$app" + echo "APP_DIR=$app" >> "$GITHUB_OUTPUT" + + - name: Run OWASP Dependency-Check + env: + NVD_API_KEY: ${{ secrets.NVD_API_KEY }} + run: | + curl -fsSL -o /tmp/dependency-check.zip \ + https://github.com/dependency-check/DependencyCheck/releases/download/v12.1.0/dependency-check-12.1.0-release.zip + unzip -q /tmp/dependency-check.zip -d /tmp + args=( + --project "NP Desktop" + --scan "${{ steps.locate.outputs.APP_DIR }}/lib/app" + --format HTML + --format JSON + --out dependency-check-report + --failOnCVSS 7 + --enableExperimental + ) + if [ -n "$NVD_API_KEY" ]; then + args+=(--nvdApiKey "$NVD_API_KEY") + fi + /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" + + - name: Run Trivy on the packaged libraries + uses: aquasecurity/trivy-action@0.28.0 + with: + scan-type: fs + scan-ref: ${{ steps.locate.outputs.APP_DIR }}/lib/app + severity: HIGH,CRITICAL + ignore-unfixed: true + exit-code: '1' + format: table + + - name: Generate a CycloneDX SBOM + uses: anchore/sbom-action@v0 + with: + path: ${{ steps.locate.outputs.APP_DIR }} + format: cyclonedx-json + output-file: sbom-linux.cyclonedx.json + artifact-name: sbom-linux.cyclonedx.json + + - name: Upload the dependency report + if: always() + uses: actions/upload-artifact@v4 + with: + name: dependency-check-report + path: dependency-check-report/ + retention-days: 14 + + gitleaks: + name: Secret scan + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@v6 with: - distribution: 'temurin' - java-version: '21' - cache: 'gradle' - - name: Build and test - run: ./gradlew test jvmTest 2>&1 | tail -30 + fetch-depth: 0 + - uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 000000000..961baf9cd --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,21 @@ +# Gitleaks configuration for the NP Desktop repository. +# +# Test fixtures intentionally contain fake credentials and URLs that look like secrets; they +# must not turn the secret scan into a permanent failure. Real source files are still scanned +# with the default rule set. +title = "NP Desktop" + +[extend] +useDefault = true + +[allowlist] +description = "Intentional test fixtures and binary build inputs" +paths = [ + '''shared/src/commonTest/.*''', + '''shared/src/jvmTest/.*''', + '''shared/src/androidDeviceTest/.*''', + '''app/src/test/.*''', + '''app/src/androidTest/.*''', + '''gradle/wrapper/gradle-wrapper.jar''', + '''.*\.png''', +] diff --git a/INSTALL.md b/INSTALL.md index 53b0546fc..dced9cbc2 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -5,14 +5,15 @@ This guide covers installing NP Desktop on Windows and Linux, verifying your dow ## Download 1. Go to the [Releases page](https://github.com/Tauseef666-ctrl/NP-Desktop/releases). -2. Open the latest release (currently **v0.25.8**). +2. Open the latest release (currently **v0.26.0**). 3. Download the file for your platform: | Platform | File | Notes | | --- | --- | --- | | Windows 10/11 (x64) | `NP-Desktop-.msi` | Bundles a JRE and the VLC libraries — no separate installs needed | -| Debian/Ubuntu (amd64) | `np-desktop__amd64.deb` | Requires the `vlc` package (installed automatically by apt) | -| Any Linux (x64) | `np-desktop--linux-x64.tar.gz` | Portable app image; requires `vlc` from your distribution, updates itself in-app | +| Debian/Ubuntu (amd64) | `np-desktop__amd64.deb` | Bundles a JRE and the playback runtime — no separate VLC install | +| Any Linux (x64) | `np-desktop--linux-x64.tar.gz` | Portable app image; bundles the playback runtime, updates itself in-app | +| Linux (x64, sandboxed) | `np-desktop--x86_64.flatpak` | Flatpak bundle; updates through Flatpak | | Android | `NewPipe_v.apk` | Android phone and Android TV builds | *(Exact filenames can vary slightly between releases — use the file listed on the release page.)* @@ -38,6 +39,7 @@ or: ```bash sha256sum np-desktop__amd64.deb sha256sum np-desktop--linux-x64.tar.gz +sha256sum np-desktop--x86_64.flatpak ``` Compare the output with the corresponding checksum file attached to the release. If they do not match, re-download the file; if the mismatch persists, do not install it and open an issue. @@ -76,7 +78,7 @@ Unsigned installers are occasionally matched by generic signatures such as `Troj ## Linux Installation (Debian/Ubuntu) -**Prerequisites:** a Debian-based distribution on amd64, plus the `vlc` package. The package bundles its own JRE and declares `vlc` as a dependency, so `apt` installs the playback runtime automatically. +**Prerequisites:** a Debian-based distribution on amd64. The package bundles its own JRE **and** the playback runtime (libVLC, its plugins and the codec libraries), so you do **not** need to install VLC separately. ```bash sudo apt install ./np-desktop__amd64.deb @@ -97,7 +99,7 @@ The deb package maintainer is `NewPipe e.V. `. ## Linux Installation (any distribution, portable) -On Arch, CachyOS, Fedora, openSUSE and other non-Debian distributions use the portable archive. It is the same app image as the Debian package, without dpkg. **Prerequisite:** the VLC runtime of your distribution (`sudo pacman -S vlc`, `sudo dnf install vlc`, `sudo zypper install vlc`). +On Arch, CachyOS, Fedora, openSUSE and other non-Debian distributions use the portable archive. It is the same app image as the Debian package, without dpkg, and bundles the playback runtime — no VLC package is required. ```bash mkdir -p ~/.local/share/np-desktop ~/.local/bin @@ -121,16 +123,41 @@ StartupNotify=true Replace `` with your user name, then start `np-desktop` once from the terminal to confirm the install. +## Linux Installation (Flatpak) + +The Flatpak bundle is sandboxed and ships the same app image, JRE and playback runtime. It only asks for network, display, audio, GPU and the Downloads/Pictures folders; your home directory is not exposed. + +```bash +flatpak install --user ./np-desktop--x86_64.flatpak +flatpak run io.github.tauseef666_ctrl.NP_Desktop +``` + +If a signed repository is published for the release, install it once and let Flatpak handle updates: + +```bash +flatpak remote-add --user --if-not-exists np-desktop \ + https://tauseef666-ctrl.github.io/NP-Desktop/flatpak/io.github.tauseef666_ctrl.NP_Desktop.flatpakrepo +flatpak install --user np-desktop io.github.tauseef666_ctrl.NP_Desktop +flatpak update io.github.tauseef666_ctrl.NP_Desktop +``` + +Inside Flatpak the in-app updater is disabled; updates come from `flatpak update`. + ### In-app updates NP Desktop updates itself from the release channel: - **Portable install (above):** the app downloads `np-desktop--linux-x64.tar.gz`, verifies the SHA-256 checksum, stages it next to the running installation, restarts and swaps the directory. No root password is needed and nothing outside `~/.local/share/np-desktop` is touched. - **Debian package:** the update downloads the `.deb` and hands it to your software installer (or `pkexec dpkg -i`), which asks for the administrator password. +- **Flatpak:** the app detects the sandbox and points you to `flatpak update`; it never tries to replace files under `/app`. - **Other layouts:** when the installation directory is not writable (for example a system-wide unpack under `/opt`), the app offers the release page instead, because replacing those files needs administrator rights. ## Troubleshooting +### "The bundled playback engine could not be loaded" on Linux + +The packaged app extracts its libVLC runtime into `~/.local/share/NP-Desktop/vlc` (or the Flatpak data directory) on first launch. If that directory is not writable, extract it manually by setting `NEWPIPE_VLC_PATH` to a directory that contains `libvlc.so` and a `plugins/` folder, or reinstall the package. A system VLC installation is only used as a development fallback. + ### "Failed to launch JVM" on Windows The packaged application bundles every JDK module specifically to prevent this error, so it should not occur. If you see it, download the installer again, verify the checksum, and reinstall. If the problem persists, open an issue on the [issue tracker](https://github.com/Tauseef666-ctrl/NP-Desktop/issues). @@ -145,13 +172,11 @@ Verify the SHA-256 hash of the original download against the release checksum. I ### "libVLC is not available" on Linux -The Debian package uses the system VLC runtime. Install it and restart the app: - -```bash -sudo apt install vlc -``` +Every official Linux package (`.deb`, portable tarball, Flatpak) bundles the playback runtime, so a system VLC installation is not required. If the message appears, the bundled runtime failed to extract or load: -If you installed the package with `dpkg -i` instead of `apt install ./...`, run `sudo apt -f install` once to pull in the dependencies. +1. Check that `~/.local/share/NP-Desktop/vlc` (or `~/.var/app/io.github.tauseef666_ctrl.NP_Desktop/data/NP-Desktop/vlc` inside Flatpak) exists and is readable. +2. If it is missing or incomplete, delete that directory and restart the app so it extracts the runtime again. +3. For a development build without a bundled runtime, point `NEWPIPE_VLC_PATH` at a libVLC installation. ## Build From Source diff --git a/README.md b/README.md index 95f7a95d1..b6395185b 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ A few of the problems this project solves that go beyond wrapping a media player ## Installation -Download the latest installer from the [Releases](https://github.com/Tauseef666-ctrl/NP-Desktop/releases) page — `.msi` for Windows, `.deb` for Debian/Ubuntu, the portable `linux-x64.tar.gz` for every other Linux distribution, or an Android APK. SHA-256 checksums are published alongside each release, and the desktop builds update themselves in-app. +Download the latest installer from the [Releases](https://github.com/Tauseef666-ctrl/NP-Desktop/releases) page — `.msi` for Windows, `.deb` for Debian/Ubuntu, the portable `linux-x64.tar.gz` for every other Linux distribution, a `.flatpak` bundle for a sandboxed install, or an Android APK. The desktop packages bundle their own JRE and playback runtime, so VLC and Java are **not** separate prerequisites. SHA-256 checksums are published alongside each release, and the desktop builds update themselves in-app (Flatpak installs update through `flatpak update`). Step-by-step instructions, including how to handle the Windows SmartScreen warning for unsigned installers, are in [INSTALL.md](INSTALL.md). @@ -115,6 +115,7 @@ Step-by-step instructions, including how to handle the Windows SmartScreen warni - JDK 21 - Git - Android SDK (for Android builds only) +- Linux packaging: `libvlc5`, `libvlccore9`, `vlc-plugin-base`, `patchelf` 0.19.3 or newer, `ffmpeg` (for the playback smoke test) ### Clone @@ -140,7 +141,15 @@ gradlew.bat --no-configuration-cache :desktopApp:createDistributable Debian/Ubuntu package: ```bash -./gradlew --no-configuration-cache :desktopApp:packageDeb +packaging/linux/build-vlc-runtime.sh build/vlc-runtime +./gradlew --no-configuration-cache :desktopApp:packageDeb -PvlcPrefix="$PWD/build/vlc-runtime" +``` + +Flatpak bundle: + +```bash +./gradlew --no-configuration-cache :desktopApp:createReleaseDistributable -PvlcPrefix="$PWD/build/vlc-runtime" +packaging/flatpak/build-flatpak.sh desktopApp/build/compose/binaries/main-release/app/NP-Desktop 0.26.0 ``` Portable app image (any distribution): diff --git a/SECURITY.md b/SECURITY.md index 6720f856a..12f255d54 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -9,7 +9,7 @@ | Version | Supported | | --- | --- | -| Latest release of the v0.25.x series (currently v0.25.8) | Yes | +| Latest release of the v0.26.x series (currently v0.26.0) | Yes | | Older releases | No — please upgrade to the latest release | ## Reporting a Vulnerability diff --git a/buildSrc/src/main/kotlin/ProjectConfig.kt b/buildSrc/src/main/kotlin/ProjectConfig.kt index a35820349..58479209c 100644 --- a/buildSrc/src/main/kotlin/ProjectConfig.kt +++ b/buildSrc/src/main/kotlin/ProjectConfig.kt @@ -9,7 +9,7 @@ const val NEWPIPE_VERSION_SDK_MIN = 23 const val NEWPIPE_VERSION_SDK_TARGET = 35 const val NEWPIPE_VERSION_CODE = 1016 -const val NEWPIPE_VERSION_NAME = "0.25.8" +const val NEWPIPE_VERSION_NAME = "0.26.0" const val NEWPIPE_APPLICATION_ID_OLD = "org.schabi.newpipe" const val NEWPIPE_APPLICATION_ID_NEW = "net.newpipe.app" diff --git a/buildSrc/src/main/kotlin/VlcBundleTask.kt b/buildSrc/src/main/kotlin/VlcBundleTask.kt index 4975fef3b..c3c0aabcc 100644 --- a/buildSrc/src/main/kotlin/VlcBundleTask.kt +++ b/buildSrc/src/main/kotlin/VlcBundleTask.kt @@ -51,7 +51,11 @@ abstract class VlcBundleTask : DefaultTask() { fun bundle() { val destination = outputDir.get().asFile.apply { mkdirs() } val source = vlcRoot.orNull?.asFile - val usable = source != null && source.resolve("libvlc.dll").isFile + val nativeLibrary = source?.let { directory -> + listOf("libvlc.dll", "libvlc.so", "libvlc.dylib") + .firstOrNull { name -> File(directory, name).isFile } + } + val usable = source != null && nativeLibrary != null if (!usable) { // Development runs and CI without a provisioned libVLC still succeed; the @@ -73,6 +77,14 @@ abstract class VlcBundleTask : DefaultTask() { } } + // The locator compares this marker with the marker of the extracted copy, so a new + // application build re-extracts a changed runtime and an unchanged one is reused. + val marker = File(destination, "bundle-version.txt") + if (!marker.isFile) { + val library = File(destination, nativeLibrary!!) + marker.writeText("${library.length()}-${library.lastModified()}") + } + zipDirectory(destination, runtimeZip.get().asFile) val bundled = destination.walkTopDown().filter { it.isFile }.count() @@ -90,7 +102,15 @@ abstract class VlcBundleTask : DefaultTask() { if (parent != null) parent.mkdirs() ZipOutputStream(target.outputStream().buffered()).use { zip -> - source.walkTopDown().filter { it.isFile }.forEach { file -> + // The version marker must be the first entry: the locator reads it without + // unpacking the whole archive. + val files = source.walkTopDown() + .filter { it.isFile } + .sortedBy { file -> + val relative = source.toPath().relativize(file.toPath()).toString() + if (relative == "bundle-version.txt") "" else relative + } + files.forEach { file -> val relative = source.toPath().relativize(file.toPath()).toString().replace('\\', '/') val entry = ZipEntry(relative) entry.time = file.lastModified() diff --git a/desktopApp/build.gradle.kts b/desktopApp/build.gradle.kts index ae2116b76..a123776bf 100644 --- a/desktopApp/build.gradle.kts +++ b/desktopApp/build.gradle.kts @@ -27,13 +27,15 @@ dependencies { // Bundled libVLC: the packaged application ships its own copy, so playback does not depend on a // separate VLC installation. The `vlcPrefix` Gradle property, the `VLC_HOME` environment variable -// or the Gradle `vlc-setup` plugin cache are checked, in this order. +// or the Gradle `vlc-setup` plugin cache are checked, in this order. Linux CI passes the directory +// produced by `packaging/linux/build-vlc-runtime.sh` through `-PvlcPrefix`. val vlcSourceDir: String? = sequenceOf( findProperty("vlcPrefix")?.toString(), System.getenv("VLC_HOME"), File(System.getProperty("user.home"), ".gradle/vlcSetup/vlc").absolutePath ).firstOrNull { source -> - source != null && File(source, "libvlc.dll").isFile + source != null && listOf("libvlc.dll", "libvlc.so", "libvlc.dylib") + .any { library -> File(source, library).isFile } } val vlcBundleDir = layout.buildDirectory.dir("compose/vlc-resources") @@ -61,7 +63,7 @@ compose.desktop { nativeDistributions { targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Exe, TargetFormat.Deb) packageName = "NP-Desktop" - packageVersion = "0.25.8" + packageVersion = "0.26.0" description = "NP Desktop - Libre lightweight streaming client" copyright = "\u00a9 2026 NewPipe e.V. Licensed under GPL-3.0-or-later" vendor = "NP Desktop" diff --git a/desktopApp/src/main/kotlin/net/newpipe/app/DesktopVersions.kt b/desktopApp/src/main/kotlin/net/newpipe/app/DesktopVersions.kt index 8118a87b2..3f1ea56e8 100644 --- a/desktopApp/src/main/kotlin/net/newpipe/app/DesktopVersions.kt +++ b/desktopApp/src/main/kotlin/net/newpipe/app/DesktopVersions.kt @@ -17,5 +17,5 @@ package net.newpipe.app */ object DesktopVersions { - const val APP_VERSION = "0.25.8" + const val APP_VERSION = "0.26.0" } diff --git a/desktopApp/src/main/kotlin/net/newpipe/app/Main.kt b/desktopApp/src/main/kotlin/net/newpipe/app/Main.kt index f36753004..1a831985f 100644 --- a/desktopApp/src/main/kotlin/net/newpipe/app/Main.kt +++ b/desktopApp/src/main/kotlin/net/newpipe/app/Main.kt @@ -50,6 +50,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import net.newpipe.app.composable.VideoPlayer import net.newpipe.app.navigation.Destination +import net.newpipe.app.platform.DesktopPaths import net.newpipe.app.platform.PopupWindowBounds import net.newpipe.app.platform.UpdateStatus import net.newpipe.app.platform.applyDarkTitlebarToWindow @@ -76,8 +77,8 @@ fun main() { // A generous image cache: thumbnails are served from memory on revisit and from disk after // a restart, so scrolling through the feed or reopening the app no longer refetches every - // picture. - val cacheRoot = File(System.getenv("APPDATA") ?: System.getProperty("user.home"), "NP-Desktop") + // picture. The XDG cache directory is writable inside a Flatpak sandbox. + val cacheRoot = DesktopPaths.cacheDir() val memory = MemoryCache.Builder() .maxSizeBytes(Runtime.getRuntime().maxMemory() / 4) .build() diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh new file mode 100755 index 000000000..30ae704d9 --- /dev/null +++ b/packaging/flatpak/build-flatpak.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2026 NewPipe e.V. +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Packages a jpackage app image as a Flatpak bundle. +# +# Usage: +# packaging/flatpak/build-flatpak.sh [output-directory] +# +# The app image already contains the JRE and the portable libVLC runtime, so the Flatpak does +# not need a build sandbox: the bundle is exported directly from the prepared app directory. +# The Flatpak runtime only provides the base system (glibc, graphics, audio, Wayland/X11). +# +# Environment: +# FLATPAK_GPG_KEY_ID sign the exported commit with this key (optional) +# FLATPAK_GPG_HOME GnuPG home that contains the key (default: ~/.gnupg) + +set -euo pipefail + +APP_IMAGE=${1:?usage: build-flatpak.sh [output-directory]} +VERSION=${2:?usage: build-flatpak.sh [output-directory]} +OUT=${3:-build/flatpak} + +APP_ID=io.github.tauseef666_ctrl.NP_Desktop +BRANCH=stable +ARCH=x86_64 +RUNTIME=org.freedesktop.Platform/x86_64/24.08 +SDK=org.freedesktop.Sdk/x86_64/24.08 +REPO="$OUT/repo" +STAGE="$OUT/app" + +fail() { + echo "build-flatpak: $*" >&2 + exit 1 +} + +command -v flatpak >/dev/null 2>&1 || fail "flatpak is not installed" +[ -d "$APP_IMAGE" ] || fail "app image not found: $APP_IMAGE" +[ -x "$APP_IMAGE/bin/NP-Desktop" ] || fail "app image has no bin/NP-Desktop" + +rm -rf "$OUT" +mkdir -p "$STAGE/files" "$STAGE/bin" \ + "$STAGE/export/share/applications" \ + "$STAGE/export/share/icons/hicolor/256x256/apps" + +cp -a "$APP_IMAGE/." "$STAGE/files/" + +cat > "$STAGE/bin/np-desktop" <<'EOF' +#!/bin/sh +exec /app/files/bin/NP-Desktop "$@" +EOF +chmod +x "$STAGE/bin/np-desktop" + +cp desktopApp/src/main/resources/app-icon.png \ + "$STAGE/export/share/icons/hicolor/256x256/apps/$APP_ID.png" + +cat > "$STAGE/export/share/applications/$APP_ID.desktop" < "$STAGE/metadata" < "$OUT/$APP_ID.gpg" + cat > "$OUT/$APP_ID.flatpakrepo" < +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Builds a portable libVLC runtime for the Linux desktop app. +# +# The runtime contains libvlc, libvlccore, the VLC plugins and every shared +# library they need, except the C runtime and the GPU driver stack, which must +# come from the host. It is shipped inside the application jar as +# `vlc-runtime.zip` and extracted on first run by VlcNativeLocator, exactly +# like the Windows runtime. +# +# Usage: +# packaging/linux/build-vlc-runtime.sh [output-directory] +# +# Environment: +# VLC_LIB_DIR directory containing libvlc.so.5 (default: multiarch dir) +# VLC_PLUGIN_DIR directory containing the VLC plugins +# VLC_VERSION version string written to bundle-version.txt +# PATCHELF patchelf binary to use (default: patchelf from PATH) +# +# The release workflow runs this on Ubuntu 22.04, which keeps the bundled +# libraries compatible with Debian 12, Ubuntu 22.04 and newer distributions. + +set -euo pipefail + +OUT=${1:-build/vlc-runtime} +LIB_DIR=${VLC_LIB_DIR:-/usr/lib/x86_64-linux-gnu} +PLUGIN_DIR=${VLC_PLUGIN_DIR:-"$LIB_DIR/vlc/plugins"} +PATCHELF=${PATCHELF:-patchelf} + +fail() { + echo "build-vlc-runtime: $*" >&2 + exit 1 +} + +[ -e "$LIB_DIR/libvlc.so.5" ] || fail "libvlc.so.5 not found in $LIB_DIR" +[ -d "$PLUGIN_DIR" ] || fail "VLC plugins not found in $PLUGIN_DIR" + +rm -rf "$OUT" +mkdir -p "$OUT/plugins" + +echo "build-vlc-runtime: staging $LIB_DIR and $PLUGIN_DIR into $OUT" + +# --------------------------------------------------------------------------- +# libVLC and libvlccore +# --------------------------------------------------------------------------- +copy_core_library() { + local name=$1 + local resolved + resolved=$(readlink -f "$LIB_DIR/$name") + [ -f "$resolved" ] || fail "$name could not be resolved" + local real + real=$(basename "$resolved") + cp -f "$resolved" "$OUT/$real" + ln -sf "$real" "$OUT/$name" + # The unversioned name is what JNA loads through jna.library.path. + ln -sf "$name" "$OUT/${name%%.so.*}.so" +} + +copy_core_library libvlc.so.5 +copy_core_library libvlccore.so.9 + +# --------------------------------------------------------------------------- +# Plugins +# --------------------------------------------------------------------------- +cp -a "$PLUGIN_DIR/." "$OUT/plugins/" + +# GUI, output, service discovery and other modules the embedded player does not +# use. Removing them keeps the runtime small and avoids dragging in desktop +# stacks (GTK, Samba, JACK, ...) that are not part of playback. +for category in gui qt skins2 lua visualization services_discovery \ + mux access_output stream_out video_splitter control logger notify; do + rm -rf "$OUT/plugins/$category" +done + +# Access modules: the application plays HTTP(S) URLs and local files. Capture, +# broadcast and network-filesystem access modules are not used. +for plugin in access_alsa access_jack access_mtp access_realrtsp access_srt \ + cdda dc1394 dtv dv1394 dvb dvdnav dvdread ftp libbluray linsys_hdsdi \ + linsys_sdi live555 nfs pulsesrc rist rtp satip sdp sftp shm smb tcp \ + timecode udp v4l2 vcd vdr xcb_screen avio; do + rm -f "$OUT/plugins/access/lib${plugin}_plugin.so" +done + +# MIDI synthesis, audio fingerprinting, scrobbling and the addon manager pull +# in large desktop stacks that the embedded player never uses. +rm -f "$OUT/plugins/codec/libfluidsynth_plugin.so" +rm -f "$OUT/plugins/misc/libaudioscrobbler_plugin.so" +rm -f "$OUT/plugins/misc/libfingerprinter_plugin.so" +rm -f "$OUT/plugins/misc/libaddonsfsstorage_plugin.so" +rm -f "$OUT/plugins/misc/libaddonsvorepository_plugin.so" +rm -f "$OUT/plugins/misc/libexport_plugin.so" +rm -f "$OUT/plugins/misc/libvod_rtsp_plugin.so" +rm -f "$OUT/plugins/misc/liblogger_plugin.so" +rm -f "$OUT/plugins/audio_output/libjack_plugin.so" + +# Text-mode video outputs are not used by the Compose player. +rm -f "$OUT/plugins/video_output/libaa_plugin.so" \ + "$OUT/plugins/video_output/libcaca_plugin.so" \ + "$OUT/plugins/video_output/libfb_plugin.so" + +# The plugin cache stores absolute build paths and mtimes. The extracted copy +# has neither, so VLC would rescan anyway; drop it instead of shipping a stale +# cache. +rm -f "$OUT/plugins/plugins.dat" + +# --------------------------------------------------------------------------- +# Shared library closure +# --------------------------------------------------------------------------- +# The C runtime, the dynamic loader and the GPU driver stack must come from the +# host: bundling glibc or Mesa inside a JVM process is not safe, and the +# graphics stack is tied to the installed kernel driver. +is_host_library() { + case "$1" in + libc.so.*|libm.so.*|libpthread.so.*|libdl.so.*|librt.so.*|\ + libresolv.so.*|libnss_*.so.*|ld-linux*.so.*|linux-vdso.so.*|\ + libcuda.so.*|libnvidia-*.so.*|libOpenCL.so.*|\ + libGL.so.*|libGLX.so.*|libEGL.so.*|libGLESv2.so.*|libgbm.so.*|\ + libdrm.so.*|libvulkan.so.*|libva.so.*|libva-drm.so.*|libva-x11.so.*|\ + libvdpau.so.*) + return 0 + ;; + *) + return 1 + ;; + esac +} + +copy_dependencies() { + local elf=$1 + local library + while IFS= read -r library; do + [ -n "$library" ] || continue + local base + base=$(basename "$library") + is_host_library "$base" && continue + [ -f "$OUT/$base" ] && continue + [ -f "$library" ] || continue + cp -Lf "$library" "$OUT/$base" + done < <(ldd "$elf" 2>/dev/null | awk '/=> \// { print $3 } /^\t\/.*\.so/ { print $1 }') +} + +# Copy dependencies recursively: a copied library can itself need another +# library that is not part of the base system. +for _ in 1 2 3 4 5 6 7 8; do + before=$(find "$OUT" -type f | wc -l) + while IFS= read -r -d '' elf; do + copy_dependencies "$elf" + done < <(find "$OUT" -type f -print0) + after=$(find "$OUT" -type f | wc -l) + [ "$before" = "$after" ] && break +done + +# --------------------------------------------------------------------------- +# RPATH and stripping +# --------------------------------------------------------------------------- +find "$OUT" -type f \( -name '*.so' -o -name '*.so.*' \) \ + -exec strip --strip-unneeded {} + 2>/dev/null || true + +if command -v "$PATCHELF" >/dev/null 2>&1; then + while IFS= read -r -d '' elf; do + file "$elf" 2>/dev/null | grep -q 'ELF' || continue + case "$elf" in + "$OUT/plugins/"*) "$PATCHELF" --set-rpath '$ORIGIN/../..' "$elf" ;; + *) "$PATCHELF" --set-rpath '$ORIGIN' "$elf" ;; + esac + done < <(find "$OUT" -type f -print0) +else + echo "build-vlc-runtime: patchelf not found; the runtime will need LD_LIBRARY_PATH" >&2 +fi + +# --------------------------------------------------------------------------- +# Version marker +# --------------------------------------------------------------------------- +if [ -z "${VLC_VERSION:-}" ]; then + if command -v dpkg-query >/dev/null 2>&1; then + VLC_VERSION=$(dpkg-query -W -f='${Version}' libvlc5 2>/dev/null || true) + elif command -v pacman >/dev/null 2>&1; then + VLC_VERSION=$(pacman -Q libvlc 2>/dev/null | awk '{ print $2 }' || true) + [ -n "$VLC_VERSION" ] || VLC_VERSION=$(pacman -Q vlc 2>/dev/null | awk '{ print $2 }' || true) + fi + VLC_VERSION=${VLC_VERSION:-unknown} +fi +printf 'linux-%s\n' "$VLC_VERSION" > "$OUT/bundle-version.txt" + +echo "build-vlc-runtime: $(find "$OUT" -type f | wc -l) files, $(du -sh "$OUT" | cut -f1)" diff --git a/packaging/linux/smoke-test-vlc.sh b/packaging/linux/smoke-test-vlc.sh new file mode 100755 index 000000000..4685743f4 --- /dev/null +++ b/packaging/linux/smoke-test-vlc.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2026 NewPipe e.V. +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Headless playback test for the libVLC runtime bundled in a jpackage app image. +# +# Usage: +# packaging/linux/smoke-test-vlc.sh [media-file] +# +# The test runs in a fresh HOME and XDG data directory, with every VLC environment variable +# removed, so a system VLC cannot mask a broken bundle. When no media file is passed, a short +# test clip is generated with ffmpeg. + +set -euo pipefail + +APP=${1:?usage: smoke-test-vlc.sh [media-file]} +MEDIA=${2:-} +HERE=$(cd "$(dirname "$0")" && pwd) +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +[ -d "$APP" ] || { + echo "smoke-test-vlc: app image not found: $APP" >&2 + exit 1 +} +[ -f "$APP/lib/app/desktopApp.jar" ] || { + echo "smoke-test-vlc: $APP does not look like a packaged app image" >&2 + exit 1 +} + +if [ -z "$MEDIA" ]; then + command -v ffmpeg >/dev/null 2>&1 || { + echo "smoke-test-vlc: ffmpeg is required to generate the test clip" >&2 + exit 1 + } + MEDIA="$WORK/test.mp4" + ffmpeg -y -loglevel error \ + -f lavfi -i testsrc=duration=4:size=320x240:rate=30 \ + -f lavfi -i sine=frequency=440:duration=4 \ + -c:v libx264 -preset ultrafast -pix_fmt yuv420p -c:a aac -shortest \ + "$MEDIA" +fi + +mkdir -p "$WORK/home" "$WORK/data" "$WORK/classes" +javac -cp "$APP/lib/app/*" -d "$WORK/classes" "$HERE/smoke/VlcBundleSmoke.java" + +env -u VLC_PLUGIN_PATH -u NEWPIPE_VLC_PATH -u LD_LIBRARY_PATH \ + XDG_DATA_HOME="$WORK/data" HOME="$WORK/home" \ + java -cp "$WORK/classes:$APP/lib/app/*" VlcBundleSmoke "$MEDIA" + +test -f "$WORK/data/NP-Desktop/vlc/libvlc.so" +test -d "$WORK/data/NP-Desktop/vlc/plugins" +echo "smoke-test-vlc: bundled runtime extracted and played $MEDIA" diff --git a/packaging/linux/smoke/VlcBundleSmoke.java b/packaging/linux/smoke/VlcBundleSmoke.java new file mode 100644 index 000000000..f5104f8ac --- /dev/null +++ b/packaging/linux/smoke/VlcBundleSmoke.java @@ -0,0 +1,55 @@ +import java.io.File; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import net.newpipe.app.service.VlcNativeLocator; +import uk.co.caprica.vlcj.factory.MediaPlayerFactory; +import uk.co.caprica.vlcj.player.base.MediaPlayer; +import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter; + +/** + * Headless smoke test for the libVLC runtime that ships inside the application jar. + * + * The test runs with an empty XDG data directory, so VlcNativeLocator has to extract the + * bundled runtime and libVLC has to decode the sample without any system VLC installation. + */ +public final class VlcBundleSmoke { + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("usage: VlcBundleSmoke "); + System.exit(2); + } + String media = args[0]; + File directory = VlcNativeLocator.INSTANCE.locate(); + File plugins = VlcNativeLocator.INSTANCE.pluginDirectory(); + System.out.println("locate()=" + directory); + System.out.println("pluginDirectory()=" + plugins); + if (directory == null || plugins == null) { + System.out.println("RESULT no bundled libVLC"); + System.exit(1); + } + String dataHome = System.getenv("XDG_DATA_HOME"); + if (dataHome != null && !directory.getAbsolutePath().startsWith(dataHome)) { + System.out.println("RESULT libVLC was not loaded from the bundled runtime"); + System.exit(1); + } + + MediaPlayerFactory factory = new MediaPlayerFactory( + "--no-video-title-show", "--vout=dummy", "--aout=dummy", "--quiet"); + MediaPlayer player = factory.mediaPlayers().newMediaPlayer(); + CountDownLatch latch = new CountDownLatch(1); + player.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() { + @Override public void timeChanged(MediaPlayer mp, long time) { + if (time >= 1000L) latch.countDown(); + } + @Override public void finished(MediaPlayer mp) { latch.countDown(); } + @Override public void error(MediaPlayer mp) { latch.countDown(); } + }); + boolean started = player.media().play(media); + boolean played = latch.await(30L, TimeUnit.SECONDS); + System.out.println("RESULT started=" + started + " played=" + played + + " state=" + player.status().state() + " time=" + player.status().time()); + player.release(); + factory.release(); + System.exit(started && played ? 0 : 1); + } +} diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index 9f93fa9ec..a84aea84c 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -170,6 +170,7 @@ kotlin { val jvmTest by getting { dependencies { implementation(compose.desktop.currentOs) + implementation(libs.jetbrains.coroutines.test) } } } diff --git a/shared/src/androidMain/kotlin/net/newpipe/app/service/AndroidContentRepository.kt b/shared/src/androidMain/kotlin/net/newpipe/app/service/AndroidContentRepository.kt index c5f3b8ca9..1b868873a 100644 --- a/shared/src/androidMain/kotlin/net/newpipe/app/service/AndroidContentRepository.kt +++ b/shared/src/androidMain/kotlin/net/newpipe/app/service/AndroidContentRepository.kt @@ -56,6 +56,19 @@ class AndroidContentRepository : ContentRepository { override suspend fun playlist(serviceId: Int, url: String): net.newpipe.app.model.PlaylistDetails = throw unsupported() + override suspend fun comments( + serviceId: Int, + url: String, + page: Int + ): net.newpipe.app.model.CommentsPage = throw unsupported() + + override suspend fun commentReplies( + serviceId: Int, + streamUrl: String, + commentId: String, + page: Int + ): net.newpipe.app.model.CommentsPage = throw unsupported() + override suspend fun suggest(query: String): List = emptyList() override suspend fun resolveUrl(url: String): net.newpipe.app.model.ResolvedContent = diff --git a/shared/src/commonMain/composeResources/drawable/ic_comment.xml b/shared/src/commonMain/composeResources/drawable/ic_comment.xml new file mode 100644 index 000000000..d11783f84 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_comment.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_expand_less.xml b/shared/src/commonMain/composeResources/drawable/ic_expand_less.xml new file mode 100644 index 000000000..ed419979c --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_expand_less.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_expand_more.xml b/shared/src/commonMain/composeResources/drawable/ic_expand_more.xml new file mode 100644 index 000000000..ee6f6c432 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_expand_more.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_favorite.xml b/shared/src/commonMain/composeResources/drawable/ic_favorite.xml new file mode 100644 index 000000000..ccbb0c7ee --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_favorite.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_push_pin.xml b/shared/src/commonMain/composeResources/drawable/ic_push_pin.xml new file mode 100644 index 000000000..3e01a2a66 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_push_pin.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_thumb_up.xml b/shared/src/commonMain/composeResources/drawable/ic_thumb_up.xml new file mode 100644 index 000000000..859433012 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_thumb_up.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_verified.xml b/shared/src/commonMain/composeResources/drawable/ic_verified.xml new file mode 100644 index 000000000..0e5650314 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_verified.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/model/Comment.kt b/shared/src/commonMain/kotlin/net/newpipe/app/model/Comment.kt new file mode 100644 index 000000000..19c4ae43a --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/model/Comment.kt @@ -0,0 +1,47 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.model + +/** + * A single comment below a stream. + * + * The model is read-only on purpose: NP Desktop shows comments like NewPipe does, but posting, + * editing, deleting and liking require a signed-in account and are not supported. + */ +data class CommentItem( + /** A stable identifier, used as the list key and for loading replies. */ + val id: String, + val author: String, + val authorUrl: String? = null, + val authorAvatarUrl: String? = null, + val text: String, + val uploadDate: String? = null, + /** `null` when the service does not expose the exact number. */ + val likeCount: Int? = null, + /** The service's own compact representation, for example `1.2K`. */ + val textualLikeCount: String? = null, + /** `null` when the service does not expose the number of replies. */ + val replyCount: Int? = null, + val isPinned: Boolean = false, + val isHeartedByUploader: Boolean = false, + val isUploaderVerified: Boolean = false, + /** The playback position the comment refers to, in seconds; `null` when it has none. */ + val streamPositionSeconds: Int? = null, + /** Whether the service offers replies for this comment. */ + val hasReplies: Boolean = false +) + +/** + * One page of comments. + * + * @param commentsDisabled whether the uploader disabled comments for the stream + * @param hasMore whether another page can be requested + */ +data class CommentsPage( + val comments: List = emptyList(), + val hasMore: Boolean = false, + val commentsDisabled: Boolean = false +) diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt b/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt index 80090f2ca..5859aea9c 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt @@ -61,6 +61,12 @@ sealed interface UpdateStatus { /** The latest release does not ship an installer for the running platform. */ data object NotAvailable : UpdateStatus + /** + * Updates are managed outside the app, for example by Flatpak. The message explains the + * command the user has to run; the app never downloads or replaces its own files. + */ + data class Managed(val message: String) : UpdateStatus + /** An installer download is running; see the sibling progress flow. */ data object Downloading : UpdateStatus diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/UpdateSettingsScreen.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/UpdateSettingsScreen.kt index 9cf166ec6..89fa42c8b 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/UpdateSettingsScreen.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/UpdateSettingsScreen.kt @@ -166,6 +166,8 @@ private fun buildStatusSummary(status: UpdateStatus, currentVersion: String?): S UpdateStatus.NotAvailable -> "The latest release does not ship an update for this platform yet" + is UpdateStatus.Managed -> status.message + UpdateStatus.Downloading -> "Downloading the update\u2026" UpdateStatus.Installing -> "Preparing the update\u2026" is UpdateStatus.Installed -> diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/StreamScreen.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/StreamScreen.kt index 005ab6e5c..a2bb49f43 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/StreamScreen.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/StreamScreen.kt @@ -90,6 +90,14 @@ fun StreamScreen( val relatedItems by viewModel.relatedItems.collectAsState() val loadingMoreRelated by viewModel.loadingMoreRelated.collectAsState() val hasMoreRelated by viewModel.hasMoreRelated.collectAsState() + val comments by viewModel.comments.collectAsState() + val commentsLoading by viewModel.commentsLoading.collectAsState() + val commentsLoaded by viewModel.commentsLoaded.collectAsState() + val commentsError by viewModel.commentsError.collectAsState() + val commentsDisabled by viewModel.commentsDisabled.collectAsState() + val hasMoreComments by viewModel.hasMoreComments.collectAsState() + val loadingMoreComments by viewModel.loadingMoreComments.collectAsState() + val commentReplies by viewModel.commentReplies.collectAsState() val playbackState by playbackController.state.collectAsState() // Derived so the four-times-a-second position tick never recomposes this screen: only the // small seek row inside the player handles the moving position. @@ -403,6 +411,14 @@ fun StreamScreen( relatedItems = relatedItems, loadingMoreRelated = loadingMoreRelated, hasMoreRelated = hasMoreRelated, + comments = comments, + commentsLoading = commentsLoading, + commentsLoaded = commentsLoaded, + commentsError = commentsError, + commentsDisabled = commentsDisabled, + hasMoreComments = hasMoreComments, + loadingMoreComments = loadingMoreComments, + commentReplies = commentReplies, onToggleImmersive = { playerUiState.toggleFullscreen() }, onClosePlayer = playbackController::clear, onNext = if (hasNext) skipToNext else null, @@ -412,6 +428,15 @@ fun StreamScreen( null }, onLoadMoreRelated = viewModel::loadMoreRelated, + onLoadMoreComments = viewModel::loadMoreComments, + onRetryComments = viewModel::retryComments, + onToggleCommentReplies = viewModel::toggleCommentReplies, + onLoadMoreCommentReplies = viewModel::loadMoreCommentReplies, + onOpenCommentAuthor = { authorUrl -> + navigator.navigateTo( + Destination.Channel(streamDetails.serviceId, authorUrl) + ) + }, onSelectVideo = selectVideo, onSelectAudio = selectAudio, onPlay = { diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt index 6b30a5f3d..65ce4cffd 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt @@ -79,6 +79,7 @@ import net.newpipe.app.composable.ContentThumbnail import net.newpipe.app.composable.VideoActionsMenuHost import net.newpipe.app.composable.VideoPlayer import net.newpipe.app.model.ChannelDetails +import net.newpipe.app.model.CommentItem import net.newpipe.app.model.ContentItem import net.newpipe.app.model.ContentType import net.newpipe.app.model.MediaStream @@ -96,8 +97,13 @@ import net.newpipe.app.ui.trackTextFieldFocus import net.newpipe.app.util.formatDuration import net.newpipe.app.util.formatSubscriberCount import net.newpipe.app.util.formatViewCount +import net.newpipe.app.viewmodel.stream.CommentRepliesState import newpipe.shared.generated.resources.Res import newpipe.shared.generated.resources.ic_close +import newpipe.shared.generated.resources.ic_comment +import newpipe.shared.generated.resources.ic_expand_less +import newpipe.shared.generated.resources.ic_expand_more +import newpipe.shared.generated.resources.ic_favorite import newpipe.shared.generated.resources.ic_file_download import newpipe.shared.generated.resources.ic_headset import newpipe.shared.generated.resources.ic_link @@ -105,7 +111,10 @@ import newpipe.shared.generated.resources.ic_more_vert import newpipe.shared.generated.resources.ic_picture_in_picture import newpipe.shared.generated.resources.ic_open_in_new import newpipe.shared.generated.resources.ic_playlist_add +import newpipe.shared.generated.resources.ic_push_pin import newpipe.shared.generated.resources.ic_subscriptions +import newpipe.shared.generated.resources.ic_thumb_up +import newpipe.shared.generated.resources.ic_verified import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.painterResource import org.koin.compose.koinInject @@ -117,9 +126,9 @@ import org.koin.compose.koinInject * videos scroll independently in a narrower column on the right. On narrow windows everything is * stacked in a single scrolling column so the player keeps as much width as possible. * - * Only controls backed by the extraction engine are shown: copying the link, opening the channel - * and opening the stream in the browser. The extraction engine offers no comments, likes or - * subscriptions for the desktop build, so those elements are deliberately absent. + * Only controls backed by the extraction engine are shown: copying the link, opening the channel, + * opening the stream in the browser and reading the comments. Comments are read-only, exactly + * like NewPipe's: posting, editing, deleting and liking require an account and are not supported. */ @Composable internal fun WatchPage( @@ -131,12 +140,25 @@ internal fun WatchPage( relatedItems: List, loadingMoreRelated: Boolean, hasMoreRelated: Boolean, + comments: List, + commentsLoading: Boolean, + commentsLoaded: Boolean, + commentsError: String?, + commentsDisabled: Boolean, + hasMoreComments: Boolean, + loadingMoreComments: Boolean, + commentReplies: Map, modifier: Modifier = Modifier, onToggleImmersive: () -> Unit, onClosePlayer: () -> Unit, onNext: (() -> Unit)?, onPrevious: (() -> Unit)?, onLoadMoreRelated: () -> Unit, + onLoadMoreComments: () -> Unit, + onRetryComments: () -> Unit, + onToggleCommentReplies: (CommentItem) -> Unit, + onLoadMoreCommentReplies: (String) -> Unit, + onOpenCommentAuthor: (String) -> Unit, onSelectVideo: (MediaStream) -> Unit, onSelectAudio: (MediaStream) -> Unit, onPlay: () -> Unit, @@ -196,6 +218,24 @@ internal fun WatchPage( onOpenPopup = onOpenPopup, onDownload = onDownload ) + + CommentsSection( + comments = comments, + loading = commentsLoading, + loaded = commentsLoaded, + error = commentsError, + disabled = commentsDisabled, + hasMore = hasMoreComments, + loadingMore = loadingMoreComments, + replies = commentReplies, + onLoadMore = onLoadMoreComments, + onRetry = onRetryComments, + onToggleReplies = onToggleCommentReplies, + onLoadMoreReplies = onLoadMoreCommentReplies, + onOpenAuthor = onOpenCommentAuthor, + onSeekTo = onSeekTo, + modifier = Modifier.padding(top = Spacing.xl, bottom = Spacing.lg) + ) } RelatedPanel( @@ -262,6 +302,26 @@ internal fun WatchPage( ) } + item(key = "comments") { + CommentsSection( + comments = comments, + loading = commentsLoading, + loaded = commentsLoaded, + error = commentsError, + disabled = commentsDisabled, + hasMore = hasMoreComments, + loadingMore = loadingMoreComments, + replies = commentReplies, + onLoadMore = onLoadMoreComments, + onRetry = onRetryComments, + onToggleReplies = onToggleCommentReplies, + onLoadMoreReplies = onLoadMoreCommentReplies, + onOpenAuthor = onOpenCommentAuthor, + onSeekTo = onSeekTo, + modifier = Modifier.padding(bottom = Spacing.lg) + ) + } + item(key = "related-header") { RelatedHeader( modifier = Modifier.padding(top = Spacing.xl, bottom = Spacing.sm) @@ -806,6 +866,469 @@ private fun StreamDetails.toContentItem() = ContentItem( liveNow = liveNow ) +/** + * The read-only comments below a stream: pagination, replies and the service's own markers. + * + * The section never offers a composer or a like button, because both would require a signed-in + * account. Timestamps inside comments seek the player like timestamps in the description do. + */ +@Composable +private fun CommentsSection( + comments: List, + loading: Boolean, + loaded: Boolean, + error: String?, + disabled: Boolean, + hasMore: Boolean, + loadingMore: Boolean, + replies: Map, + onLoadMore: () -> Unit, + onRetry: () -> Unit, + onToggleReplies: (CommentItem) -> Unit, + onLoadMoreReplies: (String) -> Unit, + onOpenAuthor: (String) -> Unit, + onSeekTo: (Long) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier = modifier.fillMaxWidth()) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + Icon( + painter = painterResource(Res.drawable.ic_comment), + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + text = "Comments", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold + ) + } + + Spacer(modifier = Modifier.size(Spacing.sm)) + + val empty = comments.isEmpty() + when { + (loading || !loaded) && empty -> CommentStatus( + text = "Loading comments\u2026", + loading = true + ) + + error != null && empty -> CommentStatus( + text = error, + onRetry = onRetry + ) + + disabled -> CommentStatus( + text = "Comments are disabled for this video." + ) + + loaded && empty -> CommentStatus( + text = "No comments yet." + ) + + else -> { + comments.forEachIndexed { index, comment -> + if (index > 0) { + Spacer( + modifier = Modifier + .fillMaxWidth() + .height(1.dp) + .background(MaterialTheme.colorScheme.outlineVariant) + ) + } + CommentThread( + comment = comment, + replies = replies, + onToggleReplies = onToggleReplies, + onLoadMoreReplies = onLoadMoreReplies, + onOpenAuthor = onOpenAuthor, + onSeekTo = onSeekTo + ) + } + + if (error != null && !empty) { + CommentStatus( + text = error, + onRetry = onRetry, + modifier = Modifier.padding(top = Spacing.sm) + ) + } + + if (hasMore) { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(top = Spacing.sm), + contentAlignment = Alignment.Center + ) { + if (loadingMore) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + strokeWidth = 2.dp + ) + } else { + TextButton(onClick = onLoadMore) { + Text("Load more comments") + } + } + } + } else { + Text( + text = "No more comments", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = Spacing.md) + ) + } + } + } + } +} + +/** + * A single comment with its author, markers, body and replies. + */ +@Composable +private fun CommentThread( + comment: CommentItem, + replies: Map, + onToggleReplies: (CommentItem) -> Unit, + onLoadMoreReplies: (String) -> Unit, + onOpenAuthor: (String) -> Unit, + onSeekTo: (Long) -> Unit, + depth: Int = 0 +) { + val replyState = replies[comment.id] + val authorClick = comment.authorUrl?.let { url -> + Modifier.clickable { onOpenAuthor(url) } + } ?: Modifier + val linkStyle = SpanStyle( + color = MaterialTheme.colorScheme.primary, + textDecoration = TextDecoration.Underline + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .padding( + start = if (depth == 0) 0.dp else 40.dp, + top = if (depth == 0) Spacing.md else Spacing.sm, + bottom = Spacing.sm + ), + verticalAlignment = Alignment.Top + ) { + CommentAvatar( + avatarUrl = comment.authorAvatarUrl, + name = comment.author, + sizeDp = if (depth == 0) 36 else 28 + ) + + Column( + modifier = Modifier + .weight(1f) + .padding(start = Spacing.md) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = comment.author, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + modifier = authorClick + ) + + if (comment.isUploaderVerified) { + Icon( + painter = painterResource(Res.drawable.ic_verified), + contentDescription = "Verified", + modifier = Modifier + .padding(start = 4.dp) + .size(14.dp), + tint = MaterialTheme.colorScheme.primary + ) + } + + comment.uploadDate?.let { date -> + Text( + text = date, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = Spacing.sm) + ) + } + } + + if (comment.isPinned || comment.isHeartedByUploader) { + Row( + modifier = Modifier.padding(top = 2.dp), + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + if (comment.isPinned) { + CommentBadge(Res.drawable.ic_push_pin, "Pinned by creator") + } + if (comment.isHeartedByUploader) { + CommentBadge(Res.drawable.ic_favorite, "Liked by creator") + } + } + } + + if (comment.text.isNotBlank()) { + Spacer(modifier = Modifier.size(Spacing.xs)) + SelectionContainer { + Text( + text = annotateTextWithLinks( + text = comment.text, + linkStyle = linkStyle, + onSeekTo = onSeekTo + ), + style = MaterialTheme.typography.bodyMedium + ) + } + } + + Row( + modifier = Modifier.padding(top = Spacing.xs), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.md) + ) { + comment.streamPositionSeconds?.let { seconds -> + Text( + text = formatDuration(seconds.toLong()), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { + onSeekTo(seconds * 1_000L) + } + ) + } + + val likeLabel = comment.textualLikeCount + ?: comment.likeCount?.let { formatViewCount(it.toLong()) } + if (likeLabel != null) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Icon( + painter = painterResource(Res.drawable.ic_thumb_up), + contentDescription = null, + modifier = Modifier.size(14.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + text = likeLabel, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + if (comment.hasReplies) { + TextButton( + onClick = { onToggleReplies(comment) }, + contentPadding = PaddingValues(horizontal = Spacing.xs) + ) { + Text( + text = when { + replyState?.loading == true -> "Loading replies\u2026" + replyState?.error != null -> "Retry replies" + replyState?.expanded == true -> "Hide replies" + else -> comment.replyCount?.takeIf { it > 0 } + ?.let { "View $it replies" } + ?: "View replies" + }, + style = MaterialTheme.typography.labelMedium + ) + Icon( + painter = painterResource( + if (replyState?.expanded == true) { + Res.drawable.ic_expand_less + } else { + Res.drawable.ic_expand_more + } + ), + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + } + } + } + + if (replyState?.expanded == true) { + if (replyState.loading && replyState.items.isEmpty()) { + Row( + modifier = Modifier.padding(start = Spacing.sm, top = Spacing.xs), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp + ) + Text( + text = "Loading replies\u2026", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + replyState.error?.let { message -> + Text( + text = message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(start = Spacing.sm, top = Spacing.xs) + ) + } + + replyState.items.forEach { reply -> + if (depth < 2) { + CommentThread( + comment = reply, + replies = replies, + onToggleReplies = onToggleReplies, + onLoadMoreReplies = onLoadMoreReplies, + onOpenAuthor = onOpenAuthor, + onSeekTo = onSeekTo, + depth = depth + 1 + ) + } + } + + if (replyState.hasMore) { + TextButton( + onClick = { onLoadMoreReplies(comment.id) }, + contentPadding = PaddingValues(horizontal = Spacing.xs), + modifier = Modifier.padding(start = 32.dp) + ) { + Text( + text = if (replyState.loading) { + "Loading more replies\u2026" + } else { + "Load more replies" + }, + style = MaterialTheme.typography.labelMedium + ) + } + } + } + } + } +} + +/** + * The author avatar of a comment with a letter fallback while the image is missing. + */ +@Composable +private fun CommentAvatar( + avatarUrl: String?, + name: String, + sizeDp: Int +) { + Box( + modifier = Modifier + .size(sizeDp.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHighest), + contentAlignment = Alignment.Center + ) { + if (avatarUrl != null) { + AsyncImage( + model = avatarUrl, + contentDescription = name, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Crop + ) + } else { + Text( + text = name.take(1).uppercase(), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +/** + * A small marker such as "Pinned by creator". + */ +@Composable +private fun CommentBadge( + icon: DrawableResource, + label: String +) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp) + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.size(12.dp), + tint = MaterialTheme.colorScheme.primary + ) + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary + ) + } +} + +/** + * A placeholder or error state of the comments section. + */ +@Composable +private fun CommentStatus( + text: String, + loading: Boolean = false, + onRetry: (() -> Unit)? = null, + modifier: Modifier = Modifier +) { + Surface( + modifier = modifier.fillMaxWidth(), + color = MaterialTheme.colorScheme.surfaceContainerLow, + shape = RoundedCornerShape(Radius.md) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(Spacing.lg), + verticalArrangement = Arrangement.spacedBy(Spacing.xs) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + if (loading) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp + ) + } + Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + if (onRetry != null) { + TextButton( + onClick = onRetry, + contentPadding = PaddingValues(0.dp) + ) { + Text("Retry") + } + } + } + } +} + /** * The description panel: metadata, the description and an expand action. */ @@ -853,8 +1376,8 @@ private fun DescriptionPanel( SelectionContainer { Text( - text = annotateDescription( - description = description, + text = annotateTextWithLinks( + text = description, linkStyle = linkStyle, onSeekTo = onSeekTo ), @@ -878,18 +1401,18 @@ private fun DescriptionPanel( } /** - * Marks urls and timestamps in the description as links, so they can be opened or used to seek. + * Marks urls and timestamps in a text as links, so they can be opened or used to seek. */ -private fun annotateDescription( - description: String, +private fun annotateTextWithLinks( + text: String, linkStyle: SpanStyle, onSeekTo: (Long) -> Unit ): AnnotatedString = buildAnnotatedString { - append(description) + append(text) val styles = TextLinkStyles(style = linkStyle) - URL_PATTERN.findAll(description).forEach { match -> + URL_PATTERN.findAll(text).forEach { match -> addLink( LinkAnnotation.Url( url = match.value, @@ -900,7 +1423,7 @@ private fun annotateDescription( ) } - TIMESTAMP_PATTERN.findAll(description).forEach { match -> + TIMESTAMP_PATTERN.findAll(text).forEach { match -> val positionMs = parseTimestamp(match.value) ?: return@forEach addLink( LinkAnnotation.Clickable( diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/service/ContentRepository.kt b/shared/src/commonMain/kotlin/net/newpipe/app/service/ContentRepository.kt index 9167e0ec1..2c6b6bd3f 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/service/ContentRepository.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/service/ContentRepository.kt @@ -6,6 +6,8 @@ package net.newpipe.app.service import net.newpipe.app.model.ChannelDetails +import net.newpipe.app.model.CommentItem +import net.newpipe.app.model.CommentsPage import net.newpipe.app.model.ContentItem import net.newpipe.app.model.PlaylistDetails import net.newpipe.app.model.ResolvedContent @@ -90,6 +92,27 @@ interface ContentRepository { */ suspend fun playlist(serviceId: Int, url: String): PlaylistDetails + /** + * Loads one page of the comments below a stream. + * + * @param page zero based page index + */ + suspend fun comments(serviceId: Int, url: String, page: Int = 0): CommentsPage + + /** + * Loads one page of the replies to a top-level comment. + * + * @param streamUrl the url of the stream the comment belongs to + * @param commentId the [CommentItem.id] of the top-level comment + * @param page zero based page index + */ + suspend fun commentReplies( + serviceId: Int, + streamUrl: String, + commentId: String, + page: Int = 0 + ): CommentsPage + /** * Suggests completions for a search query. Returns an empty list when unsupported. */ diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModel.kt b/shared/src/commonMain/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModel.kt index e1ab37377..5a27f3af3 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModel.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModel.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import com.russhwolf.settings.Settings import net.newpipe.app.model.ChannelDetails +import net.newpipe.app.model.CommentItem import net.newpipe.app.model.ContentItem import net.newpipe.app.model.ContentType import net.newpipe.app.model.MediaStream @@ -60,6 +61,33 @@ class StreamViewModel( private val _hasMoreRelated = MutableStateFlow(true) val hasMoreRelated = _hasMoreRelated.asStateFlow() + private val _comments = MutableStateFlow>(emptyList()) + val comments = _comments.asStateFlow() + + private val _commentsLoading = MutableStateFlow(false) + val commentsLoading = _commentsLoading.asStateFlow() + + private val _commentsLoaded = MutableStateFlow(false) + val commentsLoaded = _commentsLoaded.asStateFlow() + + private val _commentsError = MutableStateFlow(null) + val commentsError = _commentsError.asStateFlow() + + private val _commentsDisabled = MutableStateFlow(false) + val commentsDisabled = _commentsDisabled.asStateFlow() + + private val _hasMoreComments = MutableStateFlow(false) + val hasMoreComments = _hasMoreComments.asStateFlow() + + private val _loadingMoreComments = MutableStateFlow(false) + val loadingMoreComments = _loadingMoreComments.asStateFlow() + + private val _commentReplies = MutableStateFlow>(emptyMap()) + val commentReplies = _commentReplies.asStateFlow() + + private var commentsPage = 0 + private var commentsGeneration = 0 + private var loadedUrl: String? = null private var loadedServiceId = -1 @@ -74,6 +102,7 @@ class StreamViewModel( loadedUrl = url loadedServiceId = serviceId autoRetries = 0 + resetComments() startLoad(serviceId, url) } @@ -108,6 +137,7 @@ class StreamViewModel( _relatedItems.value = details.relatedItems.distinctBy { it.url } _hasMoreRelated.value = details.uploaderUrl != null _loadingMoreRelated.value = false + startCommentsLoad(serviceId, url) // The uploader chip only needs the channel avatar and subscriber count. It is // loaded outside the critical playback path, so that the video starts as soon @@ -248,6 +278,208 @@ class StreamViewModel( } } + /** + * Loads the next page of comments. The extraction engine only exposes a forward cursor, so + * pages are requested strictly in order. + */ + fun loadMoreComments() { + if (_commentsLoading.value || _loadingMoreComments.value) return + if (!_hasMoreComments.value) return + val details = _details.value ?: return + if (details.url != loadedUrl) return + + val generation = commentsGeneration + _commentsError.value = null + _loadingMoreComments.value = true + + viewModelScope.launch { + try { + val page = repository.comments(details.serviceId, details.url, commentsPage + 1) + if (generation != commentsGeneration || loadedUrl != details.url) return@launch + _comments.value = (_comments.value + page.comments).distinctBy { it.id } + commentsPage++ + _hasMoreComments.value = page.hasMore && page.comments.isNotEmpty() + _commentsDisabled.value = page.commentsDisabled + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + if (generation == commentsGeneration && loadedUrl == details.url) { + _commentsError.value = commentErrorMessage(exception) + } + } finally { + if (generation == commentsGeneration) { + _loadingMoreComments.value = false + } + } + } + } + + /** + * Retries a failed initial load, or the last page that could not be loaded. + */ + fun retryComments() { + if (_commentsLoading.value || _loadingMoreComments.value) return + val url = loadedUrl ?: return + _commentsError.value = null + if (_comments.value.isEmpty()) { + startCommentsLoad(loadedServiceId, url) + } else { + loadMoreComments() + } + } + + /** + * Expands or collapses the replies of a comment, loading them on first use. + */ + fun toggleCommentReplies(comment: CommentItem) { + if (!comment.hasReplies) return + + val current = _commentReplies.value[comment.id] + if (current?.expanded == true) { + // A previous attempt failed before it produced any reply: pressing the button again + // retries the first page instead of only collapsing the empty thread. + if (current.items.isEmpty() && current.error != null) { + loadCommentReplies(comment.id, page = 0) + } else { + updateCommentReplies(comment.id) { it.copy(expanded = false) } + } + return + } + if (current != null && current.items.isNotEmpty()) { + updateCommentReplies(comment.id) { it.copy(expanded = true, error = null) } + return + } + if (current?.loading == true) return + loadCommentReplies(comment.id, page = 0) + } + + /** + * Loads the next page of replies for an expanded comment. + */ + fun loadMoreCommentReplies(commentId: String) { + val current = _commentReplies.value[commentId] ?: return + if (current.loading || !current.hasMore) return + loadCommentReplies(commentId, current.page + 1) + } + + private fun loadCommentReplies(commentId: String, page: Int) { + val details = _details.value ?: return + if (details.url != loadedUrl) return + val generation = commentsGeneration + + updateCommentReplies(commentId) { + it.copy(expanded = true, loading = true, error = null) + } + + viewModelScope.launch { + try { + val result = repository.commentReplies( + serviceId = details.serviceId, + streamUrl = details.url, + commentId = commentId, + page = page + ) + if (generation != commentsGeneration || loadedUrl != details.url) return@launch + updateCommentReplies(commentId) { state -> + val items = if (page == 0) { + result.comments + } else { + state.items + result.comments + } + state.copy( + expanded = true, + loading = false, + error = null, + items = items.distinctBy { it.id }, + hasMore = result.hasMore && result.comments.isNotEmpty(), + page = page + ) + } + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + if (generation == commentsGeneration && loadedUrl == details.url) { + updateCommentReplies(commentId) { + it.copy(loading = false, error = commentErrorMessage(exception)) + } + } + } + } + } + + private fun updateCommentReplies( + commentId: String, + transform: (CommentRepliesState) -> CommentRepliesState + ) { + val updated = _commentReplies.value.toMutableMap() + updated[commentId] = transform(updated[commentId] ?: CommentRepliesState()) + _commentReplies.value = updated + } + + /** + * Resets every comment state for a new stream. The generation counter makes sure a late + * response of the previous stream cannot overwrite the new one. + */ + private fun resetComments() { + commentsGeneration++ + commentsPage = 0 + _comments.value = emptyList() + _commentsLoading.value = false + _commentsLoaded.value = false + _commentsError.value = null + _commentsDisabled.value = false + _hasMoreComments.value = false + _loadingMoreComments.value = false + _commentReplies.value = emptyMap() + } + + private fun startCommentsLoad(serviceId: Int, url: String) { + resetComments() + val generation = commentsGeneration + _commentsLoading.value = true + _commentsLoaded.value = false + + viewModelScope.launch { + try { + val page = repository.comments(serviceId, url, page = 0) + if (generation != commentsGeneration || loadedUrl != url || + loadedServiceId != serviceId + ) { + return@launch + } + _comments.value = page.comments + _commentsDisabled.value = page.commentsDisabled + _hasMoreComments.value = page.hasMore && page.comments.isNotEmpty() + _commentsLoaded.value = true + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + if (generation == commentsGeneration && loadedUrl == url) { + _commentsError.value = commentErrorMessage(exception) + _commentsLoaded.value = true + } + } finally { + if (generation == commentsGeneration) { + _commentsLoading.value = false + } + } + } + } + + private fun commentErrorMessage(exception: Exception): String = when (exception) { + is ContentException.Network -> + "Could not load comments. Check your internet connection and try again." + + is ContentException.RateLimited -> + "Comments are temporarily rate limited. Try again in a moment." + + is ContentException.CaptchaRequired -> + "The service requires a captcha before showing comments." + + else -> exception.message?.takeIf { it.isNotBlank() } + ?: "Could not load comments. Try again." + } + companion object { /** * The video stream with the highest resolution, falling back to the highest bitrate. @@ -357,3 +589,15 @@ class StreamViewModel( } } } + +/** + * The ui state of the replies below one comment. + */ +data class CommentRepliesState( + val expanded: Boolean = false, + val loading: Boolean = false, + val error: String? = null, + val items: List = emptyList(), + val hasMore: Boolean = false, + val page: Int = 0 +) diff --git a/shared/src/iosMain/kotlin/net/newpipe/app/service/IosContentRepository.kt b/shared/src/iosMain/kotlin/net/newpipe/app/service/IosContentRepository.kt index 364137b00..c2c741186 100644 --- a/shared/src/iosMain/kotlin/net/newpipe/app/service/IosContentRepository.kt +++ b/shared/src/iosMain/kotlin/net/newpipe/app/service/IosContentRepository.kt @@ -6,6 +6,7 @@ package net.newpipe.app.service import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.CommentsPage import net.newpipe.app.model.ServiceInfo import net.newpipe.app.model.StreamDetails import net.newpipe.app.model.ChannelDetails @@ -53,6 +54,16 @@ class IosContentRepository : ContentRepository { override suspend fun playlist(serviceId: Int, url: String): PlaylistDetails = throw unsupported() + override suspend fun comments(serviceId: Int, url: String, page: Int): CommentsPage = + throw unsupported() + + override suspend fun commentReplies( + serviceId: Int, + streamUrl: String, + commentId: String, + page: Int + ): CommentsPage = throw unsupported() + override suspend fun suggest(query: String): List = emptyList() override suspend fun resolveUrl(url: String): ResolvedContent = throw unsupported() diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/di/settings/DesktopSettings.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/di/settings/DesktopSettings.kt index 748a2f510..297893a08 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/di/settings/DesktopSettings.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/di/settings/DesktopSettings.kt @@ -8,6 +8,7 @@ package net.newpipe.app.di.settings import co.touchlab.kermit.Logger import com.russhwolf.settings.PropertiesSettings import com.russhwolf.settings.Settings +import net.newpipe.app.platform.DesktopPaths import java.io.File import java.io.FileOutputStream import java.util.Properties @@ -16,10 +17,25 @@ import java.util.prefs.Preferences /** * The file that stores the application settings of the desktop build. */ -fun settingsFile(): File { - val appData = System.getenv("APPDATA")?.takeIf { it.isNotBlank() } - ?: System.getProperty("user.home") ?: "." - return File(File(appData, "NP-Desktop"), "settings.properties") +fun settingsFile(): File = File(DesktopPaths.configDir(), "settings.properties") + +/** + * Copies the settings of a pre-0.26 Linux installation from the old `~/NP-Desktop` location + * into the XDG configuration directory. The migration runs only when the new file does not + * exist yet, so a user who changes a setting afterwards is never overwritten by stale data. + */ +private fun migrateLegacyLinuxSettings(target: File) { + if (DesktopPaths.isFlatpak || target.exists()) return + if (System.getProperty("os.name").orEmpty().lowercase().contains("win")) return + val legacy = File(DesktopPaths.legacyLinuxDataDir(), "settings.properties") + if (!legacy.isFile) return + runCatching { + target.parentFile?.mkdirs() + legacy.copyTo(target, overwrite = false) + Logger.i(messageString = "Migrated the settings to ${target.absolutePath}") + }.onFailure { exception -> + Logger.w(messageString = "The old settings could not be migrated", throwable = exception) + } } /** @@ -143,6 +159,7 @@ private class PersistingFileSettings( fun desktopSettings(): Settings { val file = settingsFile() file.parentFile?.mkdirs() + migrateLegacyLinuxSettings(file) val properties = Properties() if (file.exists()) { runCatching { diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/platform/AppFileLogger.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/platform/AppFileLogger.kt index 3452ad832..584349397 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/platform/AppFileLogger.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/platform/AppFileLogger.kt @@ -41,9 +41,7 @@ object AppFileLogger { return } file = try { - val appData = System.getenv("APPDATA")?.takeIf { it.isNotBlank() } - ?: System.getProperty("user.home") ?: return - val directory = File(File(appData, "NP-Desktop"), "logs") + val directory = File(DesktopPaths.stateDir(), "logs") if (!directory.isDirectory && !directory.mkdirs()) { return } diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/platform/DesktopPaths.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/platform/DesktopPaths.kt new file mode 100644 index 000000000..81104a99c --- /dev/null +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/platform/DesktopPaths.kt @@ -0,0 +1,98 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.platform + +import java.io.File + +/** + * The directories of the desktop build. + * + * Windows keeps the historical `%APPDATA%\NP-Desktop` layout, so existing installations keep + * their settings and logs. Linux follows the XDG base directory specification, which is also + * what a Flatpak sandbox exposes: the configuration, data, state and cache directories are + * writable without giving the app access to the whole home directory. + */ +object DesktopPaths { + + private val osName = System.getProperty("os.name").orEmpty().lowercase() + + private val isWindows = osName.contains("win") + + private val isMac = osName.contains("mac") + + /** + * Whether the process runs inside a Flatpak sandbox. Flatpak sets `FLATPAK_ID`; the marker + * file is the fallback for launchers that scrub the environment. + */ + val isFlatpak: Boolean = !System.getenv("FLATPAK_ID").isNullOrBlank() || + File("/.flatpak-info").isFile + + private fun home(): File = File(System.getProperty("user.home") ?: ".") + + private fun env(name: String): File? = + System.getenv(name)?.takeIf { it.isNotBlank() }?.let(::File) + + /** + * The configuration directory: settings, the YouTube session and the download folder. + */ + fun configDir(): File = when { + isWindows -> File(env("APPDATA") ?: home(), "NP-Desktop") + isMac -> File(home(), "Library/Application Support/NP-Desktop") + else -> File(env("XDG_CONFIG_HOME") ?: File(home(), ".config"), "NP-Desktop") + } + + /** + * The data directory: the extracted playback runtime and other durable files. + */ + fun dataDir(): File = when { + isWindows -> File(env("LOCALAPPDATA") ?: home(), "NP-Desktop") + isMac -> File(home(), "Library/Application Support/NP-Desktop") + else -> File(env("XDG_DATA_HOME") ?: File(home(), ".local/share"), "NP-Desktop") + } + + /** + * The state directory: logs and other files that are useful for diagnostics but can be + * recreated. + */ + fun stateDir(): File = when { + isWindows -> File(env("APPDATA") ?: home(), "NP-Desktop") + isMac -> File(home(), "Library/Logs/NP-Desktop") + else -> File(env("XDG_STATE_HOME") ?: File(home(), ".local/state"), "NP-Desktop") + } + + /** + * The cache directory: image thumbnails and other disposable data. + */ + fun cacheDir(): File = when { + isWindows -> File(env("LOCALAPPDATA") ?: home(), "NP-Desktop") + isMac -> File(home(), "Library/Caches/NP-Desktop") + else -> File(env("XDG_CACHE_HOME") ?: File(home(), ".cache"), "NP-Desktop") + } + + /** + * The download directory. A Flatpak with the `xdg-download` permission can write to the + * user's Downloads folder; everywhere else the historical `Videos/NewPipe` folder is the + * fallback when there is no Downloads folder. + */ + fun downloadsDir(): File { + val downloads = env("XDG_DOWNLOAD_DIR") ?: File(home(), "Downloads") + if (!isWindows && downloads.isDirectory) return downloads + return File(home(), "Videos${File.separator}NewPipe") + } + + /** + * The folder for player screenshots. + */ + fun picturesDir(): File { + val pictures = env("XDG_PICTURES_DIR") ?: File(home(), "Pictures") + return if (pictures.isDirectory) pictures else dataDir() + } + + /** + * The old pre-XDG location on Linux, used to migrate the settings of existing users. + */ + fun legacyLinuxDataDir(): File = File(home(), "NP-Desktop") +} diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/DownloadLocation.jvm.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/DownloadLocation.jvm.kt index ea4844e7b..9fe589ab2 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/DownloadLocation.jvm.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/DownloadLocation.jvm.kt @@ -5,7 +5,9 @@ package net.newpipe.app.service +import net.newpipe.app.platform.DesktopPaths import java.io.File +import java.util.Properties import java.util.prefs.Preferences import javax.swing.JFileChooser import javax.swing.SwingUtilities @@ -14,28 +16,74 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** - * The desktop download folder: the user's choice is stored in the Java preferences, the fallback - * is `Videos/NewPipe` in the user home. + * The desktop download folder: the user's choice is stored next to the other settings, the + * fallback is the XDG Downloads folder (or `Videos/NewPipe` where there is none). + * + * The store used to be `java.util.prefs`; the first read migrates an existing choice so a user + * who selected a folder before 0.26 keeps it. */ actual object DownloadLocation { - private val prefs = Preferences.userNodeForPackage(DownloadLocation::class.java) private const val KEY = "download_path" - actual var directory: String? = prefs.get(KEY, "").ifEmpty { null } + private val file: File + get() = File(DesktopPaths.configDir(), "downloads.properties") + + private val properties = Properties() + + @Volatile + private var loaded = false + + private fun load() { + if (loaded) return + loaded = true + if (file.isFile) { + runCatching { file.inputStream().use { properties.load(it) } } + } + } + + private fun store() { + runCatching { + file.parentFile?.mkdirs() + val temporary = File(file.parentFile, file.name + ".tmp") + temporary.outputStream().use { properties.store(it, "NP Desktop download folder") } + if (!temporary.renameTo(file)) { + temporary.copyTo(file, overwrite = true) + temporary.delete() + } + } + } + + /** + * Reads the folder from the old preference store once and writes it into the file store. + */ + private fun migrateLegacy(): String? { + val legacy = runCatching { + Preferences.userNodeForPackage(DownloadLocation::class.java).get(KEY, "") + }.getOrNull().orEmpty() + if (legacy.isBlank()) return null + properties.setProperty(KEY, legacy) + store() + return legacy + } + + actual var directory: String? + get() { + load() + return properties.getProperty(KEY)?.takeIf { it.isNotBlank() } ?: migrateLegacy() + } set(value) { - field = value + load() if (value == null) { - prefs.remove(KEY) + properties.remove(KEY) } else { - prefs.put(KEY, value) + properties.setProperty(KEY, value) } - prefs.flush() + store() } actual fun resolve(): String = - directory ?: File(System.getProperty("user.home"), "Videos${File.separator}NewPipe") - .absolutePath + directory ?: DesktopPaths.downloadsDir().absolutePath /** * The desktop offers the Swing folder chooser. diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt index c465d91b5..8c6e8d5e0 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt @@ -21,6 +21,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import net.newpipe.app.model.ChannelDetails +import net.newpipe.app.model.CommentItem +import net.newpipe.app.model.CommentsPage import net.newpipe.app.model.ContentItem import net.newpipe.app.model.ContentType import net.newpipe.app.model.MediaStream @@ -37,6 +39,8 @@ import org.schabi.newpipe.extractor.StreamingService import org.schabi.newpipe.extractor.channel.ChannelInfo import org.schabi.newpipe.extractor.channel.ChannelInfoItem import org.schabi.newpipe.extractor.channel.ChannelTabInfo +import org.schabi.newpipe.extractor.comments.CommentsInfo +import org.schabi.newpipe.extractor.comments.CommentsInfoItem import org.schabi.newpipe.extractor.exceptions.ExtractionException import org.schabi.newpipe.extractor.exceptions.ReCaptchaException import org.schabi.newpipe.extractor.search.filter.FilterItem @@ -50,6 +54,7 @@ import org.schabi.newpipe.extractor.services.youtube.sabr.media.SabrMediaSegment import org.schabi.newpipe.extractor.playlist.PlaylistInfo import org.schabi.newpipe.extractor.playlist.PlaylistInfoItem import org.schabi.newpipe.extractor.search.SearchInfo +import org.schabi.newpipe.extractor.stream.Description import org.schabi.newpipe.extractor.stream.StreamInfo import org.schabi.newpipe.extractor.stream.StreamInfoItem import org.schabi.newpipe.extractor.stream.StreamType @@ -99,6 +104,16 @@ class ExtractorContentRepository( private val kioskCache = ResultsCache>(ttlMillis = 10 * 60_000L) private val searchCache = ResultsCache>(ttlMillis = 5 * 60_000L) + /** + * Comment pages are loaded sequentially: the extraction engine only hands out the next page + * token, so the implicit cursor of each stream and each reply thread is kept here. The + * resulting [CommentItem]s are cached by the view model; these cursors only make a repeated + * request idempotent and allow replies to be loaded from the original comment item. + */ + private val commentsCursors = ConcurrentHashMap() + private val replyCursors = ConcurrentHashMap() + private val loadedComments = ConcurrentHashMap() + override suspend fun search(request: SearchRequest): List = withContext(Dispatchers.IO) { guard { if (request.page != 0) { @@ -786,6 +801,50 @@ class ExtractorContentRepository( } } + override suspend fun comments( + serviceId: Int, + url: String, + page: Int + ): CommentsPage = withContext(Dispatchers.IO) { + guard { + require(page >= 0) { "The comment page must not be negative" } + val key = CacheKey(serviceId, url) + val cursor = commentsCursors[key] ?: run { + val info = CommentsInfo.getInfo(serviceForId(serviceId), url) + val created = CommentsCursor(info) + commentsCursors.putIfAbsent(key, created) ?: created + } + cursor.page(page, serviceForId(serviceId)) { items -> + items.toCommentItems(loadedComments) + } + } + } + + override suspend fun commentReplies( + serviceId: Int, + streamUrl: String, + commentId: String, + page: Int + ): CommentsPage = withContext(Dispatchers.IO) { + guard { + require(page >= 0) { "The reply page must not be negative" } + val key = "$serviceId:$commentId" + val cursor = replyCursors[key] ?: run { + val comment = loadedComments[key] + ?: throw ContentException.Unsupported( + "The replies are no longer available. Reload the comments." + ) + val firstPage = comment.replies + ?: return@guard CommentsPage() + val created = ReplyCursor(firstPage) + replyCursors.putIfAbsent(key, created) ?: created + } + cursor.page(page, serviceForId(serviceId), streamUrl) { items -> + items.toCommentItems(loadedComments) + } + } + } + override suspend fun suggest(query: String): List = withContext(Dispatchers.IO) { val term = query.trim() if (term.isBlank()) return@withContext emptyList() @@ -959,6 +1018,84 @@ class ExtractorContentRepository( private data class SearchCursor(val index: Int, val page: Page) +/** + * The implicit page cursor of the comments below one stream. + * + * [CommentsInfo] already holds the first page and the token of the second one. Further pages are + * requested one after another, exactly as the extraction engine requires, and every fetched page + * is kept so retries and recompositions do not consume additional page tokens. + */ +private class CommentsCursor(private val info: CommentsInfo) { + + private val lock = Any() + private val pages = mutableMapOf(0 to info.relatedItems) + private var loadedPage = 0 + private var nextPage: Page? = info.nextPage + + fun page( + index: Int, + service: StreamingService, + mapper: (List) -> List + ): CommentsPage = synchronized(lock) { + while (loadedPage < index) { + val token = nextPage ?: break + val result = CommentsInfo.getMoreItems(service, info, token) + nextPage = result.nextPage + loadedPage++ + pages[loadedPage] = result.items + } + + val items = pages[index].orEmpty() + CommentsPage( + comments = mapper(items), + hasMore = nextPage != null, + commentsDisabled = info.isCommentsDisabled + ) + } +} + +/** + * The implicit page cursor of the replies to one top-level comment. + */ +private class ReplyCursor(private var nextPage: Page?) { + + private val lock = Any() + private val pages = mutableMapOf>() + private var loadedPage = -1 + + fun page( + index: Int, + service: StreamingService, + streamUrl: String, + mapper: (List) -> List + ): CommentsPage = synchronized(lock) { + while (loadedPage < index) { + val token = nextPage ?: break + val result = CommentsInfo.getMoreItems(service, streamUrl, token) + nextPage = result.nextPage + loadedPage++ + pages[loadedPage] = result.items + } + + CommentsPage( + comments = mapper(pages[index].orEmpty()), + hasMore = nextPage != null + ) + } +} + +/** + * Maps a page of extractor comments and remembers the original items so their reply cursors can + * be resolved later without another network request. + */ +private fun List.toCommentItems( + registry: MutableMap +): List = mapNotNull { item -> + item.toCommentItem()?.also { comment -> + registry["${item.serviceId}:${comment.id}"] = item + } +} + /** The cache key of one repository result: the service and a content-specific identifier. */ private data class CacheKey(val serviceId: Int, val id: String) @@ -1112,6 +1249,91 @@ private fun List?.bestImageUrl(): String? = this ?.maxByOrNull { it.width.toLong() * it.height.toLong() } ?.url +private val HTML_BREAK = Regex("(?i)") +private val HTML_PARAGRAPH = Regex("(?i)") +private val HTML_DIV = Regex("(?i)") +private val HTML_LIST_ITEM = Regex("(?i)]*>") +private val HTML_TAG = Regex("<[^>]*>") +private val HTML_ENTITY = Regex("&(#x?[0-9a-fA-F]+|[a-zA-Z]+);") + +/** + * Turns the HTML fragment the extraction engine returns for comments into the plain text the + * desktop UI displays. Line breaks and list items are preserved, other tags are dropped and + * numeric and named entities are decoded. + */ +internal fun String.htmlToPlainText(): String = replace(HTML_BREAK, "\n") + .replace(HTML_PARAGRAPH, "\n\n") + .replace(HTML_DIV, "\n") + .replace(HTML_LIST_ITEM, "\u2022 ") + .replace(HTML_TAG, "") + .decodeHtmlEntities() + .replace("\r\n", "\n") + .replace('\u00a0', ' ') + .trim() + +private fun String.decodeHtmlEntities(): String = HTML_ENTITY.replace(this) { match -> + val entity = match.groupValues[1] + val decoded = when { + entity.startsWith("#x", ignoreCase = true) -> + entity.drop(2).toIntOrNull(16)?.toCodePointText() + + entity.startsWith("#") -> + entity.drop(1).toIntOrNull()?.toCodePointText() + + else -> when (entity.lowercase()) { + "amp" -> "&" + "lt" -> "<" + "gt" -> ">" + "quot" -> "\"" + "apos" -> "'" + "nbsp" -> " " + else -> null + } + } + decoded ?: match.value +} + +private fun Int.toCodePointText(): String? = + if (Character.isValidCodePoint(this)) String(Character.toChars(this)) else null + +/** + * Converts an extraction engine comment into a platform independent [CommentItem]. + * + * Comments are read-only. Comments without an identifier or text are dropped because they cannot + * be displayed or have their replies loaded. + */ +internal fun CommentsInfoItem.toCommentItem(): CommentItem? { + val description = commentText + val text = when (description?.type) { + Description.HTML -> description.content.htmlToPlainText() + else -> description?.content.orEmpty() + }.trim() + val id = commentId?.takeIf { it.isNotBlank() } + if (id == null && text.isBlank()) return null + + val knownReplyCount = replyCount.takeIf { it >= 0 } + val commentUrl = url.orEmpty() + val author = uploaderName.orEmpty().ifBlank { "Unknown" } + + return CommentItem( + id = id ?: "$commentUrl#$author#${text.hashCode()}", + author = author, + authorUrl = uploaderUrl?.takeIf { it.isNotBlank() }, + authorAvatarUrl = pictures.toList().bestImageUrl() + ?: uploaderAvatarUrl?.takeIf { it.isNotBlank() }, + text = text, + uploadDate = textualUploadDate?.takeIf { it.isNotBlank() }, + likeCount = likeCount.takeIf { it >= 0 }, + textualLikeCount = textualLikeCount?.takeIf { it.isNotBlank() }, + replyCount = knownReplyCount, + isPinned = isPinned, + isHeartedByUploader = isHeartedByUploader, + isUploaderVerified = isUploaderVerified, + streamPositionSeconds = streamPosition.takeIf { it >= 0 }, + hasReplies = replies != null || (knownReplyCount ?: 0) > 0 + ) +} + /** * Converts an extraction engine item into a platform independent [ContentItem]. */ diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt index b97e6d200..110557179 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt @@ -17,6 +17,7 @@ import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive +import net.newpipe.app.platform.DesktopPaths import net.newpipe.app.platform.UpdateInfo import net.newpipe.app.platform.UpdateProgress import net.newpipe.app.platform.UpdateStatus @@ -133,6 +134,13 @@ object UpdateService { * result is stored in [status] and also returned, so callers can react on the outcome. */ suspend fun checkForUpdate(): UpdateStatus { + if (DesktopPaths.isFlatpak) { + val managed = UpdateStatus.Managed( + "Updates are managed by Flatpak. Run `flatpak update` to install a newer version." + ) + updateStatus(managed) + return managed + } if (!isVersionKnown) { Logger.w(messageString = "The updater cannot check without a known app version") return UpdateStatus.Error("The current version is unknown") @@ -160,6 +168,14 @@ object UpdateService { * installation. Runs asynchronously; the status flow follows every step. */ fun downloadInstall(info: UpdateInfo) { + if (DesktopPaths.isFlatpak) { + updateStatus( + UpdateStatus.Managed( + "Updates are managed by Flatpak. Run `flatpak update` to install a newer version." + ) + ) + return + } if (!installing.compareAndSet(false, true)) { Logger.w(messageString = "An update is already being installed") return diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcNativeLocator.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcNativeLocator.kt index a3e52cdb9..baed824ce 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcNativeLocator.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcNativeLocator.kt @@ -6,6 +6,9 @@ package net.newpipe.app.service import co.touchlab.kermit.Logger +import com.sun.jna.Library +import com.sun.jna.Native +import net.newpipe.app.platform.DesktopPaths import java.io.File import java.io.FileOutputStream import java.io.InputStream @@ -19,7 +22,7 @@ import java.util.zip.ZipInputStream * 1. the `newpipe.vlc.path` system property, * 2. the `NEWPIPE_VLC_PATH` environment variable, * 3. the copy extracted from the `vlc-runtime.zip` shipped inside the application jar (the - * Windows runtime, extracted to the user's local application data directory), + * Windows, Linux or macOS runtime, extracted to the user's local application data directory), * 4. the libVLC copy bundled as plain resources with the packaged application (`resources/vlc`), * 5. the working directory and its `vlc` subdirectory, which is where the packaged application * keeps its copy of libVLC, @@ -42,6 +45,12 @@ object VlcNativeLocator { */ const val ENVIRONMENT_VARIABLE = "NEWPIPE_VLC_PATH" + /** + * The environment variable libVLC reads the plugin directory from. It must be present + * before `libvlc_new`, which is why [locate] sets it before the player factory is created. + */ + private const val PLUGIN_ENVIRONMENT_VARIABLE = "VLC_PLUGIN_PATH" + /** * The system property that points at the resources directory of a packaged application. */ @@ -111,6 +120,7 @@ object VlcNativeLocator { Logger.w(messageString = "No libVLC installation was found") } else { System.setProperty("jna.library.path", directory.absolutePath) + configurePluginPath(directory) locatedDirectory = directory Logger.i(messageString = "Using libVLC from ${directory.absolutePath}") } @@ -119,31 +129,58 @@ object VlcNativeLocator { } } + /** + * The plugin directory of the located libVLC installation, or `null` when the installation + * has no plugin tree (for example a distribution that keeps the plugins elsewhere). + */ + fun pluginDirectory(): File? = locatedDirectory + ?.let { directory -> File(directory, "plugins") } + ?.takeIf { directory -> directory.isDirectory } + + /** + * Points libVLC at the plugin tree of the located installation. VLC reads + * `VLC_PLUGIN_PATH` while the native library is initialised, so the variable has to be set + * from the process before [uk.co.caprica.vlcj.factory.MediaPlayerFactory] is created. + * Windows resolves its plugins relative to `libvlc.dll` and needs no variable. + */ + private fun configurePluginPath(directory: File) { + if (!isLinux && !isMac) return + val plugins = File(directory, "plugins") + if (!plugins.isDirectory) return + + runCatching { + val libc = Native.load("c", LibC::class.java) + libc.setenv(PLUGIN_ENVIRONMENT_VARIABLE, plugins.absolutePath, 1) + }.onFailure { failure -> + Logger.w( + messageString = "Could not set $PLUGIN_ENVIRONMENT_VARIABLE; " + + "falling back to the player's plugin-path argument", + throwable = failure + ) + } + } + + /** + * The C library binding used to set the plugin path in the process environment. + */ + private interface LibC : Library { + fun setenv(name: String, value: String, overwrite: Int): Int + } + /** * Unpacks the libVLC runtime that ships inside the application jar to the user's local * application data directory, unless the current extraction is already up to date. */ private fun extractRuntime() { - // The runtime zip that is shipped inside the jar is the Windows libVLC build; the - // Linux and macOS packages rely on the system installation. - if (!isWindows) return - // Probe the resource and read the version marker through a separate stream, so that - // the unzip pass below receives an untouched stream. - val probe = classLoader.getResourceAsStream(RUNTIME_ZIP) ?: run { + val version = runtimeVersion() + if (version == null) { println("VlcRuntime: no bundled vlc-runtime.zip on the classpath") return } - val version = runCatching { probe.read().toString() }.getOrNull() ?: return - val zip = classLoader.getResourceAsStream(RUNTIME_ZIP) ?: return val targetDirectory = extractionDirectory() - if (targetDirectory == null) { - Logger.w(messageString = "No writable directory to extract the bundled libVLC to") - return - } - val marker = File(targetDirectory, EXTRACTION_MARKER) - if (marker.isFile && marker.readText() == version && hasLibrary(targetDirectory)) { + if (marker.isFile && marker.readText().trim() == version && hasLibrary(targetDirectory)) { return } @@ -152,6 +189,7 @@ object VlcNativeLocator { targetDirectory.deleteRecursively() targetDirectory.mkdirs() + val zip = classLoader.getResourceAsStream(RUNTIME_ZIP) ?: return runCatching { unzip(zip, targetDirectory) } .onSuccess { marker.writeText(version) @@ -163,6 +201,27 @@ object VlcNativeLocator { } } + /** + * Reads the version marker from the runtime archive. The marker is the first entry of the + * archive, so this does not have to unpack or scan the whole file. + */ + private fun runtimeVersion(): String? { + val stream = classLoader.getResourceAsStream(RUNTIME_ZIP) ?: return null + stream.buffered().use { buffered -> + ZipInputStream(buffered).use { zip -> + var entry = zip.nextEntry + while (entry != null) { + if (entry.name == EXTRACTION_MARKER) { + return zip.readBytes().toString(Charsets.UTF_8).trim() + } + zip.closeEntry() + entry = zip.nextEntry + } + } + } + return null + } + /** * The class loader the application was started through. `getResourceAsStream` resolves * through the same hierarchy in development runs and packaged applications. @@ -171,36 +230,10 @@ object VlcNativeLocator { get() = VlcNativeLocator::class.java.classLoader ?: ClassLoader.getSystemClassLoader() /** - * The directory into which the bundled runtime is extracted, or `null` when there is none. + * The directory into which the bundled runtime is extracted. It lives in the application + * data directory, which is writable inside a Flatpak sandbox as well. */ - private fun extractionDirectory(): File? { - val userHome = System.getProperty("user.home")?.takeIf { it.isNotBlank() } - val base = when { - isWindows -> { - val localAppData = System.getenv("LOCALAPPDATA")?.takeIf { it.isNotBlank() } - if (localAppData != null) { - File(localAppData, "NP-Desktop") - } else if (userHome != null) { - File(userHome, "AppData/Local/NP-Desktop") - } else { - null - } - } - isMac -> userHome?.let { File(it, "Library/Application Support/NP-Desktop") } - else -> { - val xdgData = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() } - if (xdgData != null) { - File(xdgData, "NP-Desktop") - } else if (userHome != null) { - File(userHome, ".local/share/NP-Desktop") - } else { - null - } - } - } ?: return null - - return File(base, "vlc") - } + private fun extractionDirectory(): File = File(DesktopPaths.dataDir(), "vlc") /** * Copies the zip archive stream into the given directory. @@ -248,7 +281,7 @@ object VlcNativeLocator { ?.let { candidates.add(File(it)) } // The libVLC copy that was extracted from the bundled runtime zip. - extractionDirectory()?.let { candidates.add(it) } + candidates.add(extractionDirectory()) // The libVLC copy bundled with the packaged application. `compose.application.resources.dir` // points at the resources directory that jpackage created inside the application image. diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcPlaybackController.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcPlaybackController.kt index 099c41a64..885159cfe 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcPlaybackController.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/VlcPlaybackController.kt @@ -6,6 +6,7 @@ package net.newpipe.app.service import co.touchlab.kermit.Logger +import net.newpipe.app.platform.DesktopPaths import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -978,6 +979,8 @@ class VlcPlaybackController : PlaybackController, VideoFrameProvider { */ private fun createFactory(): MediaPlayerFactory? = try { VlcNativeLocator.locate() + // The locator points VLC at the plugin tree through VLC_PLUGIN_PATH. The old + // --plugin-path argument was removed from libVLC 3.0.24 and only produces warnings. MediaPlayerFactory(*LIBRARY_ARGUMENTS) } catch (exception: Throwable) { Logger.e(messageString = "libVLC could not be initialised", throwable = exception) @@ -986,14 +989,14 @@ class VlcPlaybackController : PlaybackController, VideoFrameProvider { /** * The error shown when the native libVLC bindings could not be initialised. Linux gets an - * actionable message, because the Debian package does not bundle libVLC and the player - * needs the system package. + * actionable message: the packaged application carries its own runtime, so a failure means + * the extraction or the platform is broken, not that the user forgot a package. */ private fun unavailableMessage(): String { val linux = System.getProperty("os.name").orEmpty().lowercase().contains("linux") return if (linux) { - "libVLC is not available — install the VLC package " + - "(for example: sudo apt install vlc)" + "The bundled playback engine could not be loaded — reinstall NP Desktop, or set " + + "NEWPIPE_VLC_PATH to a libVLC installation" } else { "libVLC is not available" } @@ -1125,7 +1128,7 @@ class VlcPlaybackController : PlaybackController, VideoFrameProvider { return FrameCapture.NoFrame } return try { - val folder = Paths.get(System.getProperty("user.home"), "Pictures", "NP Desktop") + val folder = Paths.get(DesktopPaths.picturesDir().absolutePath, "NP Desktop") Files.createDirectories(folder) val stamp = DateTimeFormatter .ofPattern("yyyy-MM-dd_HH-mm-ss-SSS") diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/YtSession.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/YtSession.kt index bbba77553..68a57fc8f 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/YtSession.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/YtSession.kt @@ -5,6 +5,7 @@ package net.newpipe.app.service +import net.newpipe.app.platform.DesktopPaths import java.io.File import java.io.FileOutputStream import java.util.Properties @@ -21,11 +22,27 @@ import java.util.Properties object YtSession { private val file: File - get() { - val appData = System.getenv("APPDATA")?.takeIf { it.isNotBlank() } - ?: System.getProperty("user.home") ?: "." - return File(File(appData, "NP-Desktop"), "yt-session.properties") + get() = File(DesktopPaths.configDir(), "yt-session.properties") + + @Volatile + private var migrated = false + + /** + * Moves the session file of a pre-0.26 Linux installation from `~/NP-Desktop` into the XDG + * configuration directory. Flatpak starts with an empty sandbox and must not read the old + * home path. + */ + private fun migrateLegacy() { + if (migrated) return + migrated = true + if (DesktopPaths.isFlatpak || file.exists()) return + val legacy = File(DesktopPaths.legacyLinuxDataDir(), "yt-session.properties") + if (!legacy.isFile) return + runCatching { + file.parentFile?.mkdirs() + legacy.copyTo(file, overwrite = false) } + } /** Cookie names that are relevant for the InnerTube playback flow. */ private val RELEVANT_COOKIES = setOf( @@ -45,6 +62,7 @@ object YtSession { * The parsed session cookies, reloaded from the file when it changed on disk. */ fun cookies(): Map { + migrateLegacy() val current = file.takeIf { it.exists() }?.lastModified() ?: 0L val cache = cached if (cache != null && cacheStamp == current) { @@ -79,6 +97,7 @@ object YtSession { * stores the relevant YouTube cookies. Returns the number of stored cookies. */ fun save(paste: String): Int { + migrateLegacy() val parsed = parsePaste(paste) if (parsed.isEmpty()) return 0 diff --git a/shared/src/jvmTest/kotlin/net/newpipe/app/service/CommentMappingTest.kt b/shared/src/jvmTest/kotlin/net/newpipe/app/service/CommentMappingTest.kt new file mode 100644 index 000000000..ba339a9b5 --- /dev/null +++ b/shared/src/jvmTest/kotlin/net/newpipe/app/service/CommentMappingTest.kt @@ -0,0 +1,127 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import org.schabi.newpipe.extractor.Image +import org.schabi.newpipe.extractor.comments.CommentsInfoItem +import org.schabi.newpipe.extractor.stream.Description + +class CommentMappingTest { + + @Test + fun `maps a complete comment`() { + val item = commentItem(id = "comment-1", text = "Watch this at 1:23") + item.uploaderName = "Alice" + item.uploaderUrl = "https://www.youtube.com/@alice" + item.uploaderAvatarUrl = "https://example.com/alice.jpg" + item.textualUploadDate = "2 days ago" + item.likeCount = 42 + item.textualLikeCount = "42" + item.replyCount = 3 + item.setPinned(true) + item.setHeartedByUploader(true) + item.setUploaderVerified(true) + item.streamPosition = 83 + item.setPictures( + listOf( + Image("https://example.com/small.jpg", 48, 48, Image.ResolutionLevel.LOW), + Image("https://example.com/large.jpg", 128, 128, Image.ResolutionLevel.HIGH) + ) + ) + + val comment = assertNotNull(item.toCommentItem()) + + assertEquals("comment-1", comment.id) + assertEquals("Alice", comment.author) + assertEquals("https://www.youtube.com/@alice", comment.authorUrl) + assertEquals("https://example.com/large.jpg", comment.authorAvatarUrl) + assertEquals("Watch this at 1:23", comment.text) + assertEquals("2 days ago", comment.uploadDate) + assertEquals(42, comment.likeCount) + assertEquals("42", comment.textualLikeCount) + assertEquals(3, comment.replyCount) + assertTrue(comment.isPinned) + assertTrue(comment.isHeartedByUploader) + assertTrue(comment.isUploaderVerified) + assertEquals(83, comment.streamPositionSeconds) + assertTrue(comment.hasReplies) + } + + @Test + fun `unknown values become null instead of sentinels`() { + val item = commentItem(id = "comment-2", text = "No metadata") + item.likeCount = CommentsInfoItem.NO_LIKE_COUNT + item.replyCount = CommentsInfoItem.UNKNOWN_REPLY_COUNT + item.streamPosition = CommentsInfoItem.NO_STREAM_POSITION + + val comment = assertNotNull(item.toCommentItem()) + + assertNull(comment.likeCount) + assertNull(comment.replyCount) + assertNull(comment.streamPositionSeconds) + assertFalse(comment.hasReplies) + assertNull(comment.uploadDate) + assertNull(comment.authorAvatarUrl) + } + + @Test + fun `a missing comment id gets a stable fallback`() { + val first = commentItem(id = "", text = "Same text") + val second = commentItem(id = "", text = "Same text") + + val firstComment = assertNotNull(first.toCommentItem()) + val secondComment = assertNotNull(second.toCommentItem()) + + assertTrue(firstComment.id.isNotBlank()) + assertEquals(firstComment.id, secondComment.id) + } + + @Test + fun `a comment without id and text is dropped`() { + assertNull(commentItem(id = "", text = " ").toCommentItem()) + } + + @Test + fun `an empty picture set falls back to the uploader avatar`() { + val item = commentItem(id = "comment-3", text = "Avatar fallback") + item.uploaderAvatarUrl = "https://example.com/fallback.jpg" + item.setPictures(emptyList()) + + val comment = assertNotNull(item.toCommentItem()) + + assertEquals("https://example.com/fallback.jpg", comment.authorAvatarUrl) + } + + @Test + fun `html comments are converted to plain text`() { + val item = commentItem(id = "comment-4", text = "placeholder") + item.commentText = Description( + "We're so honored & happy!
Second line" + + "

Paragraph 😀 and "quotes"

", + Description.HTML + ) + + val comment = assertNotNull(item.toCommentItem()) + + assertEquals( + "We're so honored & happy!\nSecond line\n\nParagraph \uD83D\uDE00 and \"quotes\"", + comment.text + ) + } + + private fun commentItem(id: String, text: String): CommentsInfoItem = + CommentsInfoItem(0, "https://www.youtube.com/watch?v=test", "comment").apply { + commentId = id + uploaderName = "Author" + commentText = Description(text, Description.PLAIN_TEXT) + } +} diff --git a/shared/src/jvmTest/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModelCommentsTest.kt b/shared/src/jvmTest/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModelCommentsTest.kt new file mode 100644 index 000000000..cfa945cbc --- /dev/null +++ b/shared/src/jvmTest/kotlin/net/newpipe/app/viewmodel/stream/StreamViewModelCommentsTest.kt @@ -0,0 +1,246 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.viewmodel.stream + +import com.russhwolf.settings.MapSettings +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import net.newpipe.app.model.ChannelDetails +import net.newpipe.app.model.CommentItem +import net.newpipe.app.model.CommentsPage +import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.PlaylistDetails +import net.newpipe.app.model.ResolvedContent +import net.newpipe.app.model.StreamDetails +import net.newpipe.app.service.ContentException +import net.newpipe.app.service.ContentRepository +import net.newpipe.app.service.SearchRequest +import net.newpipe.app.service.ServiceKiosk + +@OptIn(ExperimentalCoroutinesApi::class) +class StreamViewModelCommentsTest { + + @Test + fun `loading a stream loads the first comments page`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + try { + val repository = FakeContentRepository().apply { + commentsPages[0] = CommentsPage( + comments = listOf(comment("c1")), + hasMore = true + ) + } + val viewModel = StreamViewModel(repository, MapSettings()) + + viewModel.load(0, STREAM_URL) + advanceUntilIdle() + + assertEquals(listOf("c1"), viewModel.comments.value.map { it.id }) + assertTrue(viewModel.commentsLoaded.value) + assertTrue(viewModel.hasMoreComments.value) + assertFalse(viewModel.commentsDisabled.value) + assertNull(viewModel.commentsError.value) + assertEquals(listOf(0), repository.commentRequests) + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun `loading more comments appends the next page`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + try { + val repository = FakeContentRepository().apply { + commentsPages[0] = CommentsPage(listOf(comment("c1")), hasMore = true) + commentsPages[1] = CommentsPage(listOf(comment("c2")), hasMore = false) + } + val viewModel = StreamViewModel(repository, MapSettings()) + + viewModel.load(0, STREAM_URL) + advanceUntilIdle() + viewModel.loadMoreComments() + advanceUntilIdle() + + assertEquals(listOf("c1", "c2"), viewModel.comments.value.map { it.id }) + assertEquals(listOf(0, 1), repository.commentRequests) + assertFalse(viewModel.hasMoreComments.value) + assertFalse(viewModel.loadingMoreComments.value) + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun `the comments disabled state is exposed`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + try { + val repository = FakeContentRepository().apply { + commentsPages[0] = CommentsPage(commentsDisabled = true) + } + val viewModel = StreamViewModel(repository, MapSettings()) + + viewModel.load(0, STREAM_URL) + advanceUntilIdle() + + assertTrue(viewModel.commentsDisabled.value) + assertTrue(viewModel.comments.value.isEmpty()) + assertTrue(viewModel.commentsLoaded.value) + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun `a failed comments load can be retried`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + try { + val repository = FakeContentRepository().apply { failComments = true } + val viewModel = StreamViewModel(repository, MapSettings()) + + viewModel.load(0, STREAM_URL) + advanceUntilIdle() + + assertNotNull(viewModel.commentsError.value) + assertFalse(viewModel.commentsLoading.value) + + repository.failComments = false + repository.commentsPages[0] = CommentsPage(listOf(comment("c1"))) + viewModel.retryComments() + advanceUntilIdle() + + assertNull(viewModel.commentsError.value) + assertEquals(listOf("c1"), viewModel.comments.value.map { it.id }) + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun `replies load on demand and can be expanded and collapsed`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + try { + val parent = comment("c1", hasReplies = true, replyCount = 2) + val repository = FakeContentRepository().apply { + commentsPages[0] = CommentsPage(listOf(parent)) + replyPages["c1" to 0] = CommentsPage( + comments = listOf(comment("r1")), + hasMore = true + ) + replyPages["c1" to 1] = CommentsPage( + comments = listOf(comment("r2")), + hasMore = false + ) + } + val viewModel = StreamViewModel(repository, MapSettings()) + + viewModel.load(0, STREAM_URL) + advanceUntilIdle() + viewModel.toggleCommentReplies(parent) + advanceUntilIdle() + + val firstState = assertNotNull(viewModel.commentReplies.value["c1"]) + assertTrue(firstState.expanded) + assertEquals(listOf("r1"), firstState.items.map { it.id }) + assertTrue(firstState.hasMore) + + viewModel.loadMoreCommentReplies("c1") + advanceUntilIdle() + + val secondState = assertNotNull(viewModel.commentReplies.value["c1"]) + assertEquals(listOf("r1", "r2"), secondState.items.map { it.id }) + assertFalse(secondState.hasMore) + + viewModel.toggleCommentReplies(parent) + val collapsed = assertNotNull(viewModel.commentReplies.value["c1"]) + assertFalse(collapsed.expanded) + // Collapsing must not throw the already loaded replies away. + assertEquals(2, collapsed.items.size) + } finally { + Dispatchers.resetMain() + } + } + + private fun comment( + id: String, + hasReplies: Boolean = false, + replyCount: Int? = null + ): CommentItem = CommentItem( + id = id, + author = "Author", + text = "Text of $id", + replyCount = replyCount, + hasReplies = hasReplies + ) + + private class FakeContentRepository : ContentRepository { + + val commentsPages = mutableMapOf() + val replyPages = mutableMapOf, CommentsPage>() + val commentRequests = mutableListOf() + var failComments = false + + override suspend fun search(request: SearchRequest): List = emptyList() + + override fun kiosks(serviceId: Int): List = emptyList() + + override suspend fun kiosk(serviceId: Int, kioskId: String): List = emptyList() + + override suspend fun kioskPage( + serviceId: Int, + kioskId: String, + pageIndex: Int + ): List = emptyList() + + override suspend fun streamDetails(serviceId: Int, url: String): StreamDetails = + StreamDetails( + serviceId = serviceId, + url = url, + title = "Test video", + uploader = "Uploader" + ) + + override suspend fun channel(serviceId: Int, url: String): ChannelDetails = + ChannelDetails(serviceId, url, "Channel") + + override suspend fun playlist(serviceId: Int, url: String): PlaylistDetails = + PlaylistDetails(serviceId, url, "Playlist") + + override suspend fun comments(serviceId: Int, url: String, page: Int): CommentsPage { + commentRequests.add(page) + if (failComments) throw ContentException.Network() + return commentsPages[page] ?: CommentsPage() + } + + override suspend fun commentReplies( + serviceId: Int, + streamUrl: String, + commentId: String, + page: Int + ): CommentsPage = replyPages[commentId to page] ?: CommentsPage() + + override suspend fun suggest(query: String): List = emptyList() + + override suspend fun resolveUrl(url: String): ResolvedContent = + throw ContentException.Unsupported("not used") + + override fun availableSearchFilters(serviceId: Int): List = emptyList() + } + + private companion object { + const val STREAM_URL = "https://www.youtube.com/watch?v=test" + } +} From 19aae85f1d96e95ff98843f2877ce1121d724e5b Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 10:38:43 +0530 Subject: [PATCH 02/11] Add likes, local library, upload notifications, and release hardening --- .github/workflows/release-linux.yml | 59 ++- .github/workflows/release-windows.yml | 50 ++- .github/workflows/security.yml | 83 +++- .gitleaks.toml | 3 + INSTALL.md | 2 + README.md | 7 +- SECURITY.md | 6 + docs/ARCHITECTURE.md | 20 +- docs/SECURITY_CHECKS.md | 50 +++ docs/THIRD_PARTY_NOTICES.md | 44 ++ packaging/README.md | 87 ++++ packaging/flatpak/build-flatpak.sh | 34 ++ .../composeResources/drawable/ic_delete.xml | 15 + .../drawable/ic_thumb_down.xml | 15 + .../drawable/ic_watch_later.xml | 15 + .../net/newpipe/app/di/ContentModule.kt | 8 + .../kotlin/net/newpipe/app/model/Content.kt | 4 + .../newpipe/app/model/UploadNotification.kt | 26 ++ .../net/newpipe/app/navigation/Destination.kt | 18 + .../net/newpipe/app/navigation/NavModule.kt | 15 + .../preferences/NotificationPreferences.kt | 61 +++ .../notifications/NotificationsScreen.kt | 388 ++++++++++++++++++ .../app/screen/saved/SavedVideosScreen.kt | 363 ++++++++++++++++ .../app/screen/settings/SettingsHomeScreen.kt | 4 + .../newpipe/app/screen/stream/WatchPage.kt | 128 +++++- .../app/service/SavedVideosRepository.kt | 192 +++++++++ .../service/UploadNotificationRepository.kt | 261 ++++++++++++ .../app/service/UploadNotificationService.kt | 143 +++++++ .../net/newpipe/app/shell/ModernShell.kt | 122 +++++- .../app/service/ExtractorContentRepository.kt | 2 + .../app/service/SavedVideosRepositoryTest.kt | 95 +++++ .../UploadNotificationRepositoryTest.kt | 141 +++++++ 32 files changed, 2396 insertions(+), 65 deletions(-) create mode 100644 docs/SECURITY_CHECKS.md create mode 100644 docs/THIRD_PARTY_NOTICES.md create mode 100644 packaging/README.md create mode 100644 shared/src/commonMain/composeResources/drawable/ic_delete.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_thumb_down.xml create mode 100644 shared/src/commonMain/composeResources/drawable/ic_watch_later.xml create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/model/UploadNotification.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/preferences/NotificationPreferences.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/screen/notifications/NotificationsScreen.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/screen/saved/SavedVideosScreen.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/service/SavedVideosRepository.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationRepository.kt create mode 100644 shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationService.kt create mode 100644 shared/src/jvmTest/kotlin/net/newpipe/app/service/SavedVideosRepositoryTest.kt create mode 100644 shared/src/jvmTest/kotlin/net/newpipe/app/service/UploadNotificationRepositoryTest.kt diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index 56ac90711..86f14f2d4 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -23,15 +23,18 @@ jobs: name: Build Linux Deb, Portable and Flatpak Packages # Ubuntu 22.04 keeps the bundled libVLC compatible with Debian 12, Ubuntu 22.04 and newer. runs-on: ubuntu-22.04 + env: + FLATPAK_GPG_PRIVATE_KEY: ${{ secrets.FLATPAK_GPG_PRIVATE_KEY }} + FLATPAK_GPG_KEY_ID: ${{ secrets.FLATPAK_GPG_KEY_ID }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ github.event.inputs.tag || github.ref }} fetch-depth: 0 - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: distribution: 'temurin' java-version: ${{ env.JAVA_VERSION }} @@ -99,12 +102,25 @@ jobs: tag="${{ github.event.inputs.tag || github.ref_name }}" version="${tag#v}" tarball="np-desktop-${version}-linux-x64.tar.gz" - tar -czf "$tarball" -C "${{ steps.locate.outputs.APP_DIR }}" . + # Reproducible tar metadata: sort entries, pin mtimes and ownership, and use the + # commit timestamp as SOURCE_DATE_EPOCH so rebuilding a tag yields the same archive. + export SOURCE_DATE_EPOCH=$(git log -1 --format=%ct) + tar --sort=name --mtime="@$SOURCE_DATE_EPOCH" --owner=0 --group=0 \ + --numeric-owner -czf "$tarball" -C "${{ steps.locate.outputs.APP_DIR }}" . echo "Found tarball: $tarball ($(du -h "$tarball" | cut -f1))" echo "VERSION=$version" >> "$GITHUB_OUTPUT" echo "TARBALL_PATH=$tarball" >> "$GITHUB_OUTPUT" echo "TARBALL_NAME=$tarball" >> "$GITHUB_OUTPUT" + - name: Generate a CycloneDX SBOM + uses: anchore/sbom-action@v0 + with: + path: ${{ steps.locate.outputs.APP_DIR }} + format: cyclonedx-json + output-file: np-desktop-${{ steps.portable.outputs.VERSION }}-linux-x86_64.cyclonedx.json + upload-artifact: false + upload-release-assets: false + - name: Smoke test the bundled runtime shell: bash run: packaging/linux/smoke-test-vlc.sh "${{ steps.locate.outputs.APP_DIR }}" @@ -121,8 +137,6 @@ jobs: - name: Import the Flatpak signing key if: env.FLATPAK_GPG_PRIVATE_KEY != '' - env: - FLATPAK_GPG_PRIVATE_KEY: ${{ secrets.FLATPAK_GPG_PRIVATE_KEY }} shell: bash run: | export FLATPAK_GPG_HOME="$PWD/.gnupg" @@ -143,6 +157,33 @@ jobs: "${{ steps.portable.outputs.VERSION }}" \ build/flatpak + - name: Install the Flatpak runtime + shell: bash + run: | + flatpak remote-add --user --if-not-exists flathub \ + https://dl.flathub.org/repo/flathub.flatpakrepo + flatpak install --user -y --noninteractive flathub \ + org.freedesktop.Platform//24.08 + + - name: Smoke test the Flatpak bundle + shell: bash + run: | + bundle=$(find build/flatpak -maxdepth 1 -name '*.flatpak' | head -n 1) + test -n "$bundle" + flatpak install --user -y --noninteractive "$bundle" + flatpak info io.github.tauseef666_ctrl.NP_Desktop >/dev/null + # The launcher, the exported desktop file, the AppStream metadata and the bundled + # jars must all be present; this runs without a display or audio server. + flatpak run --command=sh io.github.tauseef666_ctrl.NP_Desktop -c ' + set -e + test -x /app/bin/np-desktop + test -f /app/share/applications/io.github.tauseef666_ctrl.NP_Desktop.desktop + test -f /app/share/metainfo/io.github.tauseef666_ctrl.NP_Desktop.metainfo.xml + test -f /app/files/bin/NP-Desktop + ls /app/files/lib/app/*.jar >/dev/null + ' + flatpak uninstall --user -y io.github.tauseef666_ctrl.NP_Desktop + - name: Generate SHA-256 checksums id: checksum shell: bash @@ -151,17 +192,21 @@ jobs: tarball="${{ steps.portable.outputs.TARBALL_PATH }}" version="${{ steps.portable.outputs.VERSION }}" flatpak="build/flatpak/np-desktop-${version}-x86_64.flatpak" + sbom="np-desktop-${version}-linux-x86_64.cyclonedx.json" { echo "$(sha256sum "$deb" | cut -d' ' -f1) $(basename "$deb")" echo "$(sha256sum "$tarball" | cut -d' ' -f1) $(basename "$tarball")" if [ -f "$flatpak" ]; then echo "$(sha256sum "$flatpak" | cut -d' ' -f1) $(basename "$flatpak")" fi + if [ -f "$sbom" ]; then + echo "$(sha256sum "$sbom" | cut -d' ' -f1) $(basename "$sbom")" + fi } > checksums-linux-sha256.txt cat checksums-linux-sha256.txt - name: Upload Linux artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: desktop-linux path: | @@ -169,6 +214,7 @@ jobs: ${{ steps.portable.outputs.TARBALL_PATH }} build/flatpak/*.flatpak build/flatpak/*.flatpakrepo + np-desktop-${{ steps.portable.outputs.VERSION }}-linux-x86_64.cyclonedx.json checksums-linux-sha256.txt retention-days: 7 @@ -185,6 +231,7 @@ jobs: assets=( "${{ steps.locate.outputs.DEB_PATH }}" "${{ steps.portable.outputs.TARBALL_PATH }}" + "np-desktop-${{ steps.portable.outputs.VERSION }}-linux-x86_64.cyclonedx.json" checksums-linux-sha256.txt ) for file in build/flatpak/*.flatpak build/flatpak/*.flatpakrepo; do diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml index 555038cbf..21fc25354 100644 --- a/.github/workflows/release-windows.yml +++ b/.github/workflows/release-windows.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: tag: - description: 'Tag to build and release (e.g. v0.29.5)' + description: 'Tag to build and release (e.g. v0.26.0)' required: true type: string @@ -25,13 +25,13 @@ jobs: msi_name: ${{ steps.locate.outputs.MSI_NAME }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ github.event.inputs.tag || github.ref }} fetch-depth: 0 - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: distribution: 'temurin' java-version: ${{ env.JAVA_VERSION }} @@ -62,9 +62,20 @@ jobs: Write-Error "No MSI found in build output" exit 1 } + $version = "${{ github.event.inputs.tag || github.ref_name }}".TrimStart('v') Write-Host "Found MSI: $($msi.FullName) ($('{0:N2}' -f ($msi.Length / 1MB)) MB)" echo "MSI_PATH=$($msi.FullName)" >> $env:GITHUB_OUTPUT echo "MSI_NAME=$($msi.Name)" >> $env:GITHUB_OUTPUT + echo "VERSION=$version" >> $env:GITHUB_OUTPUT + + - name: Generate a CycloneDX SBOM + uses: anchore/sbom-action@v0 + with: + path: desktopApp/build/compose/binaries/main + format: cyclonedx-json + output-file: np-desktop-${{ steps.locate.outputs.VERSION }}-windows-x86_64.cyclonedx.json + upload-artifact: false + upload-release-assets: false - name: Generate SHA-256 checksum id: checksum @@ -73,7 +84,10 @@ jobs: $hash = (Get-FileHash "${{ steps.locate.outputs.MSI_PATH }}" -Algorithm SHA256).Hash.ToLower() $checksumLine = "$hash ${{ steps.locate.outputs.MSI_NAME }}" Write-Host "Checksum: $checksumLine" - echo $checksumLine | Out-File -Encoding utf8NoBOM -FilePath checksums-windows-sha256.txt + $sbom = "np-desktop-${{ steps.locate.outputs.VERSION }}-windows-x86_64.cyclonedx.json" + $sbomHash = (Get-FileHash $sbom -Algorithm SHA256).Hash.ToLower() + $lines = @($checksumLine, "$sbomHash $sbom") + $lines | Out-File -Encoding utf8NoBOM -FilePath checksums-windows-sha256.txt echo "SHA256=$hash" >> $env:GITHUB_OUTPUT - name: Stage MSI artifact @@ -82,9 +96,10 @@ jobs: New-Item -ItemType Directory -Path release-assets -Force | Out-Null Copy-Item "${{ steps.locate.outputs.MSI_PATH }}" "release-assets/" -Force Copy-Item "checksums-windows-sha256.txt" "release-assets/" -Force + Copy-Item "np-desktop-${{ steps.locate.outputs.VERSION }}-windows-x86_64.cyclonedx.json" "release-assets/" -Force - name: Upload MSI artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: windows-msi path: release-assets/* @@ -96,10 +111,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Download MSI artifact - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v7 with: name: windows-msi path: release-assets/ @@ -127,15 +142,17 @@ jobs: ### 📦 Downloads | Platform | File | Notes | |----------|------|-------| - | Windows 10/11 (x64) | `NP-Desktop-${{ steps.tag.outputs.VERSION }}.msi` | Bundles the JRE and VLC | - | Debian/Ubuntu (amd64) | `np-desktop_${{ steps.tag.outputs.VERSION }}_amd64.deb` | Requires `vlc` (installed by apt) | + | Windows 10/11 (x64) | `NP-Desktop-${{ steps.tag.outputs.VERSION }}.msi` | Bundles the JRE and the VLC playback runtime | + | Debian/Ubuntu (amd64) | `np-desktop_${{ steps.tag.outputs.VERSION }}_amd64.deb` | Bundles the JRE and the playback runtime | | Any Linux (x64) | `np-desktop-${{ steps.tag.outputs.VERSION }}-linux-x64.tar.gz` | Portable app image, updates itself in-app | + | Linux (x64, sandboxed) | `np-desktop-${{ steps.tag.outputs.VERSION }}-x86_64.flatpak` | Flatpak bundle; updates with `flatpak update` | | Android | `NewPipe_v${{ steps.tag.outputs.VERSION }}.apk` | Phone and Android TV | ### 🔒 Verification Every asset ships with a SHA-256 checksum file: `checksums-windows-sha256.txt`, `checksums-linux-sha256.txt` or - `checksums-apk-sha256.txt`. + `checksums-apk-sha256.txt`. The Linux checksum file covers the DEB, the portable + tarball, the Flatpak bundle and its CycloneDX SBOM. ```bash sha256sum -c checksums-linux-sha256.txt # Linux @@ -145,19 +162,23 @@ jobs: ``` ### ⚙️ System Requirements - - Windows 10/11 (x64), JRE and VLC bundled - - Linux x64 with the VLC runtime (`sudo apt install vlc`, - `sudo pacman -S vlc`, `sudo dnf install vlc`) + - Windows 10/11 (x64): the MSI bundles Java and the VLC runtime + - Linux x64: the DEB, portable tarball and Flatpak all bundle Java and VLC; no + separate `vlc` package is required - Android 6.0 or newer ### 📝 What's Included - Modern desktop UI with Compose Desktop + - Read-only comments with replies, pinned/hearted markers and timestamp seeking + - Like/dislike counts, local Watch later and Liked lists + - New-upload notifications for subscribed channels - Side rail navigation, resizable window, fullscreen modes - YouTube-like keyboard shortcuts - Download manager, local history & subscriptions - Multi-service: YouTube, SoundCloud, PeerTube, Bandcamp, media.ccc.de - In-app updates: `msiexec` on Windows, the `.deb` on Debian based Linux, a - self-replacing portable app image on every other distribution + self-replacing portable app image on every other distribution, and + `flatpak update` for the Flatpak bundle --- Built with ❤️ from [NewPipe](https://github.com/TeamNewPipe/NewPipe) @@ -166,6 +187,7 @@ jobs: files: | release-assets/*.msi release-assets/checksums-windows-sha256.txt + release-assets/*.cyclonedx.json fail_on_unmatched_files: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 210f4c196..632f1f091 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -17,6 +17,11 @@ permissions: security-events: write actions: read +env: + JAVA_VERSION: '21' + DEPENDENCY_CHECK_VERSION: '13.0.0' + GITLEAKS_VERSION: '8.30.1' + jobs: codeql: name: CodeQL (Java/Kotlin) @@ -26,12 +31,28 @@ jobs: contents: read steps: - uses: actions/checkout@v6 - - uses: github/codeql-action/init@v3 + + - name: Set up JDK ${{ env.JAVA_VERSION }} + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: ${{ env.JAVA_VERSION }} + cache: gradle + + - uses: github/codeql-action/init@v4 with: languages: java-kotlin queries: security-and-quality - - uses: github/codeql-action/autobuild@v3 - - uses: github/codeql-action/analyze@v3 + # The Kotlin Multiplatform build is not detected reliably by autobuild, so the + # analysis compiles the desktop target explicitly below. + build-mode: manual + + - name: Compile the desktop target for the analysis + run: | + ./gradlew :shared:compileKotlinJvm :desktopApp:compileKotlin \ + --no-daemon --no-configuration-cache + + - uses: github/codeql-action/analyze@v4 dependency-check: name: Dependency-Check, Trivy and SBOM @@ -39,15 +60,15 @@ jobs: steps: - uses: actions/checkout@v6 - - name: Set up JDK 21 - uses: actions/setup-java@v5 + - name: Set up JDK ${{ env.JAVA_VERSION }} + uses: actions/setup-java@v6 with: - java-version: 21 + java-version: ${{ env.JAVA_VERSION }} distribution: temurin cache: gradle - name: Cache the NVD data - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ~/.dependency-check/data key: dependency-check-${{ runner.os }}-${{ hashFiles('gradle/libs.versions.toml') }} @@ -55,12 +76,15 @@ jobs: dependency-check-${{ runner.os }}- - name: Build the desktop app image - run: ./gradlew :desktopApp:createReleaseDistributable --no-daemon + run: | + ./gradlew :desktopApp:createReleaseDistributable \ + --no-daemon --no-configuration-cache - name: Locate the app image id: locate run: | - app=$(find desktopApp/build/compose/binaries/main-release/app -maxdepth 1 -mindepth 1 -type d | head -n 1) + app=$(find desktopApp/build/compose/binaries/main-release/app \ + -maxdepth 1 -mindepth 1 -type d | head -n 1) test -n "$app" echo "APP_DIR=$app" >> "$GITHUB_OUTPUT" @@ -69,7 +93,7 @@ jobs: NVD_API_KEY: ${{ secrets.NVD_API_KEY }} run: | curl -fsSL -o /tmp/dependency-check.zip \ - https://github.com/dependency-check/DependencyCheck/releases/download/v12.1.0/dependency-check-12.1.0-release.zip + "https://github.com/dependency-check/DependencyCheck/releases/download/v${DEPENDENCY_CHECK_VERSION}/dependency-check-${DEPENDENCY_CHECK_VERSION}-release.zip" unzip -q /tmp/dependency-check.zip -d /tmp args=( --project "NP Desktop" @@ -78,7 +102,6 @@ jobs: --format JSON --out dependency-check-report --failOnCVSS 7 - --enableExperimental ) if [ -n "$NVD_API_KEY" ]; then args+=(--nvdApiKey "$NVD_API_KEY") @@ -86,7 +109,7 @@ jobs: /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" - name: Run Trivy on the packaged libraries - uses: aquasecurity/trivy-action@0.28.0 + uses: aquasecurity/trivy-action@0.36.0 with: scan-type: fs scan-ref: ${{ steps.locate.outputs.APP_DIR }}/lib/app @@ -96,19 +119,24 @@ jobs: format: table - name: Generate a CycloneDX SBOM + if: always() uses: anchore/sbom-action@v0 with: path: ${{ steps.locate.outputs.APP_DIR }} format: cyclonedx-json output-file: sbom-linux.cyclonedx.json - artifact-name: sbom-linux.cyclonedx.json + upload-artifact: false + upload-release-assets: false - - name: Upload the dependency report + - name: Upload the reports if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: - name: dependency-check-report - path: dependency-check-report/ + name: security-reports + path: | + dependency-check-report/ + sbom-linux.cyclonedx.json + if-no-files-found: warn retention-days: 14 gitleaks: @@ -118,6 +146,21 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - - uses: gitleaks/gitleaks-action@v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # The gitleaks GitHub action requires a paid licence for organisations; the CLI is free + # and scans the same history with the repository configuration. + - name: Install gitleaks + run: | + curl -fsSL -o /tmp/gitleaks.tar.gz \ + "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" + tar -xzf /tmp/gitleaks.tar.gz -C /tmp gitleaks + /tmp/gitleaks version + + - name: Scan the repository history + run: | + /tmp/gitleaks detect \ + --source . \ + --config .gitleaks.toml \ + --redact \ + --verbose \ + --exit-code 1 diff --git a/.gitleaks.toml b/.gitleaks.toml index 961baf9cd..9179e410e 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -16,6 +16,9 @@ paths = [ '''shared/src/androidDeviceTest/.*''', '''app/src/test/.*''', '''app/src/androidTest/.*''', + # YouTube publishes this request key in its own web client page source; it is a public + # platform constant, not a project credential. + '''app/src/main/java/org/schabi/newpipe/util/potoken/PoTokenWebView.kt''', '''gradle/wrapper/gradle-wrapper.jar''', '''.*\.png''', ] diff --git a/INSTALL.md b/INSTALL.md index dced9cbc2..59749645f 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -123,6 +123,8 @@ StartupNotify=true Replace `` with your user name, then start `np-desktop` once from the terminal to confirm the install. +On first launch after upgrading from a pre-0.26 build, Linux settings are migrated from `~/NP-Desktop/settings.properties` to `~/.config/NP-Desktop/settings.properties`. The migration only runs while the new file does not exist; the old directory is left untouched, so you can remove it after confirming your subscriptions and history are intact. + ## Linux Installation (Flatpak) The Flatpak bundle is sandboxed and ships the same app image, JRE and playback runtime. It only asks for network, display, audio, GPU and the Downloads/Pictures folders; your home directory is not exposed. diff --git a/README.md b/README.md index b6395185b..bd76cedb0 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,9 @@ - **YouTube video and audio playback** — quality ladder including 1080p+, audio-only listening, and made-for-kids videos (via a local SABR relay) - **Search, trending, and subscriptions feeds** — with kiosk sections (Feed, Trending, Live, Gaming, Music, Movies & Shows, Podcasts) - **Downloads** — built-in download options UI: muxed or adaptive streams, with quality and format choice +- **Read-only comments** — paginated comments with replies, pinned/hearted markers, avatars, likes and timestamp seeking, without signing in +- **Likes and local library** — like/dislike counts on the watch page, plus local Watch later and Liked lists that never leave the device +- **New-upload notifications** — an in-app notification centre checks subscribed channels while the app is running, with a configurable interval and manual check - **Glassmorphism UI** — modern desktop shell with side rail navigation, resizable window, and a unified context menu across feeds, search results, channel pages, history, playlists, and the player - **Windows and Android TV form factors** — proper windowing and keyboard shortcuts on desktop; D-pad/remote navigation on TV - **Fullscreen player** — toggle with `F` or `F11`; mini-player to keep watching while browsing; media key support @@ -155,7 +158,7 @@ packaging/flatpak/build-flatpak.sh desktopApp/build/compose/binaries/main-releas Portable app image (any distribution): ```bash -./gradlew --no-configuration-cache :desktopApp:createReleaseDistributable +./gradlew --no-configuration-cache :desktopApp:createReleaseDistributable -PvlcPrefix="$PWD/build/vlc-runtime" tar -czf np-desktop-linux-x64.tar.gz -C desktopApp/build/compose/binaries/main-release/app/NP-Desktop . ``` @@ -182,6 +185,8 @@ Start with `good first issue` labeled issues if you are new. This project is licensed under the **GNU General Public License v3.0 or later** (GPL-3.0-or-later). See [LICENSE](LICENSE) for details. SPDX headers in the source follow the [REUSE](https://reuse.software/) convention and credit NewPipe e.V. +Bundled third-party components (libVLC/VLC plugins, VLCJ, FFmpeg/JAVE, JNA, the JRE and the Flatpak runtime) are listed with their licences in [docs/THIRD_PARTY_NOTICES.md](docs/THIRD_PARTY_NOTICES.md). + ## Security See [SECURITY.md](SECURITY.md) for the security policy, how to report vulnerabilities, and a statement on how the app handles data. diff --git a/SECURITY.md b/SECURITY.md index 12f255d54..5df48b556 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,6 +60,12 @@ For context when assessing reports: See [PRIVACY.md](PRIVACY.md) for the full privacy statement. +## Security Checks + +The repository runs CodeQL, OWASP Dependency-Check, Trivy, a CycloneDX SBOM and Gitleaks in the +`Security` GitHub Actions workflow. See [docs/SECURITY_CHECKS.md](docs/SECURITY_CHECKS.md) for what +each check covers, how to run it locally, and which findings fail the build. + ## Upstream This is a fork of [NewPipe](https://github.com/TeamNewPipe/NewPipe). If a vulnerability affects shared components, it may also need to be reported upstream. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e0feaf1b1..744f7aad7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -18,10 +18,12 @@ NewPipe (upstream dev) │ ├── androidMain extractor-backed implementations (Android) │ ├── jvmMain extractor-backed implementations (Windows desktop) · DB · downloads │ └── iosMain explicit stubs for extractor-backed features -└── desktopApp/ Kotlin JVM — Windows entry point, window mgmt, VLCJ host, native dialogs +└── desktopApp/ Kotlin JVM — Windows/Linux entry point, window mgmt, VLCJ host, native dialogs ``` -**Media engine**: libVLC 3.0.21 driven by **VLCJ 4.11.0**. +**Media engine**: libVLC 3.0.x (the build host's version) driven by **VLCJ 4.11.0**. Linux release +packages embed a portable libVLC runtime and extract it on first launch; Windows packages bundle +the VLC installation from the build machine. --- @@ -248,8 +250,12 @@ secrets when explicitly configured. | Path | Purpose | |---|---| -| `%APPDATA%\NewPipe\` | Settings, window state | -| `%APPDATA%\NewPipe\newpipe.db` | Room database | -| `%APPDATA%\NewPipe\downloads\` | Default download directory | -| `%LOCALAPPDATA%\NewPipe\logs\` | Application logs (Kermit) | -| `libVLC` | Provisioned into the distribution image by the `vlc-setup` plugin | +| `%APPDATA%\NP-Desktop\` | Settings, window state | +| `%APPDATA%\NP-Desktop\newpipe.db` | Room database | +| `%APPDATA%\NP-Desktop\downloads\` | Default download directory | +| `%APPDATA%\NP-Desktop\logs\` | Application logs (Kermit) | +| `~/.config/NP-Desktop/` (Linux) | Settings, session and download preferences | +| `~/.local/share/NP-Desktop/` (Linux) | Extracted libVLC runtime and durable data | +| `~/.local/state/NP-Desktop/` (Linux) | Logs | +| `~/.cache/NP-Desktop/` (Linux) | Image and thumbnail cache | +| `libVLC` | Provisioned into the distribution image by `vlc-setup` (Windows) or built into a portable `vlc-runtime.zip` by `packaging/linux/build-vlc-runtime.sh` (Linux) | diff --git a/docs/SECURITY_CHECKS.md b/docs/SECURITY_CHECKS.md new file mode 100644 index 000000000..545c35247 --- /dev/null +++ b/docs/SECURITY_CHECKS.md @@ -0,0 +1,50 @@ +# Security Checks + +The `Security` workflow runs on every push and pull request to `main`, weekly on a schedule, and +on demand. It complements, but does not replace, reviewing changes before they are merged. + +## What runs + +| Job | Tool | Scope | Fails the build when | +| --- | --- | --- | --- | +| `codeql` | GitHub CodeQL (`java-kotlin`, `security-and-quality`) | `shared/`, `desktopApp/` and the rest of the Kotlin sources, compiled with `:shared:compileKotlinJvm :desktopApp:compileKotlin` | CodeQL reports a security alert at the configured severity for the query pack | +| `dependency-check` | OWASP Dependency-Check 13 | The jars in the packaged app image (`app/lib/app`) | Any dependency has a CVSS score of 7.0 or higher | +| `dependency-check` | Trivy | The same packaged jars | A HIGH or CRITICAL vulnerability with an available fix is found | +| `dependency-check` | Anchore Syft (`sbom-action`) | The packaged app image | Never; it produces `sbom-linux.cyclonedx.json` as an artifact | +| `gitleaks` | Gitleaks 8.30 CLI | Full git history | A secret matching the rules in `.gitleaks.toml` is found | + +The dependency report, JSON result and SBOM are uploaded as the `security-reports` artifact even +when a scan fails, so failures can be triaged. + +## Running locally + +```bash +# Secret scan (requires the gitleaks binary) +gitleaks detect --source . --config .gitleaks.toml --redact --verbose + +# Dependency check against a local app image +./gradlew :desktopApp:createReleaseDistributable +dependency-check.sh \ + --project "NP Desktop" \ + --scan desktopApp/build/compose/binaries/main-release/app/*/lib/app \ + --format HTML --out dependency-check-report --failOnCVSS 7 + +# Trivy on the same jars +trivy fs --scanners vuln --severity HIGH,CRITICAL \ + desktopApp/build/compose/binaries/main-release/app/*/lib/app + +# SBOM +syft desktopApp/build/compose/binaries/main-release/app -o cyclonedx-json=sbom.cyclonedx.json +``` + +`NVD_API_KEY` is optional. Without it Dependency-Check uses the public NVD feed, which is slower and +rate limited; the workflow caches the NVD data between runs. + +## Notes + +- The build job runs without a bundled libVLC runtime. Packaging and playback are covered by the + release workflows, not by the security workflow. +- Gitleaks excludes test fixtures and binary assets through `.gitleaks.toml`; source files are + still scanned with the default rules. +- Dependabot opens weekly pull requests for Gradle, GitHub Actions and Docker updates. Review and + merge them through the normal CI. diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..3565c1ece --- /dev/null +++ b/docs/THIRD_PARTY_NOTICES.md @@ -0,0 +1,44 @@ +# Third-Party Notices + +NP Desktop is licensed under GPL-3.0-or-later. The desktop packages also contain or depend on the +following third-party components. Their own licences apply to those components; this file is a +notice, not a replacement for the licence texts. + +## Bundled with the desktop packages + +| Component | Version / source | Licence | Notes | +| --- | --- | --- | --- | +| libVLC, libvlccore and VLC plugins | The VLC media player release matching the build host, from [VideoLAN](https://www.videolan.org/vlc/) | libVLC is LGPL-2.1-or-later; VLC and several plugins are GPL-2.0-or-later | The Linux runtime is assembled from the distribution's VLC packages by `packaging/linux/build-vlc-runtime.sh`. It is dynamically loaded by the app. | +| VLCJ | 4.11.0, [caprica/vlcj](https://github.com/caprica/vlcj) | GPL-3.0-or-later | JVM binding used to drive libVLC. | +| FFmpeg libraries | As shipped with the VLC packages and the JAVE binaries | LGPL-2.1-or-later; optional GPL parts depending on the build | Used for decoding inside VLC and for muxing downloaded streams. | +| JAVE (`ws.schild:jave-all-deps`) | 3.5.0, [jave](https://github.com/beatgammit/jave) | GPL-3.0-or-later (or a commercial licence from the author) | Bundles static FFmpeg binaries for the download muxer. | +| Java Native Access (JNA) | 5.x, [java-native-access/jna](https://github.com/java-native-access/jna) | Apache-2.0 or LGPL-2.1 | Loads libVLC and sets the plugin path. | +| Eclipse Temurin JRE | 21, [Adoptium](https://adoptium.net/) | GPL-2.0-or-later with the Classpath Exception | Bundled by jpackage; not required separately. | + +The rest of the Kotlin and Compose dependencies (Kotlin, Compose Multiplatform, Coroutines, +kotlinx.serialization, Koin, OkHttp, Coil, SQLDelight and their transitive libraries) are listed in +`gradle/libs.versions.toml` and are predominantly Apache-2.0. The Gradle dependency graph is the +authoritative list; `./gradlew :desktopApp:dependencies` prints it. + +## Flatpak + +The Flatpak bundle uses the `org.freedesktop.Platform` 24.08 runtime, which is distributed by the +Flatpak project under the licences of its component projects. The runtime is not embedded in the +`.flatpak` file; Flatpak installs it separately. + +## Source and relinking + +The bundled libVLC runtime is modified only mechanically (stripped symbols and an `$ORIGIN` RPATH +so the libraries load from the app directory). The build script that produces it is part of this +repository, and the corresponding VLC and FFmpeg source code is available from +[VideoLAN](https://www.videolan.org/vlc/download-sources.html) and +[FFmpeg](https://ffmpeg.org/download.html). If you need the exact source or object files for +LGPL relinking, open an issue and they will be provided. + +## Full licence texts + +- GPL-2.0: +- GPL-3.0: +- LGPL-2.1: +- Apache-2.0: +- Classpath Exception: diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 000000000..c9cc247b7 --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,87 @@ +# Desktop Packaging + +The release workflows build the Windows MSI and the Linux DEB, portable tarball and Flatpak. This +document describes the local equivalents and the inputs they need. + +## Linux: DEB and portable tarball + +Requirements: JDK 21, `patchelf` **0.19.3 or newer**, `libvlc5`/`libvlccore9`/`vlc-plugin-base`, +`file`, `ffmpeg`. On Ubuntu 22.04 the packaged `patchelf` is 0.14 and corrupts RELR relocations in +modern libraries; install the 0.19.3 static build instead. + +```bash +# 1. Build the portable playback runtime from the system VLC installation. +packaging/linux/build-vlc-runtime.sh build/vlc-runtime + +# 2. Build the app image and the DEB with that runtime embedded. +./gradlew :desktopApp:packageReleaseDeb :desktopApp:createReleaseDistributable \ + -PvlcPrefix="$PWD/build/vlc-runtime" + +# 3. Package the app image exactly like the release workflow. +tar --sort=name --mtime="@$(git log -1 --format=%ct)" --owner=0 --group=0 \ + --numeric-owner -czf np-desktop-0.26.0-linux-x64.tar.gz \ + -C desktopApp/build/compose/binaries/main-release/app/* . + +# 4. Verify that the runtime loads and plays without a system VLC. +packaging/linux/smoke-test-vlc.sh desktopApp/build/compose/binaries/main-release/app/* +``` + +Without `-PvlcPrefix`, `VLC_HOME`, or the Gradle `vlc-setup` cache, the build removes +`desktopApp/src/main/resources/vlc-runtime.zip` and the app image falls back to a system libVLC. +Release builds must always pass `-PvlcPrefix`. + +## Linux: Flatpak + +Requirements: `flatpak` and the `org.freedesktop.Platform//24.08` runtime. The app image must +already contain the JRE and libVLC. + +```bash +packaging/flatpak/build-flatpak.sh \ + desktopApp/build/compose/binaries/main-release/app/* \ + 0.26.0 build/flatpak +``` + +The script exports the app image plus the desktop file, icon and AppStream metadata, then writes +`build/flatpak/np-desktop-0.26.0-x86_64.flatpak`. It does not need `flatpak-builder` because the +self-contained app image is copied into `/app/files`. + +### Signing + +The bundle is unsigned unless `FLATPAK_GPG_KEY_ID` points at a key in `FLATPAK_GPG_HOME` +(default `~/.gnupg`). With a key the script also writes a signed OSTree repo, the exported public +key and an `.flatpakrepo` file. The release workflow imports `FLATPAK_GPG_PRIVATE_KEY` when that +secret exists; without it the release still succeeds and publishes the unsigned bundle. + +### Smoke test + +```bash +flatpak install --user -y build/flatpak/np-desktop-0.26.0-x86_64.flatpak +flatpak run --command=sh io.github.tauseef666_ctrl.NP_Desktop -c \ + 'test -x /app/bin/np-desktop && ls /app/files/lib/app/*.jar' +flatpak uninstall --user -y io.github.tauseef666_ctrl.NP_Desktop +``` + +The release workflow installs the runtime, imports the bundle, checks the exported desktop and +metainfo files and the bundled jars, and uninstalls it again. A full playback test still needs a +display and audio server. + +## Windows: MSI + +Requirements: JDK 21 and a VLC installation (`VLC_HOME` or the Gradle `vlc-setup` cache). + +```powershell +./gradlew.bat :desktopApp:packageMsi +``` + +The MSI lands in `desktopApp/build/compose/binaries/main/msi/`. The workflow installs VLC with +Chocolatey, sets `VLC_HOME`, and publishes the MSI plus `checksums-windows-sha256.txt`. + +## SBOM and checksums + +The release workflows generate CycloneDX SBOMs with Syft and SHA-256 checksums for every +artifact. The Linux checksum file covers the DEB, tarball, Flatpak and SBOM; the Windows file +covers the MSI and SBOM. Verify with: + +```bash +sha256sum -c checksums-linux-sha256.txt +``` diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh index 30ae704d9..c7e840c87 100755 --- a/packaging/flatpak/build-flatpak.sh +++ b/packaging/flatpak/build-flatpak.sh @@ -41,6 +41,7 @@ command -v flatpak >/dev/null 2>&1 || fail "flatpak is not installed" rm -rf "$OUT" mkdir -p "$STAGE/files" "$STAGE/bin" \ "$STAGE/export/share/applications" \ + "$STAGE/export/share/metainfo" \ "$STAGE/export/share/icons/hicolor/256x256/apps" cp -a "$APP_IMAGE/." "$STAGE/files/" @@ -67,6 +68,39 @@ Keywords=YouTube;PeerTube;SoundCloud;video;streaming; StartupWMClass=NP-Desktop EOF +# AppStream metadata: Flatpak and software centres expect it next to the desktop file. +RELEASE_DATE=$(date -u -d "@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y-%m-%d) +cat > "$STAGE/export/share/metainfo/$APP_ID.metainfo.xml" < + + $APP_ID + NP Desktop + Libre lightweight streaming client + CC0-1.0 + GPL-3.0-or-later + +

+ NP Desktop plays video and audio from YouTube and other supported services without ads, + tracking or an account. Subscriptions, history and preferences stay on the device. +

+

+ The application bundles its own Java runtime and playback runtime, so no separate VLC or + Java installation is required. +

+
+ $APP_ID.desktop + https://github.com/Tauseef666-ctrl/NP-Desktop + https://github.com/Tauseef666-ctrl/NP-Desktop/issues + + Tauseef Khan + + + + + +
+EOF + # The runtime supplies glibc, the graphics stack and the audio servers. The app only gets # network access, the display/audio sockets, the GPU device and the two user folders it # actually writes to; the home directory stays private. diff --git a/shared/src/commonMain/composeResources/drawable/ic_delete.xml b/shared/src/commonMain/composeResources/drawable/ic_delete.xml new file mode 100644 index 000000000..ecf359b99 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_delete.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_thumb_down.xml b/shared/src/commonMain/composeResources/drawable/ic_thumb_down.xml new file mode 100644 index 000000000..ec7fe709f --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_thumb_down.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/composeResources/drawable/ic_watch_later.xml b/shared/src/commonMain/composeResources/drawable/ic_watch_later.xml new file mode 100644 index 000000000..e311ed274 --- /dev/null +++ b/shared/src/commonMain/composeResources/drawable/ic_watch_later.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/di/ContentModule.kt b/shared/src/commonMain/kotlin/net/newpipe/app/di/ContentModule.kt index 32f1836e2..eddea391b 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/di/ContentModule.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/di/ContentModule.kt @@ -5,13 +5,17 @@ package net.newpipe.app.di +import net.newpipe.app.preferences.NotificationPreferences import net.newpipe.app.service.ContentRepository import net.newpipe.app.service.DownloadRepository import net.newpipe.app.service.MediaDownloader import net.newpipe.app.service.PlaylistRepository import net.newpipe.app.service.QueueRepository +import net.newpipe.app.service.SavedVideosRepository import net.newpipe.app.service.SearchHistoryRepository import net.newpipe.app.service.SubscriptionRepository +import net.newpipe.app.service.UploadNotificationRepository +import net.newpipe.app.service.UploadNotificationService import net.newpipe.app.service.PlaybackController import net.newpipe.app.service.ServiceRegistry import net.newpipe.app.service.WatchHistoryRepository @@ -40,9 +44,13 @@ fun contentModule( single { playerUiState ?: PlayerUiState() } single { WatchHistoryRepository(get()) } single { PlaylistRepository(get()) } + single { SavedVideosRepository(get()) } single { QueueRepository(get(), get()) } single { DownloadRepository(get()) } single { SearchHistoryRepository(get()) } single { SubscriptionRepository(get()) } + single { NotificationPreferences(get()) } + single { UploadNotificationRepository(get()) } + single { UploadNotificationService(get(), get(), get(), get()) } single { MediaDownloader() } } diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/model/Content.kt b/shared/src/commonMain/kotlin/net/newpipe/app/model/Content.kt index 509b026b0..d9b8e8d44 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/model/Content.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/model/Content.kt @@ -87,6 +87,10 @@ data class StreamDetails( val description: String? = null, val durationSeconds: Long? = null, val viewCount: Long? = null, + /** The number of likes, or `null` when the service does not expose it. */ + val likeCount: Long? = null, + /** The number of dislikes, or `null` when the service does not expose it. */ + val dislikeCount: Long? = null, val uploadDate: String? = null, val liveNow: Boolean = false, val videoStreams: List = emptyList(), diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/model/UploadNotification.kt b/shared/src/commonMain/kotlin/net/newpipe/app/model/UploadNotification.kt new file mode 100644 index 000000000..23250443a --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/model/UploadNotification.kt @@ -0,0 +1,26 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.model + +/** + * A new upload of a subscribed channel that the app has not shown yet. + * + * Notifications are local only: the upload is discovered by asking the extraction engine for the + * channel's latest videos, nothing is sent to the service and no account is involved. + */ +data class UploadNotification( + /** The canonical url of the video, also used as identifier. */ + val videoUrl: String, + val serviceId: Int, + val videoTitle: String, + val channelUrl: String, + val channelName: String, + val thumbnailUrl: String? = null, + val uploadDate: String? = null, + /** When the app discovered the upload, in epoch milliseconds. */ + val discoveredAt: Long = 0L, + val read: Boolean = false +) diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/navigation/Destination.kt b/shared/src/commonMain/kotlin/net/newpipe/app/navigation/Destination.kt index fb01c4db8..1b799db3c 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/navigation/Destination.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/navigation/Destination.kt @@ -116,5 +116,23 @@ sealed interface Destination : NavKey { */ @Serializable data object LocalPlaylists : Destination + + /** + * The videos the user saved to watch later. + */ + @Serializable + data object WatchLater : Destination + + /** + * The videos the user liked locally. + */ + @Serializable + data object LikedVideos : Destination + + /** + * The new uploads of the subscribed channels, with the check settings. + */ + @Serializable + data object Notifications : Destination } diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/navigation/NavModule.kt b/shared/src/commonMain/kotlin/net/newpipe/app/navigation/NavModule.kt index 0ae23535f..3b5a94e1f 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/navigation/NavModule.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/navigation/NavModule.kt @@ -12,8 +12,11 @@ import net.newpipe.app.screen.channel.ChannelScreen import net.newpipe.app.screen.downloads.DownloadsScreen import net.newpipe.app.screen.feed.FeedScreen import net.newpipe.app.screen.home.HomeScreen +import net.newpipe.app.screen.notifications.NotificationsScreen import net.newpipe.app.screen.playlist.PlaylistScreen import net.newpipe.app.screen.playlist.PlaylistsScreen +import net.newpipe.app.screen.saved.SavedVideoList +import net.newpipe.app.screen.saved.SavedVideosScreen import net.newpipe.app.screen.search.SearchScreen import net.newpipe.app.screen.settings.AccountSettingsScreen import net.newpipe.app.screen.settings.AppearanceSettingsScreen @@ -129,6 +132,18 @@ fun navModule() = module { navigation { PlaylistsScreen() } + + navigation { + SavedVideosScreen(SavedVideoList.WatchLater) + } + + navigation { + SavedVideosScreen(SavedVideoList.Liked) + } + + navigation { + NotificationsScreen() + } } /** diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/preferences/NotificationPreferences.kt b/shared/src/commonMain/kotlin/net/newpipe/app/preferences/NotificationPreferences.kt new file mode 100644 index 000000000..a1fc01983 --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/preferences/NotificationPreferences.kt @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.preferences + +import com.russhwolf.settings.Settings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * Persists the new-upload notification settings. + * + * Notifications are checked while the app runs; there is no background service, so nothing is + * fetched while the app is closed. The interval is stored in minutes and defaults to one hour. + */ +class NotificationPreferences( + private val settings: Settings +) { + + private val _enabled = MutableStateFlow( + settings.getBoolean(KEY_ENABLED, DEFAULT_ENABLED) + ) + + /** Whether uploads of subscribed channels are checked at all. */ + val enabled: StateFlow = _enabled.asStateFlow() + + private val _intervalMinutes = MutableStateFlow( + settings.getInt(KEY_INTERVAL, DEFAULT_INTERVAL_MINUTES) + .coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + ) + + /** The number of minutes between two automatic checks. */ + val intervalMinutes: StateFlow = _intervalMinutes.asStateFlow() + + fun setEnabled(enabled: Boolean) { + _enabled.value = enabled + settings.putBoolean(KEY_ENABLED, enabled) + } + + fun setIntervalMinutes(minutes: Int) { + val coerced = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + _intervalMinutes.value = coerced + settings.putInt(KEY_INTERVAL, coerced) + } + + companion object { + const val DEFAULT_ENABLED = true + const val DEFAULT_INTERVAL_MINUTES = 60 + const val MIN_INTERVAL_MINUTES = 15 + const val MAX_INTERVAL_MINUTES = 360 + + /** The selectable intervals shown in the settings, in minutes. */ + val INTERVAL_CHOICES = listOf(15, 30, 60, 120, 240, 360) + + private const val KEY_ENABLED = "upload_notifications_enabled_v1" + private const val KEY_INTERVAL = "upload_notifications_interval_v1" + } +} diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/notifications/NotificationsScreen.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/notifications/NotificationsScreen.kt new file mode 100644 index 000000000..e2c8fd572 --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/notifications/NotificationsScreen.kt @@ -0,0 +1,388 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.screen.notifications + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import coil3.compose.AsyncImage +import net.newpipe.app.composable.TopAppBar +import net.newpipe.app.model.UploadNotification +import net.newpipe.app.navigation.Destination +import net.newpipe.app.navigation.Navigator +import net.newpipe.app.preferences.NotificationPreferences +import net.newpipe.app.service.SubscriptionRepository +import net.newpipe.app.service.UploadNotificationRepository +import net.newpipe.app.service.UploadNotificationService +import net.newpipe.app.ui.Radius +import net.newpipe.app.ui.Spacing +import newpipe.shared.generated.resources.Res +import newpipe.shared.generated.resources.ic_notifications +import newpipe.shared.generated.resources.ic_play_arrow +import org.jetbrains.compose.resources.painterResource +import org.koin.compose.koinInject + +/** + * The notification centre: the new uploads of subscribed channels, plus the check settings. + * + * Notifications are in-app only and are created while the app is running. Clicking one opens the + * video and marks it read; the whole list can be marked read or cleared. + */ +@Composable +fun NotificationsScreen( + navigator: Navigator = koinInject(), + notificationRepository: UploadNotificationRepository = koinInject(), + service: UploadNotificationService = koinInject(), + preferences: NotificationPreferences = koinInject(), + subscriptionRepository: SubscriptionRepository = koinInject() +) { + val notifications by notificationRepository.notifications.collectAsState() + val subscriptions by subscriptionRepository.subscriptions.collectAsState() + val enabled by preferences.enabled.collectAsState() + val interval by preferences.intervalMinutes.collectAsState() + val checking by service.checking.collectAsState() + val lastCheck by service.lastCheck.collectAsState() + val unread = notifications.count { !it.read } + + Scaffold( + topBar = { + TopAppBar( + title = "Notifications", + onNavigateUp = navigator::navigateUp, + actions = { + if (notifications.isNotEmpty()) { + TextButton(onClick = notificationRepository::markAllRead) { + Text("Mark all read") + } + TextButton(onClick = notificationRepository::clear) { + Text("Clear") + } + } + } + ) + } + ) { paddingValues -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(top = paddingValues.calculateTopPadding()), + contentPadding = PaddingValues(Spacing.lg), + verticalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + item(key = "settings") { + NotificationSettingsPanel( + enabled = enabled, + intervalMinutes = interval, + checking = checking, + lastCheck = lastCheck, + hasSubscriptions = subscriptions.isNotEmpty(), + onEnabledChange = preferences::setEnabled, + onIntervalChange = preferences::setIntervalMinutes, + onCheckNow = { + if (!enabled) preferences.setEnabled(true) + service.checkNow() + } + ) + } + + if (notifications.isEmpty()) { + item(key = "empty") { + NotificationsEmptyState(checking = checking) + } + } else { + item(key = "unread-count") { + Text( + text = if (unread == 0) { + "No unread notifications" + } else { + "$unread unread" + }, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + items(notifications, key = { it.videoUrl }) { notification -> + NotificationRow( + notification = notification, + onClick = { + notificationRepository.markRead(notification.videoUrl) + navigator.navigateTo( + Destination.Stream(notification.serviceId, notification.videoUrl) + ) + } + ) + } + } + } + } +} + +@Composable +private fun NotificationSettingsPanel( + enabled: Boolean, + intervalMinutes: Int, + checking: Boolean, + lastCheck: Long?, + hasSubscriptions: Boolean, + onEnabledChange: (Boolean) -> Unit, + onIntervalChange: (Int) -> Unit, + onCheckNow: () -> Unit +) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerLow, + shape = RoundedCornerShape(Radius.lg), + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(Spacing.md), + verticalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "New uploads", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold + ) + Text( + text = "Checks your subscribed channels while the app is open.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch(checked = enabled, onCheckedChange = onEnabledChange) + } + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + Text( + text = "Check every", + style = MaterialTheme.typography.bodyMedium + ) + if (enabled) { + NotificationPreferences.INTERVAL_CHOICES.forEach { choice -> + FilterChip( + selected = intervalMinutes == choice, + onClick = { onIntervalChange(choice) }, + label = { Text(intervalLabel(choice)) } + ) + } + } + } + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + Text( + text = when { + !hasSubscriptions -> "Subscribe to channels to see new uploads here." + checking -> "Checking for new uploads\u2026" + lastCheck != null -> "Last check ${relativeTime(lastCheck)}" + else -> "Not checked yet" + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f) + ) + if (checking) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } else { + OutlinedButton( + onClick = onCheckNow, + contentPadding = PaddingValues(horizontal = Spacing.md, vertical = Spacing.xs) + ) { + Text("Check now") + } + } + } + } + } +} + +@Composable +private fun NotificationsEmptyState(checking: Boolean) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = Spacing.xl * 2), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(Spacing.md) + ) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(Radius.lg) + ) { + Icon( + painter = painterResource(Res.drawable.ic_notifications), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .padding(Spacing.lg) + .size(32.dp) + ) + } + Text( + text = if (checking) "Checking your subscriptions" else "No new uploads", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "New videos from subscribed channels show up here after a check.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} + +@Composable +private fun NotificationRow( + notification: UploadNotification, + onClick: () -> Unit +) { + Surface( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick), + color = if (notification.read) { + MaterialTheme.colorScheme.surfaceContainerLow + } else { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.35f) + }, + shape = RoundedCornerShape(Radius.md) + ) { + Row( + modifier = Modifier.padding(Spacing.sm), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .width(160.dp) + .clip(RoundedCornerShape(Radius.sm)) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + ) { + Box(modifier = Modifier.size(width = 160.dp, height = 90.dp)) { + notification.thumbnailUrl?.let { url -> + AsyncImage( + model = url, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + } + } + } + + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = Spacing.md), + verticalArrangement = Arrangement.spacedBy(Spacing.xs) + ) { + Text( + text = notification.videoTitle, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (notification.read) FontWeight.Normal else FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Text( + text = notification.channelName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = relativeTime(notification.discoveredAt), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + if (!notification.read) { + Box( + modifier = Modifier + .padding(end = Spacing.xs) + .size(8.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary) + ) + } + + IconButton(onClick = onClick) { + Icon( + painter = painterResource(Res.drawable.ic_play_arrow), + contentDescription = "Open video", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp) + ) + } + } + } +} + +private fun intervalLabel(minutes: Int): String = when { + minutes < 60 -> "${minutes}m" + minutes == 60 -> "1h" + minutes % 60 == 0 -> "${minutes / 60}h" + else -> "${minutes}m" +} + +private fun relativeTime(timestamp: Long): String { + if (timestamp <= 0L) return "" + val elapsed = System.currentTimeMillis() - timestamp + val minutes = elapsed / 60_000L + return when { + minutes < 1 -> "just now" + minutes < 60 -> "${minutes}m ago" + minutes < 24 * 60 -> "${minutes / 60}h ago" + minutes < 7 * 24 * 60 -> "${minutes / (24 * 60)}d ago" + else -> "${minutes / (7 * 24 * 60)}w ago" + } +} diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/saved/SavedVideosScreen.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/saved/SavedVideosScreen.kt new file mode 100644 index 000000000..021342d27 --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/saved/SavedVideosScreen.kt @@ -0,0 +1,363 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.screen.saved + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.newpipe.app.composable.ContentThumbnail +import net.newpipe.app.composable.VideoActionsMenuHost +import net.newpipe.app.model.ContentItem +import net.newpipe.app.navigation.Destination +import net.newpipe.app.navigation.Navigator +import net.newpipe.app.service.QueueRepository +import net.newpipe.app.service.SavedVideosRepository +import net.newpipe.app.screen.stream.StreamIntents +import net.newpipe.app.ui.Radius +import net.newpipe.app.ui.Spacing +import newpipe.shared.generated.resources.Res +import newpipe.shared.generated.resources.ic_delete +import newpipe.shared.generated.resources.ic_play_arrow +import newpipe.shared.generated.resources.ic_thumb_up +import newpipe.shared.generated.resources.ic_watch_later +import org.jetbrains.compose.resources.painterResource +import org.koin.compose.koinInject + +/** + * The two locally saved video lists. + * + * @param key the persisted list to show + */ +enum class SavedVideoList(val title: String, val storageKey: String) { + WatchLater("Watch later", "watch-later"), + Liked("Liked videos", "liked") +} + +/** + * The Watch later and Liked screens. + * + * Both lists are local only: adding a video never changes anything on the service and never + * requires an account. Entries open in the watch page, can be removed one by one, cleared at + * once, or played as a queue. + */ +@Composable +fun SavedVideosScreen( + list: SavedVideoList, + navigator: Navigator = koinInject(), + repository: SavedVideosRepository = koinInject(), + queueRepository: QueueRepository = koinInject() +) { + val watchLater by repository.watchLater.collectAsState() + val liked by repository.liked.collectAsState() + val items = when (list) { + SavedVideoList.WatchLater -> watchLater + SavedVideoList.Liked -> liked + } + var showClearConfirm by remember { mutableStateOf(false) } + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(Spacing.lg), + verticalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + item(key = "header") { + SavedVideosHeader( + title = list.title, + count = items.size, + onPlayAll = if (items.isEmpty()) { + null + } else { + { queueAllAndPlay(items, queueRepository, navigator) } + }, + onClearAll = if (items.isEmpty()) null else ({ showClearConfirm = true }) + ) + } + + if (items.isEmpty()) { + item(key = "empty") { + SavedVideosEmptyState(list = list) + } + } else { + itemsIndexed(items, key = { index, item -> "saved-${list.storageKey}-$index-${item.url}" }) { _, item -> + VideoActionsMenuHost(item = item) { + SavedVideoRow( + item = item, + onOpen = { + navigator.navigateTo(Destination.Stream(item.serviceId, item.url)) + }, + onRemove = { + when (list) { + SavedVideoList.WatchLater -> repository.removeFromWatchLater(item.url) + SavedVideoList.Liked -> repository.removeFromLiked(item.url) + } + } + ) + } + } + } + } + + if (showClearConfirm) { + AlertDialog( + onDismissRequest = { showClearConfirm = false }, + title = { Text("Clear ${list.title.lowercase()}") }, + text = { Text("Remove all ${items.size} videos from this list?") }, + confirmButton = { + TextButton( + onClick = { + when (list) { + SavedVideoList.WatchLater -> items.forEach { + repository.removeFromWatchLater(it.url) + } + SavedVideoList.Liked -> items.forEach { + repository.removeFromLiked(it.url) + } + } + showClearConfirm = false + } + ) { + Text("Clear all") + } + }, + dismissButton = { + TextButton(onClick = { showClearConfirm = false }) { + Text("Cancel") + } + } + ) + } +} + +@Composable +private fun SavedVideosHeader( + title: String, + count: Int, + onPlayAll: (() -> Unit)?, + onClearAll: (() -> Unit)? +) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(bottom = Spacing.sm), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + ) { + Text( + text = title, + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + + if (count > 0) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(Radius.lg) + ) { + Text( + text = count.toString(), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = Spacing.sm, vertical = Spacing.xs) + ) + } + } + + onPlayAll?.let { + Surface( + onClick = it, + color = MaterialTheme.colorScheme.primaryContainer, + shape = RoundedCornerShape(Radius.lg) + ) { + Row( + modifier = Modifier.padding(horizontal = Spacing.md, vertical = Spacing.xs), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.xs) + ) { + Icon( + painter = painterResource(Res.drawable.ic_play_arrow), + contentDescription = null, + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer + ) + Text( + text = "Play all", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) + } + } + } + + onClearAll?.let { + OutlinedButton( + onClick = it, + contentPadding = PaddingValues(horizontal = Spacing.md, vertical = Spacing.xs) + ) { + Text("Clear all") + } + } + } +} + +@Composable +private fun SavedVideosEmptyState(list: SavedVideoList) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = Spacing.xl * 2), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(Spacing.md) + ) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(Radius.lg) + ) { + Icon( + painter = painterResource( + if (list == SavedVideoList.WatchLater) { + Res.drawable.ic_watch_later + } else { + Res.drawable.ic_thumb_up + } + ), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .padding(Spacing.lg) + .size(32.dp) + ) + } + Text( + text = if (list == SavedVideoList.WatchLater) { + "Nothing saved for later" + } else { + "No liked videos yet" + }, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = if (list == SavedVideoList.WatchLater) { + "Use Watch later on a video to keep it here. The list stays on this device." + } else { + "Like a video to keep it here. Likes are local and never sent to the service." + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} + +@Composable +private fun SavedVideoRow( + item: ContentItem, + onOpen: () -> Unit, + onRemove: () -> Unit +) { + Surface( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpen), + color = MaterialTheme.colorScheme.surfaceContainerLow, + shape = RoundedCornerShape(Radius.md) + ) { + Row( + modifier = Modifier.padding(Spacing.sm), + verticalAlignment = Alignment.CenterVertically + ) { + Box(modifier = Modifier.width(180.dp)) { + ContentThumbnail(item = item) + } + + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = Spacing.md), + verticalArrangement = Arrangement.spacedBy(Spacing.xs) + ) { + Text( + text = item.title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Text( + text = item.uploader ?: "Unknown", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + IconButton(onClick = onOpen) { + Icon( + painter = painterResource(Res.drawable.ic_play_arrow), + contentDescription = "Play", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp) + ) + } + + IconButton(onClick = onRemove) { + Icon( + painter = painterResource(Res.drawable.ic_delete), + contentDescription = "Remove", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + } + } + } +} + +private fun queueAllAndPlay( + items: List, + queueRepository: QueueRepository, + navigator: Navigator +) { + queueRepository.clear() + items.forEach { queueRepository.add(it) } + items.firstOrNull()?.let { first -> + StreamIntents.request(first.url, StreamIntents.Action.PLAY) + navigator.navigateTo(Destination.Stream(first.serviceId, first.url)) + } + queueRepository.startWatching() +} diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/SettingsHomeScreen.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/SettingsHomeScreen.kt index 751b15455..90a272b68 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/SettingsHomeScreen.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/settings/SettingsHomeScreen.kt @@ -76,6 +76,10 @@ fun SettingsHomeScreen( Destination.DownloadSettings ) + SettingsCategoryType.NOTIFICATIONS -> navigator.navigateTo( + Destination.Notifications + ) + // TODO: wire remaining sub-screens as they are migrated else -> Unit } diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt index 65ce4cffd..1b144e6bd 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/screen/stream/WatchPage.kt @@ -14,6 +14,8 @@ import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -88,6 +90,7 @@ import net.newpipe.app.model.SubscribedChannel import net.newpipe.app.service.PlaybackController import net.newpipe.app.service.PlaylistRepository import net.newpipe.app.service.QueueRepository +import net.newpipe.app.service.SavedVideosRepository import net.newpipe.app.service.SubscriptionRepository import net.newpipe.app.ui.Breakpoints import net.newpipe.app.ui.Motion @@ -113,7 +116,9 @@ import newpipe.shared.generated.resources.ic_open_in_new import newpipe.shared.generated.resources.ic_playlist_add import newpipe.shared.generated.resources.ic_push_pin import newpipe.shared.generated.resources.ic_subscriptions +import newpipe.shared.generated.resources.ic_thumb_down import newpipe.shared.generated.resources.ic_thumb_up +import newpipe.shared.generated.resources.ic_watch_later import newpipe.shared.generated.resources.ic_verified import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.painterResource @@ -406,6 +411,11 @@ private fun WatchInformation( onDownload: () -> Unit ) { var playlistDialogVisible by remember { mutableStateOf(false) } + val savedVideos: SavedVideosRepository = koinInject() + val watchLater by savedVideos.watchLater.collectAsState() + val liked by savedVideos.liked.collectAsState() + val inWatchLater = watchLater.any { it.url == details.url } + val isLiked = liked.any { it.url == details.url } Column( modifier = Modifier @@ -418,6 +428,11 @@ private fun WatchInformation( fontWeight = FontWeight.SemiBold ) + ReactionRow( + details = details, + modifier = Modifier.padding(top = Spacing.sm) + ) + Spacer(modifier = Modifier.size(Spacing.md)) BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { @@ -451,7 +466,11 @@ private fun WatchInformation( WatchActionBar( audioOnly = audioOnly, + inWatchLater = inWatchLater, + isLiked = isLiked, onSave = { playlistDialogVisible = true }, + onToggleWatchLater = { savedVideos.toggleWatchLater(details.toContentItem()) }, + onToggleLiked = { savedVideos.toggleLiked(details.toContentItem()) }, onToggleAudioOnly = onToggleAudioOnly, onOpenPopup = onOpenPopup, onDownload = onDownload, @@ -477,6 +496,70 @@ private fun WatchInformation( } } +/** + * The read-only like and dislike counts of the stream. + */ +@Composable +private fun ReactionRow( + details: StreamDetails, + modifier: Modifier = Modifier +) { + val likes = details.likeCount + val dislikes = details.dislikeCount + if (likes == null && dislikes == null) return + + Row( + modifier = modifier, + horizontalArrangement = Arrangement.spacedBy(Spacing.sm), + verticalAlignment = Alignment.CenterVertically + ) { + likes?.let { + ReactionCount( + icon = Res.drawable.ic_thumb_up, + count = it, + contentDescription = "likes" + ) + } + if (dislikes != null && dislikes > 0) { + ReactionCount( + icon = Res.drawable.ic_thumb_down, + count = dislikes, + contentDescription = "dislikes" + ) + } + } +} + +@Composable +private fun ReactionCount( + icon: DrawableResource, + count: Long, + contentDescription: String +) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(Radius.lg) + ) { + Row( + modifier = Modifier.padding(horizontal = Spacing.md, vertical = Spacing.xs), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.xs) + ) { + Icon( + painter = painterResource(icon), + contentDescription = contentDescription, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + text = formatViewCount(count), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + /** * The avatar, the name and the subscriber count of the uploader. */ @@ -609,21 +692,27 @@ private fun SubscribeButton( * The action bar below the channel: each action shows an icon with its label underneath, like the * action bar of the Android client. */ +@OptIn(ExperimentalLayoutApi::class) @Composable private fun WatchActionBar( audioOnly: Boolean, + inWatchLater: Boolean, + isLiked: Boolean, onSave: () -> Unit, + onToggleWatchLater: () -> Unit, + onToggleLiked: () -> Unit, onToggleAudioOnly: () -> Unit, onOpenPopup: () -> Unit, onDownload: () -> Unit, onCopyLink: () -> Unit, onOpenInBrowser: () -> Unit ) { - Row( + FlowRow( modifier = Modifier .fillMaxWidth() .padding(top = Spacing.md), - horizontalArrangement = Arrangement.spacedBy(Spacing.sm) + horizontalArrangement = Arrangement.spacedBy(Spacing.sm), + verticalArrangement = Arrangement.spacedBy(Spacing.sm) ) { WatchAction( icon = Res.drawable.ic_playlist_add, @@ -631,6 +720,20 @@ private fun WatchActionBar( onClick = onSave ) + WatchAction( + icon = Res.drawable.ic_watch_later, + label = "Watch later", + selected = inWatchLater, + onClick = onToggleWatchLater + ) + + WatchAction( + icon = Res.drawable.ic_thumb_up, + label = if (isLiked) "Liked" else "Like", + selected = isLiked, + onClick = onToggleLiked + ) + WatchAction( icon = Res.drawable.ic_headset, label = if (audioOnly) "Video mode" else "Audio only", @@ -705,12 +808,17 @@ private fun MoreAction( private fun WatchAction( icon: DrawableResource, label: String, + selected: Boolean = false, onClick: () -> Unit ) { Surface( onClick = onClick, shape = RoundedCornerShape(Radius.md), - color = MaterialTheme.colorScheme.surfaceContainerHigh + color = if (selected) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + } ) { Column( modifier = Modifier @@ -722,13 +830,23 @@ private fun WatchAction( Icon( painter = painterResource(icon), contentDescription = null, - modifier = Modifier.size(22.dp) + modifier = Modifier.size(22.dp), + tint = if (selected) { + MaterialTheme.colorScheme.onPrimaryContainer + } else { + MaterialTheme.colorScheme.onSurface + } ) Text( text = label, style = MaterialTheme.typography.labelMedium, maxLines = 1, - overflow = TextOverflow.Ellipsis + overflow = TextOverflow.Ellipsis, + color = if (selected) { + MaterialTheme.colorScheme.onPrimaryContainer + } else { + MaterialTheme.colorScheme.onSurface + } ) } } diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/service/SavedVideosRepository.kt b/shared/src/commonMain/kotlin/net/newpipe/app/service/SavedVideosRepository.kt new file mode 100644 index 000000000..8b209959f --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/service/SavedVideosRepository.kt @@ -0,0 +1,192 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import co.touchlab.kermit.Logger +import com.russhwolf.settings.Settings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.ContentType + +/** + * The two quick-access video lists of the library: Watch later and the videos the user liked + * locally. + * + * The extraction engine is read-only, so liking a video here never changes anything on the + * service; it only keeps the video in a local list. Both lists are persisted as JSON in the + * platform settings, newest entry first, and survive restarts on every platform. + */ +class SavedVideosRepository( + private val settings: Settings +) { + + private val json = Json { + ignoreUnknownKeys = true + encodeDefaults = true + } + + private val _watchLater = MutableStateFlow(load(KEY_WATCH_LATER)) + val watchLater = _watchLater.asStateFlow() + + private val _liked = MutableStateFlow(load(KEY_LIKED)) + val liked = _liked.asStateFlow() + + /** + * Adds the video to Watch later, or removes it when it is already saved. + * + * @return `true` when the video is in Watch later afterwards + */ + fun toggleWatchLater(item: ContentItem): Boolean = + toggle(_watchLater, KEY_WATCH_LATER, item) + + /** + * Adds the video to the local liked list, or removes it when it is already liked. + * + * @return `true` when the video is liked locally afterwards + */ + fun toggleLiked(item: ContentItem): Boolean = + toggle(_liked, KEY_LIKED, item) + + /** + * Whether the stream with the given url is in Watch later. + */ + fun isInWatchLater(url: String?): Boolean = + url != null && _watchLater.value.any { it.url == url } + + /** + * Whether the stream with the given url is in the local liked list. + */ + fun isLiked(url: String?): Boolean = + url != null && _liked.value.any { it.url == url } + + /** + * Removes one entry from Watch later. + */ + fun removeFromWatchLater(url: String) { + remove(_watchLater, KEY_WATCH_LATER, url) + } + + /** + * Removes one entry from the local liked list. + */ + fun removeFromLiked(url: String) { + remove(_liked, KEY_LIKED, url) + } + + /** + * Removes every entry from both lists. + */ + fun clearAll() { + _watchLater.value = emptyList() + _liked.value = emptyList() + settings.remove(KEY_WATCH_LATER) + settings.remove(KEY_LIKED) + } + + private fun toggle( + state: MutableStateFlow>, + key: String, + item: ContentItem + ): Boolean { + if (item.type != ContentType.STREAM || item.url.isBlank()) return false + + val contains = state.value.any { it.url == item.url } + val updated = if (contains) { + state.value.filterNot { it.url == item.url } + } else { + (listOf(item.withoutResumePosition()) + state.value.filterNot { it.url == item.url }) + .take(MAX_ENTRIES) + } + state.value = updated + persist(key, updated) + return !contains + } + + private fun remove( + state: MutableStateFlow>, + key: String, + url: String + ) { + val updated = state.value.filterNot { it.url == url } + if (updated.size == state.value.size) return + state.value = updated + persist(key, updated) + } + + private fun load(key: String): List { + val stored = settings.getStringOrNull(key) ?: return emptyList() + return try { + json.decodeFromString>(stored).map { it.toContentItem() } + } catch (exception: Exception) { + Logger.w(messageString = "The saved videos could not be read", throwable = exception) + emptyList() + } + } + + private fun persist(key: String, items: List) { + try { + settings.putString(key, json.encodeToString(items.map { StoredItem.from(it) })) + } catch (exception: Exception) { + Logger.w(messageString = "The saved videos could not be saved", throwable = exception) + } + } + + @Serializable + private data class StoredItem( + val serviceId: Int, + val url: String, + val title: String, + val uploader: String? = null, + val uploaderUrl: String? = null, + val thumbnailUrl: String? = null, + val durationSeconds: Long? = null, + val viewCount: Long? = null, + val uploadDate: String? = null, + val liveNow: Boolean = false + ) { + fun toContentItem() = ContentItem( + serviceId = serviceId, + url = url, + title = title, + type = ContentType.STREAM, + uploader = uploader, + uploaderUrl = uploaderUrl, + thumbnailUrl = thumbnailUrl, + durationSeconds = durationSeconds, + viewCount = viewCount, + uploadDate = uploadDate, + liveNow = liveNow + ) + + companion object { + fun from(item: ContentItem) = StoredItem( + serviceId = item.serviceId, + url = item.url, + title = item.title, + uploader = item.uploader, + uploaderUrl = item.uploaderUrl, + thumbnailUrl = item.thumbnailUrl, + durationSeconds = item.durationSeconds, + viewCount = item.viewCount, + uploadDate = item.uploadDate, + liveNow = item.liveNow + ) + } + } + + private companion object { + const val KEY_WATCH_LATER = "saved_watch_later_v1" + const val KEY_LIKED = "saved_liked_videos_v1" + const val MAX_ENTRIES = 200 + } +} + +private fun ContentItem.withoutResumePosition(): ContentItem = + if (resumePositionMs == null) this else copy(resumePositionMs = null) diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationRepository.kt b/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationRepository.kt new file mode 100644 index 000000000..e88849d60 --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationRepository.kt @@ -0,0 +1,261 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import co.touchlab.kermit.Logger +import com.russhwolf.settings.Settings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.ContentType +import net.newpipe.app.model.SubscribedChannel +import net.newpipe.app.model.UploadNotification + +/** + * Stores the new-upload notifications of subscribed channels and the videos already seen. + * + * The repository is the deduplication point: the first successful check of a channel only records + * its current uploads, so subscribing to a channel never floods the notification list with its + * whole back catalogue. Later checks create one notification per upload that was not seen before. + * Both the notifications and the seen video urls are persisted as JSON in the platform settings. + */ +class UploadNotificationRepository( + private val settings: Settings +) { + + private val json = Json { + ignoreUnknownKeys = true + encodeDefaults = true + } + + private val lock = Any() + + private val _notifications = MutableStateFlow(loadNotifications()) + val notifications = _notifications.asStateFlow() + + /** The number of notifications the user has not read yet. */ + val unreadCount: Int + get() = _notifications.value.count { !it.read } + + /** The url of every video that was already recorded, oldest first. */ + private val seenVideos = loadStringList(KEY_SEEN).toMutableList() + + /** The channels whose current uploads were already recorded without notifying. */ + private val initializedChannels = loadStringList(KEY_INITIALIZED).toMutableSet() + + /** + * Records the latest uploads of [channel]. + * + * The first call for a channel marks its uploads as seen without creating notifications. Any + * later upload that is not in the seen set becomes a notification. + * + * @return the notifications created by this call, newest first + */ + fun recordUploads( + channel: SubscribedChannel, + uploads: List, + now: Long = System.currentTimeMillis() + ): List { + if (channel.url.isBlank()) return emptyList() + val allVideos = uploads + .filter { it.type == ContentType.STREAM && it.url.isNotBlank() } + .distinctBy { it.url } + if (allVideos.isEmpty()) return emptyList() + + synchronized(lock) { + val firstCheck = channel.url !in initializedChannels + // The first check records the whole visible back catalogue silently; later checks + // only look at the newest uploads. + val videos = if (firstCheck) allVideos else allVideos.take(MAX_UPLOADS_PER_CHANNEL) + val created = mutableListOf() + + videos.forEach { video -> + if (video.url in seenVideos) return@forEach + seenVideos += video.url + if (!firstCheck) { + created += UploadNotification( + videoUrl = video.url, + serviceId = video.serviceId, + videoTitle = video.title, + channelUrl = channel.url, + channelName = channel.name, + thumbnailUrl = video.thumbnailUrl, + uploadDate = video.uploadDate, + discoveredAt = now + ) + } + } + + val boundedSeen = seenVideos.takeLast(MAX_SEEN_VIDEOS) + seenVideos.clear() + seenVideos += boundedSeen + if (firstCheck) { + initializedChannels += channel.url + persistStringList(KEY_INITIALIZED, initializedChannels.toList()) + } + + if (created.isEmpty()) { + persistStringList(KEY_SEEN, seenVideos) + return emptyList() + } + + val updated = (created + _notifications.value) + .distinctBy { it.videoUrl } + .take(MAX_NOTIFICATIONS) + _notifications.value = updated + persistStringList(KEY_SEEN, seenVideos) + persistNotifications(updated) + return created + } + } + + /** + * Marks one notification as read. + */ + fun markRead(videoUrl: String) { + synchronized(lock) { + val updated = _notifications.value.map { + if (it.videoUrl == videoUrl) it.copy(read = true) else it + } + if (updated == _notifications.value) return + _notifications.value = updated + persistNotifications(updated) + } + } + + /** + * Marks every notification as read. + */ + fun markAllRead() { + synchronized(lock) { + if (_notifications.value.none { !it.read }) return + val updated = _notifications.value.map { it.copy(read = true) } + _notifications.value = updated + persistNotifications(updated) + } + } + + /** + * Removes every notification. The seen videos stay recorded, so clearing the list does not + * resurrect old uploads on the next check. + */ + fun clear() { + synchronized(lock) { + _notifications.value = emptyList() + settings.remove(KEY_NOTIFICATIONS) + } + } + + /** + * Forgets the current uploads of a channel, so the next check records them silently again. + * Used when a channel is unsubscribed from and later subscribed to anew. + */ + fun resetChannel(channelUrl: String) { + synchronized(lock) { + if (initializedChannels.remove(channelUrl)) { + persistStringList(KEY_INITIALIZED, initializedChannels.toList()) + } + } + } + + private fun loadNotifications(): List { + val stored = settings.getStringOrNull(KEY_NOTIFICATIONS) ?: return emptyList() + return try { + json.decodeFromString>(stored) + .map { it.toNotification() } + } catch (exception: Exception) { + Logger.w( + messageString = "The upload notifications could not be read", + throwable = exception + ) + emptyList() + } + } + + private fun persistNotifications(items: List) { + try { + val stored = items.map { StoredNotification.from(it) } + settings.putString(KEY_NOTIFICATIONS, json.encodeToString(stored)) + } catch (exception: Exception) { + Logger.w( + messageString = "The upload notifications could not be saved", + throwable = exception + ) + } + } + + private fun loadStringList(key: String): List { + val stored = settings.getStringOrNull(key) ?: return emptyList() + return try { + json.decodeFromString>(stored) + } catch (exception: Exception) { + Logger.w(messageString = "The notification state could not be read", throwable = exception) + emptyList() + } + } + + private fun persistStringList(key: String, values: List) { + try { + settings.putString(key, json.encodeToString(values)) + } catch (exception: Exception) { + Logger.w( + messageString = "The notification state could not be saved", + throwable = exception + ) + } + } + + @Serializable + private data class StoredNotification( + val videoUrl: String, + val serviceId: Int, + val videoTitle: String, + val channelUrl: String, + val channelName: String, + val thumbnailUrl: String? = null, + val uploadDate: String? = null, + val discoveredAt: Long = 0L, + val read: Boolean = false + ) { + fun toNotification() = UploadNotification( + videoUrl = videoUrl, + serviceId = serviceId, + videoTitle = videoTitle, + channelUrl = channelUrl, + channelName = channelName, + thumbnailUrl = thumbnailUrl, + uploadDate = uploadDate, + discoveredAt = discoveredAt, + read = read + ) + + companion object { + fun from(item: UploadNotification) = StoredNotification( + videoUrl = item.videoUrl, + serviceId = item.serviceId, + videoTitle = item.videoTitle, + channelUrl = item.channelUrl, + channelName = item.channelName, + thumbnailUrl = item.thumbnailUrl, + uploadDate = item.uploadDate, + discoveredAt = item.discoveredAt, + read = item.read + ) + } + } + + private companion object { + const val KEY_NOTIFICATIONS = "upload_notifications_v1" + const val KEY_SEEN = "upload_notifications_seen_v1" + const val KEY_INITIALIZED = "upload_notifications_initialized_v1" + const val MAX_NOTIFICATIONS = 100 + const val MAX_SEEN_VIDEOS = 10_000 + const val MAX_UPLOADS_PER_CHANNEL = 30 + } +} diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationService.kt b/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationService.kt new file mode 100644 index 000000000..99ec70775 --- /dev/null +++ b/shared/src/commonMain/kotlin/net/newpipe/app/service/UploadNotificationService.kt @@ -0,0 +1,143 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import co.touchlab.kermit.Logger +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import net.newpipe.app.preferences.NotificationPreferences + +/** + * Checks the subscribed channels for new uploads while the app is running. + * + * The service never runs in the background: it starts with the application shell and stops with + * the process. Checks are serialised, spaced out between channels and failures are ignored, so a + * slow or broken channel never blocks the UI or the other channels. The first check of a channel + * only records its current uploads, see [UploadNotificationRepository.recordUploads]. + */ +class UploadNotificationService( + private val contentRepository: ContentRepository, + private val subscriptionRepository: SubscriptionRepository, + private val notificationRepository: UploadNotificationRepository, + private val preferences: NotificationPreferences +) { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val checkMutex = Mutex() + + private var loopJob: Job? = null + private var rotation = 0 + + private val _checking = MutableStateFlow(false) + + /** Whether a check is running right now. */ + val checking = _checking.asStateFlow() + + private val _lastCheck = MutableStateFlow(null) + + /** When the last successful check finished, in epoch milliseconds, or `null` before the first. */ + val lastCheck = _lastCheck.asStateFlow() + + /** + * Starts the periodic check loop. Calling this more than once has no effect. + */ + fun start() { + synchronized(this) { + if (loopJob != null) return + loopJob = scope.launch { + while (isActive) { + if (preferences.enabled.value) { + runCheck() + delay(preferences.intervalMinutes.value * MINUTE_MS) + } else { + // Waiting in small steps lets an interval or enable change take effect + // without restarting the process. + delay(DISABLED_POLL_MS) + } + } + } + } + } + + /** + * Runs a check right away, for example from the "check now" button. + */ + fun checkNow() { + scope.launch { runCheck() } + } + + /** + * Fetches the latest uploads of the subscribed channels and records new notifications. + * + * Checks never run concurrently: a manual check during an automatic one is skipped. + */ + suspend fun runCheck(): Int { + if (!preferences.enabled.value) return 0 + if (!checkMutex.tryLock()) return 0 + + _checking.value = true + var created = 0 + try { + val channels = subscriptionRepository.subscriptions.value + if (channels.isEmpty()) { + _lastCheck.value = System.currentTimeMillis() + return 0 + } + + val batch = rotate(channels).take(MAX_CHANNELS_PER_CHECK) + batch.forEachIndexed { index, channel -> + if (!preferences.enabled.value) return created + try { + val uploads = contentRepository.channel(channel.serviceId, channel.url).items + created += notificationRepository.recordUploads(channel, uploads).size + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + // A broken channel is retried on the next check; it must not hide the others. + Logger.w( + messageString = "Could not check ${channel.url} for new uploads", + throwable = exception + ) + } + if (index < batch.lastIndex) delay(CHANNEL_SPACING_MS) + } + + _lastCheck.value = System.currentTimeMillis() + return created + } finally { + _checking.value = false + checkMutex.unlock() + } + } + + /** + * Returns the channels in a rotating order, so a large subscription list is checked across + * several rounds instead of hammering every channel on every round. + */ + private fun rotate(channels: List): List { + if (channels.size <= MAX_CHANNELS_PER_CHECK) return channels + val start = rotation % channels.size + rotation = (rotation + MAX_CHANNELS_PER_CHECK) % channels.size + return channels.drop(start) + channels.take(start) + } + + private companion object { + const val MINUTE_MS = 60_000L + const val DISABLED_POLL_MS = 60_000L + const val CHANNEL_SPACING_MS = 400L + const val MAX_CHANNELS_PER_CHECK = 25 + } +} diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/shell/ModernShell.kt b/shared/src/commonMain/kotlin/net/newpipe/app/shell/ModernShell.kt index b5f29c70f..cb4075f70 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/shell/ModernShell.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/shell/ModernShell.kt @@ -33,6 +33,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.relocation.BringIntoViewRequester @@ -57,6 +58,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import co.touchlab.kermit.Logger @@ -72,6 +74,8 @@ import net.newpipe.app.service.PlaybackController import net.newpipe.app.service.DownloadRepository import net.newpipe.app.service.MediaDownloader import net.newpipe.app.service.PopupPlayer +import net.newpipe.app.service.UploadNotificationRepository +import net.newpipe.app.service.UploadNotificationService import net.newpipe.app.ui.Breakpoints import net.newpipe.app.ui.Layout import net.newpipe.app.ui.PlayerUiState @@ -90,6 +94,9 @@ import newpipe.shared.generated.resources.ic_sports_esports import newpipe.shared.generated.resources.ic_subscriptions import newpipe.shared.generated.resources.ic_trending_up import newpipe.shared.generated.resources.ic_history +import newpipe.shared.generated.resources.ic_notifications +import newpipe.shared.generated.resources.ic_thumb_up +import newpipe.shared.generated.resources.ic_watch_later import newpipe.shared.generated.resources.ic_home import newpipe.shared.generated.resources.ic_np_desktop_logo import newpipe.shared.generated.resources.ic_language @@ -155,7 +162,10 @@ private val shellSections = listOf( label = "Library", entries = listOf( ShellEntry(Destination.Subscriptions, "Feed", Res.drawable.ic_subscriptions), + ShellEntry(Destination.Notifications, "Notifications", Res.drawable.ic_notifications), ShellEntry(Destination.History, "History", Res.drawable.ic_history), + ShellEntry(Destination.WatchLater, "Watch later", Res.drawable.ic_watch_later), + ShellEntry(Destination.LikedVideos, "Liked", Res.drawable.ic_thumb_up), ShellEntry(Destination.Downloads, "Downloads", Res.drawable.ic_file_download), ShellEntry(Destination.LocalPlaylists, "Playlists", Res.drawable.ic_playlist_play) ) @@ -192,8 +202,16 @@ fun ModernShell( contentRepository: ContentRepository = koinInject(), downloader: MediaDownloader = koinInject(), downloadRepository: DownloadRepository = koinInject(), + notificationRepository: UploadNotificationRepository = koinInject(), + notificationService: UploadNotificationService = koinInject(), content: @Composable () -> Unit ) { + LaunchedEffect(Unit) { + notificationService.start() + } + val unreadNotifications by notificationRepository.notifications.collectAsState() + val unreadNotificationCount = unreadNotifications.count { !it.read } + val edgeInteraction = remember { MutableInteractionSource() } val edgeHovered by edgeInteraction.collectIsHoveredAsState() val railInteraction = remember { MutableInteractionSource() } @@ -385,21 +403,68 @@ fun ModernShell( ) } } else { - // A small, transparent search shortcut in the top right corner of every screen. + // Small, transparent shortcuts in the top right corner of every screen: the + // notification centre with its unread badge and the search. if (!immersive) { - IconButton( - onClick = { onNavigate(Destination.Search) }, + Row( modifier = Modifier .align(Alignment.TopEnd) - .padding(top = Spacing.xs, end = Spacing.xs) - .size(32.dp) + .padding(top = Spacing.xs, end = Spacing.xs), + verticalAlignment = Alignment.CenterVertically ) { - Icon( - painter = painterResource(Res.drawable.ic_search), - contentDescription = "Search", - tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), - modifier = Modifier.size(18.dp) - ) + IconButton( + onClick = { onNavigate(Destination.Notifications) }, + modifier = Modifier.size(32.dp) + ) { + Box { + Icon( + painter = painterResource(Res.drawable.ic_notifications), + contentDescription = if (unreadNotificationCount > 0) { + "$unreadNotificationCount unread uploads" + } else { + "Notifications" + }, + tint = if (unreadNotificationCount > 0) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) + }, + modifier = Modifier.size(18.dp) + ) + if (unreadNotificationCount > 0) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .align(Alignment.TopEnd) + .size(12.dp) + ) { + Text( + text = if (unreadNotificationCount > 9) { + "9+" + } else { + unreadNotificationCount.toString() + }, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onPrimary, + textAlign = TextAlign.Center + ) + } + } + } + } + + IconButton( + onClick = { onNavigate(Destination.Search) }, + modifier = Modifier.size(32.dp) + ) { + Icon( + painter = painterResource(Res.drawable.ic_search), + contentDescription = "Search", + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + modifier = Modifier.size(18.dp) + ) + } } } @@ -566,6 +631,13 @@ private fun NavigationRailItem( val hovered by interactionSource.collectIsHoveredAsState() val focused by interactionSource.collectIsFocusedAsState() val bringIntoView = remember { BringIntoViewRequester() } + val notificationRepository: UploadNotificationRepository = koinInject() + val notifications by notificationRepository.notifications.collectAsState() + val unread = if (entry.destination == Destination.Notifications) { + notifications.count { !it.read } + } else { + 0 + } // Television focus: the row is scrolled into view before it is highlighted, so the visible // focus indicator is never clipped. @@ -625,15 +697,41 @@ private fun NavigationRailItem( modifier = Modifier.size(18.dp) ) + if (unread > 0 && !expanded) { + Box( + modifier = Modifier + .padding(start = 2.dp) + .size(6.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary) + ) + } + if (expanded) { Text( text = entry.label, - modifier = Modifier.padding(start = Spacing.sm), + modifier = Modifier + .weight(1f) + .padding(start = Spacing.sm), style = MaterialTheme.typography.bodySmall, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, color = contentColor, maxLines = 1 ) + if (unread > 0) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = Spacing.xs) + ) { + Text( + text = if (unread > 99) "99+" else unread.toString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier.padding(horizontal = 5.dp, vertical = 1.dp) + ) + } + } } } } diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt index 8c6e8d5e0..1c5178d7a 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/ExtractorContentRepository.kt @@ -444,6 +444,8 @@ class ExtractorContentRepository( description = info.description?.content, durationSeconds = info.duration.takeIf { it > 0 }, viewCount = info.viewCount.takeIf { it >= 0 }, + likeCount = info.likeCount.takeIf { it >= 0 }, + dislikeCount = info.dislikeCount.takeIf { it >= 0 }, uploadDate = info.textualUploadDate, liveNow = info.streamType == StreamType.LIVE_STREAM, videoStreams = (info.videoStreams + info.videoOnlyStreams) diff --git a/shared/src/jvmTest/kotlin/net/newpipe/app/service/SavedVideosRepositoryTest.kt b/shared/src/jvmTest/kotlin/net/newpipe/app/service/SavedVideosRepositoryTest.kt new file mode 100644 index 000000000..b263c7b05 --- /dev/null +++ b/shared/src/jvmTest/kotlin/net/newpipe/app/service/SavedVideosRepositoryTest.kt @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import com.russhwolf.settings.MapSettings +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.ContentType + +class SavedVideosRepositoryTest { + + private val settings = MapSettings() + + @Test + fun `watch later toggles and survives a restart`() { + val repository = SavedVideosRepository(settings) + val video = video("https://example.com/watch?v=one", "One") + + assertTrue(repository.toggleWatchLater(video)) + assertTrue(repository.isInWatchLater(video.url)) + assertEquals(listOf(video.url), repository.watchLater.value.map { it.url }) + + val restarted = SavedVideosRepository(settings) + assertTrue(restarted.isInWatchLater(video.url)) + assertEquals("One", restarted.watchLater.value.single().title) + + assertFalse(restarted.toggleWatchLater(video)) + assertFalse(restarted.isInWatchLater(video.url)) + assertTrue(SavedVideosRepository(settings).watchLater.value.isEmpty()) + } + + @Test + fun `liked videos are newest first and independent of watch later`() { + val repository = SavedVideosRepository(settings) + val first = video("https://example.com/watch?v=one", "One") + val second = video("https://example.com/watch?v=two", "Two") + + repository.toggleLiked(first) + repository.toggleLiked(second) + + assertTrue(repository.isLiked(second.url)) + assertFalse(repository.isInWatchLater(second.url)) + assertEquals( + listOf(second.url, first.url), + repository.liked.value.map { it.url } + ) + assertEquals(emptyList(), repository.watchLater.value.map { it.url }) + } + + @Test + fun `removing an entry persists the remaining list`() { + val repository = SavedVideosRepository(settings) + val first = video("https://example.com/watch?v=one", "One") + val second = video("https://example.com/watch?v=two", "Two") + repository.toggleWatchLater(first) + repository.toggleWatchLater(second) + + repository.removeFromWatchLater(second.url) + + val restarted = SavedVideosRepository(settings) + assertFalse(restarted.isInWatchLater(second.url)) + assertEquals(listOf(first.url), restarted.watchLater.value.map { it.url }) + } + + @Test + fun `non stream entries are ignored`() { + val repository = SavedVideosRepository(settings) + val channel = ContentItem( + serviceId = 0, + url = "https://example.com/channel", + title = "Channel", + type = ContentType.CHANNEL + ) + + assertFalse(repository.toggleWatchLater(channel)) + assertFalse(repository.toggleLiked(channel)) + assertTrue(repository.watchLater.value.isEmpty()) + assertTrue(repository.liked.value.isEmpty()) + } + + private fun video(url: String, title: String) = ContentItem( + serviceId = 0, + url = url, + title = title, + type = ContentType.STREAM, + uploader = "Uploader", + durationSeconds = 120 + ) +} diff --git a/shared/src/jvmTest/kotlin/net/newpipe/app/service/UploadNotificationRepositoryTest.kt b/shared/src/jvmTest/kotlin/net/newpipe/app/service/UploadNotificationRepositoryTest.kt new file mode 100644 index 000000000..fe51c4a21 --- /dev/null +++ b/shared/src/jvmTest/kotlin/net/newpipe/app/service/UploadNotificationRepositoryTest.kt @@ -0,0 +1,141 @@ +/* + * SPDX-FileCopyrightText: 2026 NewPipe e.V. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package net.newpipe.app.service + +import com.russhwolf.settings.MapSettings +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import net.newpipe.app.model.ContentItem +import net.newpipe.app.model.ContentType +import net.newpipe.app.model.SubscribedChannel +import net.newpipe.app.preferences.NotificationPreferences + +class UploadNotificationRepositoryTest { + + private val settings = MapSettings() + private val channel = SubscribedChannel( + serviceId = 0, + url = "https://example.com/channel", + name = "Channel" + ) + + @Test + fun `first check records uploads without notifying`() { + val repository = UploadNotificationRepository(settings) + + val created = repository.recordUploads(channel, listOf(video("one"), video("two"))) + + assertTrue(created.isEmpty()) + assertTrue(repository.notifications.value.isEmpty()) + } + + @Test + fun `later uploads are notified once`() { + val repository = UploadNotificationRepository(settings) + repository.recordUploads(channel, listOf(video("one"))) + + val created = repository.recordUploads( + channel, + listOf(video("two"), video("one")) + ) + + assertEquals(listOf("https://example.com/watch?v=two"), created.map { it.videoUrl }) + assertEquals(1, repository.notifications.value.size) + assertFalse(repository.notifications.value.single().read) + assertEquals(1, repository.unreadCount) + + val again = repository.recordUploads(channel, listOf(video("two"), video("one"))) + assertTrue(again.isEmpty()) + assertEquals(1, repository.notifications.value.size) + } + + @Test + fun `deduplication survives a restart`() { + val first = UploadNotificationRepository(settings) + first.recordUploads(channel, listOf(video("one"))) + first.recordUploads(channel, listOf(video("two"))) + + val restarted = UploadNotificationRepository(settings) + assertTrue(restarted.notifications.value.any { it.videoUrl == video("two").url }) + assertTrue(restarted.recordUploads(channel, listOf(video("two"))).isEmpty()) + } + + @Test + fun `clearing notifications keeps uploads seen`() { + val repository = UploadNotificationRepository(settings) + repository.recordUploads(channel, listOf(video("one"))) + repository.recordUploads(channel, listOf(video("two"))) + assertEquals(1, repository.notifications.value.size) + + repository.clear() + + assertTrue(repository.notifications.value.isEmpty()) + assertTrue(repository.recordUploads(channel, listOf(video("two"))).isEmpty()) + } + + @Test + fun `a newly subscribed channel is initialized silently`() { + val repository = UploadNotificationRepository(settings) + repository.recordUploads(channel, listOf(video("one"))) + + val other = channel.copy(url = "https://example.com/other", name = "Other") + assertTrue(repository.recordUploads(other, listOf(video("three"))).isEmpty()) + + val created = repository.recordUploads(other, listOf(video("four"))) + assertEquals(listOf(video("four").url), created.map { it.videoUrl }) + } + + @Test + fun `marking read updates the unread count and persists`() { + val repository = UploadNotificationRepository(settings) + repository.recordUploads(channel, listOf(video("one"))) + repository.recordUploads(channel, listOf(video("two"))) + val url = repository.notifications.value.single().videoUrl + + repository.markRead(url) + + assertEquals(0, repository.unreadCount) + val restarted = UploadNotificationRepository(settings) + assertTrue(restarted.notifications.value.single().read) + } + + @Test + fun `mark all read handles every notification`() { + val repository = UploadNotificationRepository(settings) + repository.recordUploads(channel, listOf(video("one"))) + repository.recordUploads(channel, listOf(video("two"), video("three"))) + + repository.markAllRead() + + assertEquals(0, repository.unreadCount) + assertTrue(repository.notifications.value.all { it.read }) + } + + @Test + fun `notification preferences persist and clamp the interval`() { + val preferences = NotificationPreferences(settings) + + assertTrue(preferences.enabled.value) + assertEquals(NotificationPreferences.DEFAULT_INTERVAL_MINUTES, preferences.intervalMinutes.value) + + preferences.setEnabled(false) + preferences.setIntervalMinutes(1) + + val restarted = NotificationPreferences(settings) + assertFalse(restarted.enabled.value) + assertEquals(NotificationPreferences.MIN_INTERVAL_MINUTES, restarted.intervalMinutes.value) + } + + private fun video(name: String) = ContentItem( + serviceId = 0, + url = "https://example.com/watch?v=$name", + title = name, + type = ContentType.STREAM, + thumbnailUrl = "https://example.com/$name.jpg" + ) +} From 1a76208d5dd1329c6132d0f677315b03a5486798 Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 10:42:04 +0530 Subject: [PATCH 03/11] Fix security workflow action ref and gitleaks false positive --- .github/workflows/security.yml | 2 +- .gitleaks.toml | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 632f1f091..8f8f32356 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -109,7 +109,7 @@ jobs: /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" - name: Run Trivy on the packaged libraries - uses: aquasecurity/trivy-action@0.36.0 + uses: aquasecurity/trivy-action@v0.36.0 with: scan-type: fs scan-ref: ${{ steps.locate.outputs.APP_DIR }}/lib/app diff --git a/.gitleaks.toml b/.gitleaks.toml index 9179e410e..d5092c120 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -19,6 +19,10 @@ paths = [ # YouTube publishes this request key in its own web client page source; it is a public # platform constant, not a project credential. '''app/src/main/java/org/schabi/newpipe/util/potoken/PoTokenWebView.kt''', + # Documentation that names standard JCE cipher parameters; the generic-api-key heuristic + # mistakes the "AES-256-GCM" notation for a credential. The file no longer exists at HEAD, + # but old branches still contain it and gitleaks scans every fetched ref. + '''BACKUP_FORMAT.md''', '''gradle/wrapper/gradle-wrapper.jar''', '''.*\.png''', ] From e72455105c85b479b5ccdd489a3fc71daf5ded4d Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 10:45:03 +0530 Subject: [PATCH 04/11] Clarify Flatpak updates and export the signing key --- .github/workflows/release-linux.yml | 7 ++++++- .github/workflows/release-windows.yml | 8 ++++---- INSTALL.md | 22 ++++++++++++++-------- README.md | 2 +- packaging/README.md | 12 ++++++++---- packaging/flatpak/build-flatpak.sh | 16 +++++++++++++--- 6 files changed, 46 insertions(+), 21 deletions(-) diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index 86f14f2d4..e948cd415 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -26,6 +26,7 @@ jobs: env: FLATPAK_GPG_PRIVATE_KEY: ${{ secrets.FLATPAK_GPG_PRIVATE_KEY }} FLATPAK_GPG_KEY_ID: ${{ secrets.FLATPAK_GPG_KEY_ID }} + APP_ID: io.github.tauseef666_ctrl.NP_Desktop steps: - name: Checkout uses: actions/checkout@v6 @@ -199,6 +200,9 @@ jobs: if [ -f "$flatpak" ]; then echo "$(sha256sum "$flatpak" | cut -d' ' -f1) $(basename "$flatpak")" fi + if [ -f "build/flatpak/$APP_ID.gpg" ]; then + echo "$(sha256sum "build/flatpak/$APP_ID.gpg" | cut -d' ' -f1) $APP_ID.gpg" + fi if [ -f "$sbom" ]; then echo "$(sha256sum "$sbom" | cut -d' ' -f1) $(basename "$sbom")" fi @@ -214,6 +218,7 @@ jobs: ${{ steps.portable.outputs.TARBALL_PATH }} build/flatpak/*.flatpak build/flatpak/*.flatpakrepo + build/flatpak/*.gpg np-desktop-${{ steps.portable.outputs.VERSION }}-linux-x86_64.cyclonedx.json checksums-linux-sha256.txt retention-days: 7 @@ -234,7 +239,7 @@ jobs: "np-desktop-${{ steps.portable.outputs.VERSION }}-linux-x86_64.cyclonedx.json" checksums-linux-sha256.txt ) - for file in build/flatpak/*.flatpak build/flatpak/*.flatpakrepo; do + for file in build/flatpak/*.flatpak build/flatpak/*.flatpakrepo build/flatpak/*.gpg; do [ -f "$file" ] && assets+=("$file") done gh release upload "$tag" "${assets[@]}" --clobber diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml index 21fc25354..1324321fd 100644 --- a/.github/workflows/release-windows.yml +++ b/.github/workflows/release-windows.yml @@ -145,7 +145,7 @@ jobs: | Windows 10/11 (x64) | `NP-Desktop-${{ steps.tag.outputs.VERSION }}.msi` | Bundles the JRE and the VLC playback runtime | | Debian/Ubuntu (amd64) | `np-desktop_${{ steps.tag.outputs.VERSION }}_amd64.deb` | Bundles the JRE and the playback runtime | | Any Linux (x64) | `np-desktop-${{ steps.tag.outputs.VERSION }}-linux-x64.tar.gz` | Portable app image, updates itself in-app | - | Linux (x64, sandboxed) | `np-desktop-${{ steps.tag.outputs.VERSION }}-x86_64.flatpak` | Flatpak bundle; updates with `flatpak update` | + | Linux (x64, sandboxed) | `np-desktop-${{ steps.tag.outputs.VERSION }}-x86_64.flatpak` | Flatpak bundle; install the newer bundle to update | | Android | `NewPipe_v${{ steps.tag.outputs.VERSION }}.apk` | Phone and Android TV | ### 🔒 Verification @@ -176,9 +176,9 @@ jobs: - YouTube-like keyboard shortcuts - Download manager, local history & subscriptions - Multi-service: YouTube, SoundCloud, PeerTube, Bandcamp, media.ccc.de - - In-app updates: `msiexec` on Windows, the `.deb` on Debian based Linux, a - self-replacing portable app image on every other distribution, and - `flatpak update` for the Flatpak bundle + - In-app updates: `msiexec` on Windows, the `.deb` on Debian based Linux, and a + self-replacing portable app image on every other distribution. The Flatpak sandbox + is updated by installing the newer bundle; it never replaces files under `/app`. --- Built with ❤️ from [NewPipe](https://github.com/TeamNewPipe/NewPipe) diff --git a/INSTALL.md b/INSTALL.md index 59749645f..1f154b884 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -13,7 +13,7 @@ This guide covers installing NP Desktop on Windows and Linux, verifying your dow | Windows 10/11 (x64) | `NP-Desktop-.msi` | Bundles a JRE and the VLC libraries — no separate installs needed | | Debian/Ubuntu (amd64) | `np-desktop__amd64.deb` | Bundles a JRE and the playback runtime — no separate VLC install | | Any Linux (x64) | `np-desktop--linux-x64.tar.gz` | Portable app image; bundles the playback runtime, updates itself in-app | -| Linux (x64, sandboxed) | `np-desktop--x86_64.flatpak` | Flatpak bundle; updates through Flatpak | +| Linux (x64, sandboxed) | `np-desktop--x86_64.flatpak` | Flatpak bundle; update by installing the newer bundle | | Android | `NewPipe_v.apk` | Android phone and Android TV builds | *(Exact filenames can vary slightly between releases — use the file listed on the release page.)* @@ -134,16 +134,22 @@ flatpak install --user ./np-desktop--x86_64.flatpak flatpak run io.github.tauseef666_ctrl.NP_Desktop ``` -If a signed repository is published for the release, install it once and let Flatpak handle updates: +When the release includes a public key (`io.github.tauseef666_ctrl.NP_Desktop.gpg`), the bundle is +signed and can be verified while installing: ```bash -flatpak remote-add --user --if-not-exists np-desktop \ - https://tauseef666-ctrl.github.io/NP-Desktop/flatpak/io.github.tauseef666_ctrl.NP_Desktop.flatpakrepo -flatpak install --user np-desktop io.github.tauseef666_ctrl.NP_Desktop -flatpak update io.github.tauseef666_ctrl.NP_Desktop +flatpak install --user \ + --gpg-file=io.github.tauseef666_ctrl.NP_Desktop.gpg \ + ./np-desktop--x86_64.flatpak ``` -Inside Flatpak the in-app updater is disabled; updates come from `flatpak update`. +A standalone `.flatpak` bundle is not attached to an update remote, so install the newer bundle +when a release comes out. If you host the optional signed OSTree repository described in +[packaging/README.md](packaging/README.md), add its `.flatpakrepo` file as a remote and use +`flatpak update` instead. + +Inside Flatpak the in-app updater is disabled; the app points you to the release page and never +tries to replace files under `/app`. ### In-app updates @@ -151,7 +157,7 @@ NP Desktop updates itself from the release channel: - **Portable install (above):** the app downloads `np-desktop--linux-x64.tar.gz`, verifies the SHA-256 checksum, stages it next to the running installation, restarts and swaps the directory. No root password is needed and nothing outside `~/.local/share/np-desktop` is touched. - **Debian package:** the update downloads the `.deb` and hands it to your software installer (or `pkexec dpkg -i`), which asks for the administrator password. -- **Flatpak:** the app detects the sandbox and points you to `flatpak update`; it never tries to replace files under `/app`. +- **Flatpak:** the app detects the sandbox and points you to the release page; it never tries to replace files under `/app`. Install the newer bundle to update (or use a self-hosted signed repository with `flatpak update`). - **Other layouts:** when the installation directory is not writable (for example a system-wide unpack under `/opt`), the app offers the release page instead, because replacing those files needs administrator rights. ## Troubleshooting diff --git a/README.md b/README.md index bd76cedb0..4f6e874ba 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ A few of the problems this project solves that go beyond wrapping a media player ## Installation -Download the latest installer from the [Releases](https://github.com/Tauseef666-ctrl/NP-Desktop/releases) page — `.msi` for Windows, `.deb` for Debian/Ubuntu, the portable `linux-x64.tar.gz` for every other Linux distribution, a `.flatpak` bundle for a sandboxed install, or an Android APK. The desktop packages bundle their own JRE and playback runtime, so VLC and Java are **not** separate prerequisites. SHA-256 checksums are published alongside each release, and the desktop builds update themselves in-app (Flatpak installs update through `flatpak update`). +Download the latest installer from the [Releases](https://github.com/Tauseef666-ctrl/NP-Desktop/releases) page — `.msi` for Windows, `.deb` for Debian/Ubuntu, the portable `linux-x64.tar.gz` for every other Linux distribution, a `.flatpak` bundle for a sandboxed install, or an Android APK. The desktop packages bundle their own JRE and playback runtime, so VLC and Java are **not** separate prerequisites. SHA-256 checksums are published alongside each release, and the desktop builds update themselves in-app (install the newer Flatpak bundle to update a sandboxed install). Step-by-step instructions, including how to handle the Windows SmartScreen warning for unsigned installers, are in [INSTALL.md](INSTALL.md). diff --git a/packaging/README.md b/packaging/README.md index c9cc247b7..08be757f6 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -32,8 +32,9 @@ Release builds must always pass `-PvlcPrefix`. ## Linux: Flatpak -Requirements: `flatpak` and the `org.freedesktop.Platform//24.08` runtime. The app image must -already contain the JRE and libVLC. +Requirements: `flatpak`. The `org.freedesktop.Platform//24.08` runtime is required to install +and smoke-test the bundle, but not to export it. The app image must already contain the JRE and +libVLC. ```bash packaging/flatpak/build-flatpak.sh \ @@ -48,8 +49,11 @@ self-contained app image is copied into `/app/files`. ### Signing The bundle is unsigned unless `FLATPAK_GPG_KEY_ID` points at a key in `FLATPAK_GPG_HOME` -(default `~/.gnupg`). With a key the script also writes a signed OSTree repo, the exported public -key and an `.flatpakrepo` file. The release workflow imports `FLATPAK_GPG_PRIVATE_KEY` when that +(default `~/.gnupg`). With a key the script signs the bundle and exports the public key as +`build/flatpak/io.github.tauseef666_ctrl.NP_Desktop.gpg`; installers can then verify it with +`flatpak install --gpg-file=...`. Set `FLATPAK_REPO_URL` to the public URL of a repository you +host to additionally write a signed OSTree repo and a matching `.flatpakrepo` file, which enables +updates through `flatpak update`. The release workflow imports `FLATPAK_GPG_PRIVATE_KEY` when that secret exists; without it the release still succeeds and publishes the unsigned bundle. ### Smoke test diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh index c7e840c87..b9f425f50 100755 --- a/packaging/flatpak/build-flatpak.sh +++ b/packaging/flatpak/build-flatpak.sh @@ -12,8 +12,10 @@ # The Flatpak runtime only provides the base system (glibc, graphics, audio, Wayland/X11). # # Environment: -# FLATPAK_GPG_KEY_ID sign the exported commit with this key (optional) +# FLATPAK_GPG_KEY_ID sign the bundle with this key (optional) # FLATPAK_GPG_HOME GnuPG home that contains the key (default: ~/.gnupg) +# FLATPAK_REPO_URL public URL of a self-hosted OSTree repo; when set, the script also +# exports an update repo and a matching .flatpakrepo file set -euo pipefail @@ -134,18 +136,26 @@ flatpak build-bundle "${SIGN_ARGS[@]}" --arch="$ARCH" \ echo "build-flatpak: $(du -h "$BUNDLE" | cut -f1) bundle at $BUNDLE" if [ -n "${FLATPAK_GPG_KEY_ID:-}" ]; then - flatpak build-update-repo "${SIGN_ARGS[@]}" "$REPO" gpg --homedir "${FLATPAK_GPG_HOME:-$HOME/.gnupg}" --armor \ --export "$FLATPAK_GPG_KEY_ID" > "$OUT/$APP_ID.gpg" + echo "build-flatpak: exported the public key to $OUT/$APP_ID.gpg" +fi + +if [ -n "${FLATPAK_REPO_URL:-}" ]; then + [ -n "${FLATPAK_GPG_KEY_ID:-}" ] || + fail "FLATPAK_REPO_URL requires FLATPAK_GPG_KEY_ID so clients can verify updates" + flatpak build-update-repo "${SIGN_ARGS[@]}" "$REPO" cat > "$OUT/$APP_ID.flatpakrepo" < Date: Fri, 4 Dec 2026 10:51:59 +0530 Subject: [PATCH 05/11] Point Flatpak users to the release bundle for updates --- .../kotlin/net/newpipe/app/platform/UpdateActions.kt | 4 ++-- .../jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt b/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt index 5859aea9c..411bff372 100644 --- a/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt +++ b/shared/src/commonMain/kotlin/net/newpipe/app/platform/UpdateActions.kt @@ -62,8 +62,8 @@ sealed interface UpdateStatus { data object NotAvailable : UpdateStatus /** - * Updates are managed outside the app, for example by Flatpak. The message explains the - * command the user has to run; the app never downloads or replaces its own files. + * Updates are managed outside the app, for example by Flatpak. The message explains what + * the user has to do; the app never downloads or replaces its own files. */ data class Managed(val message: String) : UpdateStatus diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt index 110557179..1f33be131 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/UpdateService.kt @@ -136,7 +136,7 @@ object UpdateService { suspend fun checkForUpdate(): UpdateStatus { if (DesktopPaths.isFlatpak) { val managed = UpdateStatus.Managed( - "Updates are managed by Flatpak. Run `flatpak update` to install a newer version." + "Updates are managed outside the app. Install the newer Flatpak bundle from the release page, or run `flatpak update` if this install uses a signed repository." ) updateStatus(managed) return managed @@ -171,7 +171,7 @@ object UpdateService { if (DesktopPaths.isFlatpak) { updateStatus( UpdateStatus.Managed( - "Updates are managed by Flatpak. Run `flatpak update` to install a newer version." + "Updates are managed outside the app. Install the newer Flatpak bundle from the release page, or run `flatpak update` if this install uses a signed repository." ) ) return From 5041e2c1f0bde5f6a496019942e5e94821fae83f Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 11:01:05 +0530 Subject: [PATCH 06/11] Fix Flatpak launcher layout and container smoke test JDK --- .github/workflows/ci.yml | 2 +- .github/workflows/release-linux.yml | 2 +- .github/workflows/release-windows.yml | 2 +- packaging/flatpak/build-flatpak.sh | 9 ++++++--- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c99b267a4..3c1435dc6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -96,6 +96,6 @@ jobs: docker run --rm -v "$PWD:/work" -w /work ubuntu:24.04 bash -c " set -e apt-get update >/dev/null - apt-get install -y --no-install-recommends openjdk-21-jre-headless ffmpeg >/dev/null + apt-get install -y --no-install-recommends openjdk-21-jdk-headless ffmpeg >/dev/null packaging/linux/smoke-test-vlc.sh '$app' " diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index e948cd415..5cc6467b9 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -132,7 +132,7 @@ jobs: docker run --rm -v "$PWD:/work" -w /work ubuntu:24.04 bash -c ' set -e apt-get update >/dev/null - apt-get install -y --no-install-recommends openjdk-21-jre-headless ffmpeg >/dev/null + apt-get install -y --no-install-recommends openjdk-21-jdk-headless ffmpeg >/dev/null packaging/linux/smoke-test-vlc.sh "${{ steps.locate.outputs.APP_DIR }}" ' diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml index 1324321fd..3be782eea 100644 --- a/.github/workflows/release-windows.yml +++ b/.github/workflows/release-windows.yml @@ -155,7 +155,7 @@ jobs: tarball, the Flatpak bundle and its CycloneDX SBOM. ```bash - sha256sum -c checksums-linux-sha256.txt # Linux + sha256sum -c --ignore-missing checksums-linux-sha256.txt # Linux ``` ```powershell (Get-FileHash .\*.msi -Algorithm SHA256).Hash # Windows diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh index b9f425f50..e6d91c0de 100755 --- a/packaging/flatpak/build-flatpak.sh +++ b/packaging/flatpak/build-flatpak.sh @@ -41,18 +41,21 @@ command -v flatpak >/dev/null 2>&1 || fail "flatpak is not installed" [ -x "$APP_IMAGE/bin/NP-Desktop" ] || fail "app image has no bin/NP-Desktop" rm -rf "$OUT" -mkdir -p "$STAGE/files" "$STAGE/bin" \ +mkdir -p "$STAGE/files" \ "$STAGE/export/share/applications" \ "$STAGE/export/share/metainfo" \ "$STAGE/export/share/icons/hicolor/256x256/apps" cp -a "$APP_IMAGE/." "$STAGE/files/" -cat > "$STAGE/bin/np-desktop" <<'EOF' +# /app/bin is backed by files/bin in a Flatpak; the wrapper keeps the exported command name +# stable even if jpackage changes the executable name. +mkdir -p "$STAGE/files/bin" +cat > "$STAGE/files/bin/np-desktop" <<'EOF' #!/bin/sh exec /app/files/bin/NP-Desktop "$@" EOF -chmod +x "$STAGE/bin/np-desktop" +chmod +x "$STAGE/files/bin/np-desktop" cp desktopApp/src/main/resources/app-icon.png \ "$STAGE/export/share/icons/hicolor/256x256/apps/$APP_ID.png" From aa505aef3b77d8db06fcdcb3b4bdde45f8f38ceb Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 11:02:15 +0530 Subject: [PATCH 07/11] Create the Dependency-Check output directory --- .github/workflows/security.yml | 1 + docs/SECURITY_CHECKS.md | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 8f8f32356..00e41d3f5 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -106,6 +106,7 @@ jobs: if [ -n "$NVD_API_KEY" ]; then args+=(--nvdApiKey "$NVD_API_KEY") fi + mkdir -p dependency-check-report /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" - name: Run Trivy on the packaged libraries diff --git a/docs/SECURITY_CHECKS.md b/docs/SECURITY_CHECKS.md index 545c35247..61a6e0022 100644 --- a/docs/SECURITY_CHECKS.md +++ b/docs/SECURITY_CHECKS.md @@ -24,6 +24,7 @@ gitleaks detect --source . --config .gitleaks.toml --redact --verbose # Dependency check against a local app image ./gradlew :desktopApp:createReleaseDistributable +mkdir -p dependency-check-report dependency-check.sh \ --project "NP Desktop" \ --scan desktopApp/build/compose/binaries/main-release/app/*/lib/app \ From e33987c996a62d059f25c0ec8095f664d32ba037 Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 11:08:11 +0530 Subject: [PATCH 08/11] Use a supported Flatpak runtime and fix the NVD key handling --- .github/workflows/build-release-apk.yml | 4 ++-- .github/workflows/release-linux.yml | 2 +- .github/workflows/security.yml | 7 ++++++- buildSrc/src/main/kotlin/ProjectConfig.kt | 2 +- docs/THIRD_PARTY_NOTICES.md | 2 +- packaging/README.md | 2 +- packaging/flatpak/build-flatpak.sh | 4 ++-- 7 files changed, 14 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build-release-apk.yml b/.github/workflows/build-release-apk.yml index 81e5fd773..bfb51d5f2 100644 --- a/.github/workflows/build-release-apk.yml +++ b/.github/workflows/build-release-apk.yml @@ -4,9 +4,9 @@ on: workflow_dispatch: inputs: tag: - description: 'Tag to build and release (e.g. v0.25.5). APK is attached to this release.' + description: 'Tag to build and release (e.g. v0.26.0). APK is attached to this release.' required: true - default: 'v0.25.5' + default: 'v0.26.0' permissions: contents: write diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index 5cc6467b9..d6be5afa4 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -164,7 +164,7 @@ jobs: flatpak remote-add --user --if-not-exists flathub \ https://dl.flathub.org/repo/flathub.flatpakrepo flatpak install --user -y --noninteractive flathub \ - org.freedesktop.Platform//24.08 + org.freedesktop.Platform//26.08 - name: Smoke test the Flatpak bundle shell: bash diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 00e41d3f5..f794f5f00 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -103,13 +103,18 @@ jobs: --out dependency-check-report --failOnCVSS 7 ) - if [ -n "$NVD_API_KEY" ]; then + if [ -n "${NVD_API_KEY:-}" ]; then args+=(--nvdApiKey "$NVD_API_KEY") + else + # An empty NVD_API_KEY still counts as a configured key and the CLI rejects it; + # remove the variable so the public feed is used. + unset NVD_API_KEY fi mkdir -p dependency-check-report /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" - name: Run Trivy on the packaged libraries + if: always() uses: aquasecurity/trivy-action@v0.36.0 with: scan-type: fs diff --git a/buildSrc/src/main/kotlin/ProjectConfig.kt b/buildSrc/src/main/kotlin/ProjectConfig.kt index 58479209c..6da916ae4 100644 --- a/buildSrc/src/main/kotlin/ProjectConfig.kt +++ b/buildSrc/src/main/kotlin/ProjectConfig.kt @@ -8,7 +8,7 @@ const val NEWPIPE_VERSION_SDK_COMPILE_MINOR = 0 const val NEWPIPE_VERSION_SDK_MIN = 23 const val NEWPIPE_VERSION_SDK_TARGET = 35 -const val NEWPIPE_VERSION_CODE = 1016 +const val NEWPIPE_VERSION_CODE = 1017 const val NEWPIPE_VERSION_NAME = "0.26.0" const val NEWPIPE_APPLICATION_ID_OLD = "org.schabi.newpipe" diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md index 3565c1ece..3858a3e61 100644 --- a/docs/THIRD_PARTY_NOTICES.md +++ b/docs/THIRD_PARTY_NOTICES.md @@ -22,7 +22,7 @@ authoritative list; `./gradlew :desktopApp:dependencies` prints it. ## Flatpak -The Flatpak bundle uses the `org.freedesktop.Platform` 24.08 runtime, which is distributed by the +The Flatpak bundle uses the `org.freedesktop.Platform` 26.08 runtime, which is distributed by the Flatpak project under the licences of its component projects. The runtime is not embedded in the `.flatpak` file; Flatpak installs it separately. diff --git a/packaging/README.md b/packaging/README.md index 08be757f6..7654482fe 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -32,7 +32,7 @@ Release builds must always pass `-PvlcPrefix`. ## Linux: Flatpak -Requirements: `flatpak`. The `org.freedesktop.Platform//24.08` runtime is required to install +Requirements: `flatpak`. The `org.freedesktop.Platform//26.08` runtime is required to install and smoke-test the bundle, but not to export it. The app image must already contain the JRE and libVLC. diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh index e6d91c0de..4bd6362df 100755 --- a/packaging/flatpak/build-flatpak.sh +++ b/packaging/flatpak/build-flatpak.sh @@ -26,8 +26,8 @@ OUT=${3:-build/flatpak} APP_ID=io.github.tauseef666_ctrl.NP_Desktop BRANCH=stable ARCH=x86_64 -RUNTIME=org.freedesktop.Platform/x86_64/24.08 -SDK=org.freedesktop.Sdk/x86_64/24.08 +RUNTIME=org.freedesktop.Platform/x86_64/26.08 +SDK=org.freedesktop.Sdk/x86_64/26.08 REPO="$OUT/repo" STAGE="$OUT/app" From 21f6e3d9c0b8424454a0f43c4bacda340f0984e7 Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 11:20:00 +0530 Subject: [PATCH 09/11] Fix the Flatpak sandbox layout and use the NVD datafeed mirror --- .github/workflows/release-linux.yml | 16 ++++++++++------ .github/workflows/security.yml | 12 +++--------- docs/SECURITY_CHECKS.md | 7 ++++--- packaging/README.md | 4 ++-- packaging/flatpak/build-flatpak.sh | 2 +- 5 files changed, 20 insertions(+), 21 deletions(-) diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.yml index d6be5afa4..2f441ee13 100644 --- a/.github/workflows/release-linux.yml +++ b/.github/workflows/release-linux.yml @@ -173,15 +173,19 @@ jobs: test -n "$bundle" flatpak install --user -y --noninteractive "$bundle" flatpak info io.github.tauseef666_ctrl.NP_Desktop >/dev/null - # The launcher, the exported desktop file, the AppStream metadata and the bundled - # jars must all be present; this runs without a display or audio server. + # The desktop file, icon and AppStream metadata are exported next to the deployment, + # not into /app. The app image itself is mounted at /app. + location=$(flatpak info --user --show-location io.github.tauseef666_ctrl.NP_Desktop) + test -f "$location/export/share/applications/io.github.tauseef666_ctrl.NP_Desktop.desktop" + test -f "$location/export/share/metainfo/io.github.tauseef666_ctrl.NP_Desktop.metainfo.xml" + test -f "$location/export/share/icons/hicolor/256x256/apps/io.github.tauseef666_ctrl.NP_Desktop.png" + # The launcher and the bundled jars must be present; this runs without a display or + # audio server. flatpak run --command=sh io.github.tauseef666_ctrl.NP_Desktop -c ' set -e test -x /app/bin/np-desktop - test -f /app/share/applications/io.github.tauseef666_ctrl.NP_Desktop.desktop - test -f /app/share/metainfo/io.github.tauseef666_ctrl.NP_Desktop.metainfo.xml - test -f /app/files/bin/NP-Desktop - ls /app/files/lib/app/*.jar >/dev/null + test -x /app/bin/NP-Desktop + ls /app/lib/app/*.jar >/dev/null ' flatpak uninstall --user -y io.github.tauseef666_ctrl.NP_Desktop diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index f794f5f00..04955ed9f 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -89,8 +89,6 @@ jobs: echo "APP_DIR=$app" >> "$GITHUB_OUTPUT" - name: Run OWASP Dependency-Check - env: - NVD_API_KEY: ${{ secrets.NVD_API_KEY }} run: | curl -fsSL -o /tmp/dependency-check.zip \ "https://github.com/dependency-check/DependencyCheck/releases/download/v${DEPENDENCY_CHECK_VERSION}/dependency-check-${DEPENDENCY_CHECK_VERSION}-release.zip" @@ -102,14 +100,10 @@ jobs: --format JSON --out dependency-check-report --failOnCVSS 7 + # Dependency-Check 13 rejects an empty NVD API key, so use the project's NVD 2.0 + # datafeed mirror. It needs no key and is rebuilt from the NVD every day. + --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" ) - if [ -n "${NVD_API_KEY:-}" ]; then - args+=(--nvdApiKey "$NVD_API_KEY") - else - # An empty NVD_API_KEY still counts as a configured key and the CLI rejects it; - # remove the variable so the public feed is used. - unset NVD_API_KEY - fi mkdir -p dependency-check-report /tmp/dependency-check/bin/dependency-check.sh "${args[@]}" diff --git a/docs/SECURITY_CHECKS.md b/docs/SECURITY_CHECKS.md index 61a6e0022..3872ce917 100644 --- a/docs/SECURITY_CHECKS.md +++ b/docs/SECURITY_CHECKS.md @@ -28,7 +28,8 @@ mkdir -p dependency-check-report dependency-check.sh \ --project "NP Desktop" \ --scan desktopApp/build/compose/binaries/main-release/app/*/lib/app \ - --format HTML --out dependency-check-report --failOnCVSS 7 + --format HTML --out dependency-check-report --failOnCVSS 7 \ + --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" # Trivy on the same jars trivy fs --scanners vuln --severity HIGH,CRITICAL \ @@ -38,8 +39,8 @@ trivy fs --scanners vuln --severity HIGH,CRITICAL \ syft desktopApp/build/compose/binaries/main-release/app -o cyclonedx-json=sbom.cyclonedx.json ``` -`NVD_API_KEY` is optional. Without it Dependency-Check uses the public NVD feed, which is slower and -rate limited; the workflow caches the NVD data between runs. +Dependency-Check uses the Dependency-Check project's NVD 2.0 datafeed mirror instead of the NVD +API, so no NVD API key is required. The workflow caches the vulnerability database between runs. ## Notes diff --git a/packaging/README.md b/packaging/README.md index 7654482fe..4621ef3ef 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -44,7 +44,7 @@ packaging/flatpak/build-flatpak.sh \ The script exports the app image plus the desktop file, icon and AppStream metadata, then writes `build/flatpak/np-desktop-0.26.0-x86_64.flatpak`. It does not need `flatpak-builder` because the -self-contained app image is copied into `/app/files`. +self-contained app image is copied into `/app`. ### Signing @@ -61,7 +61,7 @@ secret exists; without it the release still succeeds and publishes the unsigned ```bash flatpak install --user -y build/flatpak/np-desktop-0.26.0-x86_64.flatpak flatpak run --command=sh io.github.tauseef666_ctrl.NP_Desktop -c \ - 'test -x /app/bin/np-desktop && ls /app/files/lib/app/*.jar' + 'test -x /app/bin/np-desktop && ls /app/lib/app/*.jar' flatpak uninstall --user -y io.github.tauseef666_ctrl.NP_Desktop ``` diff --git a/packaging/flatpak/build-flatpak.sh b/packaging/flatpak/build-flatpak.sh index 4bd6362df..de6794f85 100755 --- a/packaging/flatpak/build-flatpak.sh +++ b/packaging/flatpak/build-flatpak.sh @@ -53,7 +53,7 @@ cp -a "$APP_IMAGE/." "$STAGE/files/" mkdir -p "$STAGE/files/bin" cat > "$STAGE/files/bin/np-desktop" <<'EOF' #!/bin/sh -exec /app/files/bin/NP-Desktop "$@" +exec /app/bin/NP-Desktop "$@" EOF chmod +x "$STAGE/files/bin/np-desktop" From f97c91614a33557e725bef6e4b55b41994face6c Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 16:47:54 +0530 Subject: [PATCH 10/11] Upgrade JAVE and resolve the dependency scan findings JAVE 4.2.0 bundles ffmpeg 9.0.1. Selecting only the build host's native package removes the stale Windows ffmpeg binaries (and their 1,200+ findings) from the Linux app image. okhttp-brotli is dropped because CVE-2023-3782 has no fixed release; gzip is enough for the extractor. Version-pinned suppressions document the JNA, protobuf-java and Square Wire false positives. --- .github/workflows/security.yml | 1 + app/build.gradle.kts | 1 - docs/SECURITY_CHECKS.md | 14 ++++++ gradle/libs.versions.toml | 12 +++-- security/dependency-check-suppressions.xml | 46 +++++++++++++++++++ shared/build.gradle.kts | 33 +++++++++++-- .../net/newpipe/app/service/JvmDownloader.kt | 5 +- 7 files changed, 102 insertions(+), 10 deletions(-) create mode 100644 security/dependency-check-suppressions.xml diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 04955ed9f..2ceaaa833 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -100,6 +100,7 @@ jobs: --format JSON --out dependency-check-report --failOnCVSS 7 + --suppression security/dependency-check-suppressions.xml # Dependency-Check 13 rejects an empty NVD API key, so use the project's NVD 2.0 # datafeed mirror. It needs no key and is rebuilt from the NVD every day. --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6e05fc523..8fb86cf2d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -270,7 +270,6 @@ dependencies { // HTTP client implementation(libs.squareup.okhttp) - implementation(libs.squareup.okhttp.brotli) // Media player implementation(libs.google.exoplayer.core) diff --git a/docs/SECURITY_CHECKS.md b/docs/SECURITY_CHECKS.md index 3872ce917..974439808 100644 --- a/docs/SECURITY_CHECKS.md +++ b/docs/SECURITY_CHECKS.md @@ -29,6 +29,7 @@ dependency-check.sh \ --project "NP Desktop" \ --scan desktopApp/build/compose/binaries/main-release/app/*/lib/app \ --format HTML --out dependency-check-report --failOnCVSS 7 \ + --suppression security/dependency-check-suppressions.xml \ --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" # Trivy on the same jars @@ -42,6 +43,19 @@ syft desktopApp/build/compose/binaries/main-release/app -o cyclonedx-json=sbom.c Dependency-Check uses the Dependency-Check project's NVD 2.0 datafeed mirror instead of the NVD API, so no NVD API key is required. The workflow caches the vulnerability database between runs. +## Suppressions + +False positives are documented in `security/dependency-check-suppressions.xml`. A rule has to name +the exact artifact version and list the individual CVEs it covers, so an upgrade makes the rule +stop matching and the new artifact is scanned normally. Rules are only acceptable when the CVE +cannot apply to the shipped code (for example, a Python-only advisory matched against the Java +protobuf runtime) or when Dependency-Check matched the wrong product entirely. Real vulnerabilities +are fixed by upgrading or removing the dependency instead of being suppressed. + +The app bundles only the ffmpeg binary for the platform it is built on. JAVE's +`jave-nativebin-*` packages are selected at configuration time, so Windows and macOS binaries are +not shipped in, or scanned from, a Linux build. + ## Notes - The build job runs without a bundled libVLC runtime. Packaging and playback are covered by the diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index f1a5f56ec..08d1a63ff 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -27,7 +27,7 @@ espresso = "3.7.0" exoplayer = "2.19.1" fragment = "1.9.1" groupie = "2.10.1" -jave = "3.5.0" +jave = "4.2.0" json = "20260522" jsoup = "1.23.2" junit = "4.13.2" @@ -148,7 +148,14 @@ google-exoplayer-smoothstreaming = { module = "com.google.android.exoplayer:exop google-exoplayer-ui = { module = "com.google.android.exoplayer:exoplayer-ui", version.ref = "exoplayer" } jakewharton-phoenix = { module = "com.jakewharton:process-phoenix", version.ref = "phoenix" } jakewharton-rxbinding = { module = "com.jakewharton.rxbinding4:rxbinding", version.ref = "rxbinding" } -jave-all-deps = { module = "ws.schild:jave-all-deps", version.ref = "jave" } +jave-core = { module = "ws.schild:jave-core", version.ref = "jave" } +jave-nativebin-linux-arm32 = { module = "ws.schild:jave-nativebin-linux-arm32", version.ref = "jave" } +jave-nativebin-linux-arm64 = { module = "ws.schild:jave-nativebin-linux-arm64", version.ref = "jave" } +jave-nativebin-linux64 = { module = "ws.schild:jave-nativebin-linux64", version.ref = "jave" } +jave-nativebin-osx64 = { module = "ws.schild:jave-nativebin-osx64", version.ref = "jave" } +jave-nativebin-osxm1 = { module = "ws.schild:jave-nativebin-osxm1", version.ref = "jave" } +jave-nativebin-win-arm64 = { module = "ws.schild:jave-nativebin-win-arm64", version.ref = "jave" } +jave-nativebin-win64 = { module = "ws.schild:jave-nativebin-win64", version.ref = "jave" } jetbrains-compose-foundation = { module = "org.jetbrains.compose.foundation:foundation", version.ref = "multiplatform" } jetbrains-compose-material3 = { module = "org.jetbrains.compose.material3:material3", version.ref = "material3" } jetbrains-compose-preview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "multiplatform" } @@ -193,7 +200,6 @@ squareup-leakcanary-core = { module = "com.squareup.leakcanary:leakcanary-androi squareup-leakcanary-plumber = { module = "com.squareup.leakcanary:plumber-android", version.ref = "leakcanary" } squareup-leakcanary-watcher = { module = "com.squareup.leakcanary:leakcanary-object-watcher-android", version.ref = "leakcanary" } squareup-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } -squareup-okhttp-brotli = { module = "com.squareup.okhttp3:okhttp-brotli", version.ref = "okhttp" } touchlab-kermit = { module = "co.touchlab:kermit", version.ref = "kermit" } vlcj = { module = "uk.co.caprica:vlcj", version.ref = "vlcj" } zacsweers-autoservice-compiler = { module = "dev.zacsweers.autoservice:auto-service-ksp", version.ref = "autoservice-zacsweers" } diff --git a/security/dependency-check-suppressions.xml b/security/dependency-check-suppressions.xml new file mode 100644 index 000000000..905928948 --- /dev/null +++ b/security/dependency-check-suppressions.xml @@ -0,0 +1,46 @@ + + + + + + + .*/jna-jpms-5\.14\.0-[^/]*\.jar + CVE-2009-2475 + CVE-2009-2476 + CVE-2009-2676 + CVE-2009-2689 + CVE-2009-2690 + CVE-2009-2716 + CVE-2009-2717 + CVE-2009-2719 + CVE-2009-2720 + + + + + .*/protobuf-java-4\.35\.1-[^/]*\.jar + CVE-2026-0994 + + + + + .*/wire-runtime-jvm-6\.4\.1-[^/]*\.jar + CVE-2018-8909 + CVE-2023-22737 + + diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index a84aea84c..bf475cad4 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -32,6 +32,31 @@ val buildConfigGenerator by tasks.registering(Sync::class) { into(layout.buildDirectory.dir("generated/kotlin/")) } +// JAVE publishes one ffmpeg binary per platform. Depending on the single binary for the build +// host instead of jave-all-deps keeps every other platform's ffmpeg out of the app image, the +// SBOM and the dependency scan. +val javeNative = run { + val os = System.getProperty("os.name") + val arch = System.getProperty("os.arch") + when { + os.startsWith("Windows", ignoreCase = true) && arch in setOf("aarch64", "arm64") -> + libs.jave.nativebin.win.arm64 + os.startsWith("Windows", ignoreCase = true) -> + libs.jave.nativebin.win64 + os.startsWith("Mac", ignoreCase = true) && arch in setOf("aarch64", "arm64") -> + libs.jave.nativebin.osxm1 + os.startsWith("Mac", ignoreCase = true) -> + libs.jave.nativebin.osx64 + os.startsWith("Linux", ignoreCase = true) && arch in setOf("aarch64", "arm64") -> + libs.jave.nativebin.linux.arm64 + os.startsWith("Linux", ignoreCase = true) && arch == "arm" -> + libs.jave.nativebin.linux.arm32 + os.startsWith("Linux", ignoreCase = true) -> + libs.jave.nativebin.linux64 + else -> error("No bundled ffmpeg for $os/$arch") + } +} + kotlin { jvmToolchain(21) @@ -145,7 +170,6 @@ kotlin { // the desktop JVM has to carry it itself for the engine's parser paths. implementation(libs.org.json) implementation(libs.squareup.okhttp) - implementation(libs.squareup.okhttp.brotli) // Fetcher for Coil, the image loading library used by the content lists implementation(libs.coil.network.okhttp) @@ -153,9 +177,10 @@ kotlin { // libVLC bindings, used for the media playback of the desktop application implementation(libs.vlcj) - // Static ffmpeg binaries, used to merge a video-only stream and its audio file - // into a single playable video file - implementation(libs.jave.all.deps) + // Static ffmpeg binary, used to merge a video-only stream and its audio file into a + // single playable video file. Only the binary for the build host is packaged. + implementation(libs.jave.core) + implementation(javeNative) } val androidDeviceTest by getting { dependencies { diff --git a/shared/src/jvmMain/kotlin/net/newpipe/app/service/JvmDownloader.kt b/shared/src/jvmMain/kotlin/net/newpipe/app/service/JvmDownloader.kt index 43a0926b2..0c2a10158 100644 --- a/shared/src/jvmMain/kotlin/net/newpipe/app/service/JvmDownloader.kt +++ b/shared/src/jvmMain/kotlin/net/newpipe/app/service/JvmDownloader.kt @@ -12,7 +12,6 @@ import okhttp3.CompressionInterceptor import okhttp3.Gzip import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.brotli.Brotli import org.schabi.newpipe.extractor.downloader.CancellableCall import org.schabi.newpipe.extractor.downloader.Downloader import org.schabi.newpipe.extractor.downloader.Downloader.AsyncCallback @@ -36,7 +35,9 @@ class JvmDownloader( private val client: OkHttpClient = builder .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS) .connectTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS) - .addInterceptor(CompressionInterceptor(Brotli, Gzip)) + // Gzip only. okhttp-brotli has an unfixed decompression-bomb advisory + // (CVE-2023-3782) and the extractor does not need Brotli. + .addInterceptor(CompressionInterceptor(Gzip)) .build() private val cookies = ConcurrentHashMap() From 018baca03f895c3e000953dc402b0e4c6d85f124 Mon Sep 17 00:00:00 2001 From: Tauseef666-ctrl Date: Fri, 4 Dec 2026 17:07:15 +0530 Subject: [PATCH 11/11] Disable the flaky Maven Central analyzer in the dependency scan search.maven.org regularly times out from GitHub-hosted runners, which made Dependency-Check abort with exit code 14 even when the scan itself found nothing. The analyzer only contributes evidence and is not needed for the NVD match. --- .github/workflows/security.yml | 3 +++ docs/SECURITY_CHECKS.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 2ceaaa833..48dec2394 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -101,6 +101,9 @@ jobs: --out dependency-check-report --failOnCVSS 7 --suppression security/dependency-check-suppressions.xml + # The Central analyzer is only an evidence source and fails the whole run when + # search.maven.org times out, which it regularly does from GitHub-hosted runners. + --disableCentral # Dependency-Check 13 rejects an empty NVD API key, so use the project's NVD 2.0 # datafeed mirror. It needs no key and is rebuilt from the NVD every day. --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" diff --git a/docs/SECURITY_CHECKS.md b/docs/SECURITY_CHECKS.md index 974439808..7c8f944e1 100644 --- a/docs/SECURITY_CHECKS.md +++ b/docs/SECURITY_CHECKS.md @@ -30,6 +30,7 @@ dependency-check.sh \ --scan desktopApp/build/compose/binaries/main-release/app/*/lib/app \ --format HTML --out dependency-check-report --failOnCVSS 7 \ --suppression security/dependency-check-suppressions.xml \ + --disableCentral \ --nvdDatafeed "https://dependency-check.github.io/DependencyCheck_Builder/nvd_cache/nvdcve-{0}.json.gz" # Trivy on the same jars @@ -42,6 +43,8 @@ syft desktopApp/build/compose/binaries/main-release/app -o cyclonedx-json=sbom.c Dependency-Check uses the Dependency-Check project's NVD 2.0 datafeed mirror instead of the NVD API, so no NVD API key is required. The workflow caches the vulnerability database between runs. +The Maven Central analyzer is disabled: it only adds identifying evidence, and a timeout on +`search.maven.org` aborts the entire scan with exit code 14. ## Suppressions