diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index ee9519c..1d90cda 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -32,5 +32,5 @@ body:
id: log
attributes:
label: Relevant log lines (optional)
- description: Easiest is **Copy diagnostics** on the Help tab of the settings window (it names what you played; folder paths, sign-ins and keys are left out). Or paste lines from the Help tab or `mpcvibedrpc.log` in the settings folder (**Open settings folder** under Advanced > Maintenance).
+ description: Easiest is **Copy diagnostics** on the Help tab of the settings window (it names what you played; folder paths, sign-ins and keys are left out). Or paste lines from the Help tab or `mprp.log` in the settings folder (**Open settings folder** under Advanced > Maintenance).
render: text
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 2950a4e..2560817 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,5 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Security problem
- url: https://github.com/CptPakundo/MPCvibedRPC/security/advisories/new
+ url: https://github.com/CptPakundo/MPRP/security/advisories/new
about: Please report security problems privately here instead of in a public issue.
\ No newline at end of file
diff --git a/.github/actions/build-unix/action.yml b/.github/actions/build-unix/action.yml
index d6c98dd..54a1f3c 100644
--- a/.github/actions/build-unix/action.yml
+++ b/.github/actions/build-unix/action.yml
@@ -1,6 +1,6 @@
# Builds the Linux programs (on a Linux runner) or the macOS app (on a macOS runner) the way a release is built, then
# smoke-tests them for real in a throwaway folder (tools/ci/smoke-unix.sh), for ci.yml and release.yml alike. The job
-# must have checked out and set up Go before. Output: dist/ (MPCvibedRPC-linux-amd64 and -arm64, or MPCvibedRPC-macos.zip).
+# must have checked out and set up Go before. Output: dist/ (MPRP-linux-amd64 and -arm64, or MPRP-macos.zip).
name: Build and smoke-test the Linux or macOS program
description: dist/ for this runner's system, then tools/ci/smoke-unix.sh
inputs:
@@ -18,16 +18,16 @@ runs:
run: |
mkdir -p dist
for arch in amd64 arm64; do
- CGO_ENABLED=0 GOOS=linux GOARCH=$arch go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$V" -o dist/MPCvibedRPC-linux-$arch ./cmd/mpcvibedrpc
+ CGO_ENABLED=0 GOOS=linux GOARCH=$arch go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$V" -o dist/MPRP-linux-$arch ./cmd/mprp
done
ls -l dist
- echo "::notice title=linux-amd64 size::$(stat -c %s dist/MPCvibedRPC-linux-amd64) bytes"
+ echo "::notice title=linux-amd64 size::$(stat -c %s dist/MPRP-linux-amd64) bytes"
- name: Smoke test (Linux)
if: runner.os == 'Linux'
shell: bash
env:
V: ${{ inputs.version }}
- run: PASSED_FILE="$RUNNER_TEMP/smoke-ok" ./tools/ci/run-annotated.sh "smoke test" ./tools/ci/smoke-unix.sh "$PWD/dist/MPCvibedRPC-linux-amd64" "$V"
+ run: PASSED_FILE="$RUNNER_TEMP/smoke-ok" ./tools/ci/run-annotated.sh "smoke test" ./tools/ci/smoke-unix.sh "$PWD/dist/MPRP-linux-amd64" "$V"
- name: Build (macOS app)
if: runner.os == 'macOS'
shell: bash
@@ -40,6 +40,6 @@ runs:
env:
V: ${{ inputs.version }}
run: |
- mkdir -p "$RUNNER_TEMP/app" && ditto -x -k dist/MPCvibedRPC-macos.zip "$RUNNER_TEMP/app"
- app="$RUNNER_TEMP/app/MPCvibedRPC.app"
- SCREENSHOT="$RUNNER_TEMP/macos-window.png" PASSED_FILE="$RUNNER_TEMP/smoke-ok" ./tools/ci/run-annotated.sh "smoke test" ./tools/ci/smoke-unix.sh "$app/Contents/MacOS/MPCvibedRPC" "$V" "$app"
+ mkdir -p "$RUNNER_TEMP/app" && ditto -x -k dist/MPRP-macos.zip "$RUNNER_TEMP/app"
+ app="$RUNNER_TEMP/app/MPRP.app"
+ SCREENSHOT="$RUNNER_TEMP/macos-window.png" PASSED_FILE="$RUNNER_TEMP/smoke-ok" ./tools/ci/run-annotated.sh "smoke test" ./tools/ci/smoke-unix.sh "$app/Contents/MacOS/MPRP" "$V" "$app"
diff --git a/.github/actions/build-windows/action.yml b/.github/actions/build-windows/action.yml
index 1e5d645..cd70763 100644
--- a/.github/actions/build-windows/action.yml
+++ b/.github/actions/build-windows/action.yml
@@ -1,9 +1,9 @@
# Builds the Windows program the way a release is built and smoke-tests it, for ci.yml and release.yml alike:
-# dist/MPCvibedRPC.exe (and dist/next.exe, the version after it, which the smoke test updates to) from an LF checkout
+# dist/MPRP.exe (and dist/next.exe, the version after it, which the smoke test updates to) from an LF checkout
# without cgo, so the Linux rebuild (tools/ci/reproduce.sh) gives the same bytes. The job must have checked out with
# core.autocrlf off and set up Go before.
name: Build and smoke-test the Windows program
-description: dist/MPCvibedRPC.exe and dist/next.exe, then tools/ci/smoke.ps1
+description: dist/MPRP.exe and dist/next.exe, then tools/ci/smoke.ps1
inputs:
version:
description: the version being built (VERSION from tools/ci/version.sh)
@@ -22,12 +22,12 @@ runs:
run: |
$env:CGO_ENABLED = '0' # no cgo: the exe can be rebuilt anywhere, byte for byte
New-Item -ItemType Directory dist -Force | Out-Null
- go run ./tools/mkrsrc -version $env:V -out cmd/mpcvibedrpc/rsrc_windows_amd64.syso
- go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$env:V" -o dist/MPCvibedRPC.exe ./cmd/mpcvibedrpc
- go run ./tools/mkrsrc -version $env:N -out cmd/mpcvibedrpc/rsrc_windows_amd64.syso
- go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$env:N" -o dist/next.exe ./cmd/mpcvibedrpc
+ go run ./tools/mkrsrc -version $env:V -out cmd/mprp/rsrc_windows_amd64.syso
+ go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$env:V" -o dist/MPRP.exe ./cmd/mprp
+ go run ./tools/mkrsrc -version $env:N -out cmd/mprp/rsrc_windows_amd64.syso
+ go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$env:N" -o dist/next.exe ./cmd/mprp
Get-ChildItem dist | Format-Table Name, Length
- Write-Host "::notice title=exe size::$((Get-Item dist/MPCvibedRPC.exe).Length) bytes"
+ Write-Host "::notice title=exe size::$((Get-Item dist/MPRP.exe).Length) bytes"
# the checkout must be LF, or the rebuild on Linux cannot match
$crlf = git ls-files --eol | Select-String "w/crlf"
if ($crlf) { $crlf | Select-Object -First 5; Write-Host "::error title=build::the checkout has CRLF files; the exe would not be reproducible"; exit 1 }
@@ -36,4 +36,4 @@ runs:
env:
V: ${{ inputs.version }}
N: ${{ inputs.next }}
- run: ./tools/ci/smoke.ps1 -Exe "$PWD/dist/MPCvibedRPC.exe" -NewExe "$PWD/dist/next.exe" -Version $env:V -NextVersion $env:N
+ run: ./tools/ci/smoke.ps1 -Exe "$PWD/dist/MPRP.exe" -NewExe "$PWD/dist/next.exe" -Version $env:V -NextVersion $env:N
diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml
index 93f51b3..6c99203 100644
--- a/.github/workflows/canary.yml
+++ b/.github/workflows/canary.yml
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with: { go-version-file: go.mod, cache: false }
- name: Live catalog check
- run: MPCRPC_LIVE_CATALOGS=1 ./tools/ci/run-annotated.sh "live catalogs" ./tools/ci/must-pass.sh TestLiveCatalogs go test -count=1 -run TestLiveCatalogs -v ./internal/artwork
+ run: MPRP_LIVE_CATALOGS=1 ./tools/ci/run-annotated.sh "live catalogs" ./tools/ci/must-pass.sh TestLiveCatalogs go test -count=1 -run TestLiveCatalogs -v ./internal/artwork
shell: bash
# mpv, VLC and Celluloid as their makers release them (Flathub), with the live engine test and a pause from their events.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 090b1e5..030494f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -124,8 +124,8 @@ jobs:
with: { version: "${{ env.VERSION }}", next: "${{ env.NEXT }}" }
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- name: MPCvibedRPC-windows
- path: dist/MPCvibedRPC.exe
+ name: MPRP-windows
+ path: dist/MPRP.exe
# The exe again, built on Linux from the same files: it must be the same, byte for byte, so anyone can rebuild a
# release and check it (release.yml does that for every release before it is published).
@@ -143,11 +143,11 @@ jobs:
shell: bash
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
- name: MPCvibedRPC-windows
+ name: MPRP-windows
path: windows
- name: Rebuild and compare
shell: bash
- run: ./tools/ci/reproduce.sh "$VERSION" rebuilt && ./tools/ci/reproduce.sh compare windows/MPCvibedRPC.exe rebuilt/MPCvibedRPC.exe
+ run: ./tools/ci/reproduce.sh "$VERSION" rebuilt && ./tools/ci/reproduce.sh compare windows/MPRP.exe rebuilt/MPRP.exe
# The Linux programs and the macOS app as a release builds them (.github/actions/build-unix), started for real in
# throwaway folders.
@@ -178,7 +178,7 @@ jobs:
if-no-files-found: ignore
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- name: MPCvibedRPC-${{ runner.os == 'macOS' && 'macos' || 'linux' }}
+ name: MPRP-${{ runner.os == 'macOS' && 'macos' || 'linux' }}
path: dist/*
# The live jobs below run once per pull request (opened, reopened or marked ready), by hand, and from the canary: not
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index d5e3816..d197fdf 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -25,7 +25,7 @@ jobs:
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with: { go-version-file: go.mod, cache: false }
- run: go test -count=1 -run 'TestEverySettingIsDocumented' ./internal/store
- - run: go test -count=1 -run 'TestPlayersAreNamedEverywhere' ./cmd/mpcvibedrpc
+ - run: go test -count=1 -run 'TestPlayersAreNamedEverywhere' ./cmd/mprp
- run: go test -count=1 -run 'TestSecurityListsEveryHost|TestEveryHostIsListed' ./internal/core
- run: go test -count=1 ./tools/relnotes
- run: go test -count=1 ./tools/doclinks
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5f576e9..bce8fc3 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,8 +1,9 @@
-# Publishes a release when a version tag is pushed: git tag -a vX.Y.Z -m "MPCvibedRPC X.Y.Z" && git push origin vX.Y.Z
-# The tag must match the version in cmd/mpcvibedrpc/main.go. The program's own updater looks for its file
-# (MPCvibedRPC.exe, MPCvibedRPC-linux-amd64, ...) and the .sha256 next to it on the latest release; on macOS it links to
-# the release page. The release is first a draft; it is made public only once its files check out, and then the update
-# path is tried on it (tools/ci/verify-release.ps1).
+# Publishes a release when a version tag is pushed: git tag -a vX.Y.Z -m "MPRP X.Y.Z" && git push origin vX.Y.Z
+# The tag must match the version in cmd/mprp/main.go. The program's own updater looks for its file
+# (MPRP.exe, MPRP-linux-amd64, ...) and the .sha256 next to it on the latest release; on macOS it links to
+# the release page. Each program file is also published under the program's former name, for copies installed
+# before the rename (tools/ci/former-names.txt). The release is first a draft; it is made public only once its files
+# check out, and then the update path is tried on it (tools/ci/verify-release.ps1).
name: release
on:
push:
@@ -23,6 +24,17 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+ # Every copy looks for its updates (and the player logos) in the repository the code names: DefaultUpdateRepo in
+ # internal/store/store.go (store's TestReleaseChecksTheRepositoryName ties this step to it). A repository that
+ # was not renamed yet would publish a release that no copy finds after it updates: rename it first.
+ - name: The repository has the name the code gives it
+ shell: bash
+ run: |
+ want=$(sed -n 's/^const DefaultUpdateRepo = "\(.*\)"$/\1/p' internal/store/store.go)
+ if [ -z "$want" ] || [ "$GITHUB_REPOSITORY" != "$want" ]; then
+ echo "::error title=Wrong repository name::This repository is $GITHUB_REPOSITORY, but the code publishes and updates from ${want:-(DefaultUpdateRepo not found)} (DefaultUpdateRepo in internal/store/store.go). Rename the repository first (docs/maintaining.md > Releasing), then delete and push the tag again."
+ exit 1
+ fi
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with: { go-version-file: go.mod, cache: false }
- run: ./tools/ci/version.sh "$TAG"
@@ -86,23 +98,36 @@ jobs:
id: sums
shell: pwsh
run: |
- foreach ($f in 'MPCvibedRPC.exe', 'MPCvibedRPC-linux-amd64', 'MPCvibedRPC-linux-arm64', 'MPCvibedRPC-macos.zip') {
+ foreach ($f in 'MPRP.exe', 'MPRP-linux-amd64', 'MPRP-linux-arm64', 'MPRP-macos.zip') {
$h = (Get-FileHash "dist/$f" -Algorithm SHA256).Hash.ToLower()
Set-Content -LiteralPath "dist/$f.sha256" -Value "$h $f`n" -NoNewline
- $key = @{ 'MPCvibedRPC.exe' = 'exe'; 'MPCvibedRPC-linux-amd64' = 'linux_amd64'; 'MPCvibedRPC-linux-arm64' = 'linux_arm64' }[$f]
+ $key = @{ 'MPRP.exe' = 'exe'; 'MPRP-linux-amd64' = 'linux_amd64'; 'MPRP-linux-arm64' = 'linux_arm64' }[$f]
if ($key) { Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "$key=$h" }
}
+ # Copies installed before the rename look for their update under the former file names: each program file is
+ # published under that name too, byte for byte the same, with its own checksum file (tools/ci/former-names.txt).
+ - name: Copies under the former names
+ shell: pwsh
+ run: |
+ foreach ($line in Get-Content tools/ci/former-names.txt) {
+ $w = $line.Trim() -split '\s+'
+ if ($w[0] -ne 'file') { continue }
+ Copy-Item "dist/$($w[1])" "dist/$($w[2])"
+ $h = (Get-FileHash "dist/$($w[2])" -Algorithm SHA256).Hash.ToLower()
+ Set-Content -LiteralPath "dist/$($w[2]).sha256" -Value "$h $($w[2])`n" -NoNewline
+ }
Get-ChildItem dist | Format-Table Name, Length
# A signed statement that these files were built from this repository by this workflow (no certificate needed).
- # Check a download with: gh attestation verify MPCvibedRPC.exe --repo CptPakundo/MPCvibedRPC
+ # Check a download with: gh attestation verify MPRP.exe --repo CptPakundo/MPRP
+ # (the patterns take in the copies under the former names, never the .sha256 files)
- name: Attest build provenance
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
with:
subject-path: |
- dist/MPCvibedRPC.exe
- dist/MPCvibedRPC-linux-amd64
- dist/MPCvibedRPC-linux-arm64
- dist/MPCvibedRPC-macos.zip
+ dist/*.exe
+ dist/*-linux-amd64
+ dist/*-linux-arm64
+ dist/*-macos.zip
# A re-run after the release went public would turn it back into a draft and replace its files: refuse. A draft
# (or no release at all) is fine. (gh finds a release by its tag only once it is public.)
- name: The release must not be public yet
@@ -122,15 +147,17 @@ jobs:
fi
- uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with:
+ # the program files with their checksums, under the current and the former names (verify-release.ps1
+ # checks that exactly these are there)
files: |
- dist/MPCvibedRPC.exe
- dist/MPCvibedRPC.exe.sha256
- dist/MPCvibedRPC-linux-amd64
- dist/MPCvibedRPC-linux-amd64.sha256
- dist/MPCvibedRPC-linux-arm64
- dist/MPCvibedRPC-linux-arm64.sha256
- dist/MPCvibedRPC-macos.zip
- dist/MPCvibedRPC-macos.zip.sha256
+ dist/*.exe
+ dist/*.exe.sha256
+ dist/*-linux-amd64
+ dist/*-linux-amd64.sha256
+ dist/*-linux-arm64
+ dist/*-linux-arm64.sha256
+ dist/*-macos.zip
+ dist/*-macos.zip.sha256
dist/LICENSE
dist/THIRD-PARTY-NOTICES.md
body_path: ${{ runner.temp }}/release-notes.md
@@ -191,9 +218,9 @@ jobs:
- name: The rebuild matches the release
shell: bash
run: |
- ./tools/ci/reproduce.sh same MPCvibedRPC.exe '${{ needs.release.outputs.exe }}' '${{ needs.reproduce.outputs.exe }}'
- ./tools/ci/reproduce.sh same MPCvibedRPC-linux-amd64 '${{ needs.release.outputs.linux_amd64 }}' '${{ needs.reproduce.outputs.linux_amd64 }}'
- ./tools/ci/reproduce.sh same MPCvibedRPC-linux-arm64 '${{ needs.release.outputs.linux_arm64 }}' '${{ needs.reproduce.outputs.linux_arm64 }}'
+ ./tools/ci/reproduce.sh same MPRP.exe '${{ needs.release.outputs.exe }}' '${{ needs.reproduce.outputs.exe }}'
+ ./tools/ci/reproduce.sh same MPRP-linux-amd64 '${{ needs.release.outputs.linux_amd64 }}' '${{ needs.reproduce.outputs.linux_amd64 }}'
+ ./tools/ci/reproduce.sh same MPRP-linux-arm64 '${{ needs.release.outputs.linux_arm64 }}' '${{ needs.reproduce.outputs.linux_arm64 }}'
- name: Check the draft
shell: pwsh
run: ./tools/ci/verify-release.ps1 -Version $env:VERSION -Stage draft
diff --git a/AGENTS.md b/AGENTS.md
index 975c1e3..0881755 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -3,7 +3,7 @@
Guidance for any AI coding assistant working on this repository.
## What this is
-MPCvibedRPC is a small Windows tray app (Go, standard library only, one exe under 10 MB, nothing to install) that
+MPRP is a small Windows tray app (Go, standard library only, one exe under 10 MB, nothing to install) that
shows what a video player is playing as a Discord status: "Watching
" with a progress bar, cover art, episode
titles and the player's logo. It reads the players listed in the [README](README.md#-players), talks to the Discord
desktop app over its local IPC pipe, and shows its settings in a local web page. It also runs on macOS (menu bar) and
@@ -13,7 +13,7 @@ Linux. Windows is the main system and its behaviour must not change for the othe
```bash
go vet ./...
go test -count=1 ./...
-go build -trimpath -ldflags "-H=windowsgui -s -w -X main.version=X.Y.Z" -o dist/MPCvibedRPC.exe ./cmd/mpcvibedrpc
+go build -trimpath -ldflags "-H=windowsgui -s -w -X main.version=X.Y.Z" -o dist/MPRP.exe ./cmd/mprp
```
CI runs the rest (the race detector, the lint gates, macOS and Linux for real): see
[development.md > CI](docs/development.md#ci).
@@ -24,7 +24,7 @@ CI runs the rest (the race detector, the lint gates, macOS and Linux for real):
2. [docs/development.md](docs/development.md): packages, how players are read, the engine's state, testing, CI, and
the checklists for adding a player, setting, catalog or host. Before you run the program or a real player, read
[Running the program safely](docs/development.md#running-the-program-safely): a *throwaway copy* is one started
- with a data folder of its own (`MPCRPC_HOME`), so it cannot touch an installed copy.
+ with a data folder of its own (`MPRP_HOME`), so it cannot touch an installed copy.
3. [docs/maintaining.md](docs/maintaining.md): releasing, screenshots, downloading release files.
4. [docs/roadmap.md](docs/roadmap.md) before proposing a feature, a service or a distribution change (don't propose a
listed non-goal without saying so), and [docs/decisions.md](docs/decisions.md) before changing listed behaviour.
@@ -41,11 +41,11 @@ Read the named sections, make the change, then run the tests named with it (and
[Packages](docs/development.md#packages-internal); run `go test ./internal/core` (the golden data must still pass).
- **A window or UI fix:** [The window and the menu](docs/how-it-works.md#the-window-and-the-menu) and the
`internal/assets` rows in [Packages](docs/development.md#packages-internal) and the window's look in
- [design/settings-window.md](docs/design/settings-window.md); run `go test ./internal/assets ./cmd/mpcvibedrpc`
- (`TestPageScriptParses` needs Node.js).
+ [design/settings-window.md](docs/design/settings-window.md); run `go test ./internal/assets ./cmd/mprp`
+ (`TestPageScriptParses` and `TestPageBehaviour` need Node.js).
- **A new player:** [A new player](docs/development.md#a-new-player) and
- [How players are read](docs/development.md#how-players-are-read); run `go test ./internal/engine ./cmd/mpcvibedrpc`.
-- **A new setting:** [A new setting](docs/development.md#a-new-setting); run `go test ./internal/store ./cmd/mpcvibedrpc`
+ [How players are read](docs/development.md#how-players-are-read); run `go test ./internal/engine ./cmd/mprp`.
+- **A new setting:** [A new setting](docs/development.md#a-new-setting); run `go test ./internal/store ./cmd/mprp`
(`TestEverySettingIsDocumented` fails until `docs/config.md` has its row).
## Invariants: never break these
@@ -56,7 +56,8 @@ Read the named sections, make the change, then run the tests named with it (and
([decision](docs/decisions.md#behaviour)).
- **MPRIS reads only the allowlist** in `internal/mpris`: music players and browsers must never show as "Watching".
- **Readers are read-only**, and tests never use real accounts or a real setup ([ground rules](CONTRIBUTING.md#ground-rules)).
-- **The default Discord application (`clientId`) belongs to the upstream project**; every install depends on it.
+- **The default Discord application (`clientId`, `core.DefaultClientID`) is the project's own**, named MPRP; every
+ install depends on it. A saved former default (`core.FormerClientID`) reads as it: keep that carry-over.
- **Player logo addresses are fixed.** Every install fetches the logos from `docs/players/.png` on the `master`
branch (`PlayerIconBase` in `internal/core/icons.go`). Never move, rename or delete those files or rename `master`;
adding a logo is fine.
@@ -72,6 +73,6 @@ Read the named sections, make the change, then run the tests named with it (and
- The program is AI-generated; the README says so once, near the top, and that is enough. Never present the code as
written by the repository maintainer. The idea comes from angeloanan/MPC-DiscordRPC (MIT), credited in the README,
`LICENSE` and `THIRD-PARTY-NOTICES.md`.
-- Versions are `0.9.x`; the current one is in `cmd/mpcvibedrpc/main.go`. Changelog lines are short, one emoji each.
+- Versions are `0.9.x`; the current one is in `cmd/mprp/main.go`. Changelog lines are short, one emoji each.
- Merging, tagging and publishing are outward-facing: do them only with the maintainer's go-ahead
([maintaining.md](docs/maintaining.md#rules-for-maintainers)).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0af3d8f..446e0ce 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,13 +7,14 @@ and testing. Bug reports, reviews and pull requests with tests are welcome all t
1. Install [Go](https://go.dev/dl/) at the version in `go.mod` (the `go` line) and clone the repository. The default
branch is `master`.
2. Run the checks: `go vet ./...` and `go test -count=1 ./...`.
-3. Build: `go build -trimpath -ldflags "-H=windowsgui -s -w -X main.version=0.0.0" -o dist/MPCvibedRPC.exe ./cmd/mpcvibedrpc`
+3. Build: `go build -trimpath -ldflags "-H=windowsgui -s -w -X main.version=0.0.0" -o dist/MPRP.exe ./cmd/mprp`
(other systems: [development.md](docs/development.md#building-and-running)).
4. Before you start the program you built, read [Running the program safely](docs/development.md#running-the-program-safely):
- a copy with its own data folder (`MPCRPC_HOME`) leaves your installed copy, Discord and players alone.
+ a copy with its own data folder (`MPRP_HOME`) leaves your installed copy, Discord and players alone.
Optional tools:
-- **Node.js**: `TestPageScriptParses` checks the settings page's script with `node --check`; without Node.js it skips.
+- **Node.js**: `TestPageScriptParses` checks the settings page's script with `node --check`, and `TestPageBehaviour` runs it
+ in a fake page; without Node.js they skip.
- **The lint tools** CI runs, at the versions pinned in `.github/workflows/ci.yml`:
go install golang.org/x/vuln/cmd/govulncheck@v1.9.0
@@ -23,7 +24,7 @@ Optional tools:
Run them as CI does: `govulncheck ./...`, `staticcheck -checks inherit,-ST1005 ./...` and `deadcode -test ./...`.
## How to help
-- **Bugs:** use the [issue templates](https://github.com/CptPakundo/MPCvibedRPC/issues/new/choose). On the **Help** tab,
+- **Bugs:** use the [issue templates](https://github.com/CptPakundo/MPRP/issues/new/choose). On the **Help** tab,
**Copy diagnostics** gives a report to attach; what it contains is in
[Troubleshooting](docs/troubleshooting.md#reporting-a-problem). Look through it before you post it.
- **Security problems:** report them privately, as described in [SECURITY.md](SECURITY.md), not in a public issue.
@@ -102,6 +103,7 @@ Maintainers have a few more rules (outward-facing steps, release-file downloads)
## Where to find what
| You want | Read |
|---|---|
+| Every page of the documentation, by topic | [docs/README.md](docs/README.md) |
| Rules for AI coding tools | [AGENTS.md](AGENTS.md) |
| Building, running safely, the package map, how players are read, the engine, testing, CI, adding a player, setting, catalog or host | [docs/development.md](docs/development.md) |
| Releasing, screenshots, downloading release files | [docs/maintaining.md](docs/maintaining.md) |
diff --git a/README.md b/README.md
index b21e521..799c81f 100644
--- a/README.md
+++ b/README.md
@@ -2,77 +2,84 @@
-# MPCvibedRPC
+# MPRP
+
+Media Player Rich Presence (formerly MPCvibedRPC)
**Show what you're watching on Discord.**
-A tiny app for MPC-HC, MPC-BE, MPC-QT, mpv, VLC, PotPlayer, IINA, Kodi, Plex, Stremio, Jellyfin and Emby, with clean titles, cover art and a real progress bar.
+A tiny app that turns what your video player plays into a Discord status: the title, the episode, the cover and a
+progress bar that keeps up.
+
+
+MPC-HC · MPC-BE · MPC-QT · mpv · VLC · PotPlayer · IINA · Kodi · Plex · Stremio · Jellyfin · Emby
-> **Made with AI ("vibe coded").** The code, tests and documentation were written by an AI (Claude, by Anthropic) from
-> the repository maintainer's prompts and testing ([how that works](docs/ai.md)). There is no warranty (see `LICENSE`). The
-> idea and the approach come from [angeloanan/MPC-DiscordRPC](https://github.com/angeloanan/MPC-DiscordRPC); the credit for that belongs to its author.
+Made with AI: the code, tests and docs were written by Claude (Anthropic) from the maintainer's prompts and testing. [How that works](docs/ai.md).
## ✨ What you get
-- 🎬 **"Watching Sample Show"** on your profile, with the episode, its title and a progress bar that follows seeking and pausing.
+- 🎬 **"Watching Sample Show"** on your profile, with the episode, its title and a progress bar that follows seeking
+ and pausing.
- 🧹 **Clean titles** from messy file names: `Show.Name.S01E02.1080p.WEB-DL.x265-GRP.mkv` becomes *Show Name · S01E02*.
-- 🖼️ **Cover art, episode names and ratings**, looked up in several free catalogs (IMDb, TVmaze, AniList and more).
-- 📺 **Your players**: MPC-HC, MPC-BE, MPC-QT, mpv, VLC and PotPlayer on Windows; IINA, mpv, VLC and MPC-QT on macOS; VLC, mpv, Celluloid, Haruna and most other video players on Linux; Kodi on any system; and **Plex**, **Stremio**, **Jellyfin** and **Emby** on any device. Players with a logo of their own show it on Discord.
-- 🔗 **Clickable**: both text lines and the cover open the title's page (IMDb, AniList, ...), next to up to two "View on ..." buttons, and the player's logo opens its site. Or "View on Letterboxd", if you switch that on. **Hide what I'm watching** is also in the tray / menu bar menu.
-- 📡 **On your streams**: while you share your screen, Discord says "Streaming Sample Show" instead of showing a stream without a name (Windows; elsewhere it is a switch).
-- 🔒 **Private by design**: hide titles or whole folders, choose which services may see a title, or stay fully offline. No tracking.
-- 🪶 **Tiny and tidy**: one file of under 10 MB, nothing to install, updates itself on Windows and Linux (on macOS it links to the new download). While Discord is closed it waits quietly and asks no player at all.
+- 🖼️ **Cover art, episode names and ratings** from free catalogs (IMDb, TVmaze, AniList and more).
+- 🎯 **Fix a match**: a wrong title or cover is put right from the window, with a search that suggests as you type.
+ The fix sticks for every episode.
+- ✏️ **Text lines your way**: Standard, Short, Detailed, or lines of your own with placeholders such as
+ `{episodeTitle}`.
+- 🔗 **Clickable**: the lines and the cover open the title's page (IMDb, AniList, ...), next to up to two "View on ..."
+ buttons.
+- 📡 **On your streams**: while you share your screen, Discord says "Streaming Sample Show" instead of a stream
+ without a name.
+- 🔒 **Private by design**: hide titles or whole folders, choose which services may see a title, or stay fully offline.
+ No tracking.
+- 🪶 **Small and quiet**: one file under 10 MB, nothing to install, updates itself (on macOS it links to the download). While Discord is closed it
+ rests and asks no player at all.
## 🚀 Getting started
-Every system needs the **Discord desktop app** with *User Settings > Activity Privacy > "Share my activity"* turned on (Activity Privacy is in the *Games & Apps* section, called *Activity Settings* in older Discord versions).
+You need the **Discord desktop app** with *User Settings > Activity Privacy > "Share my activity"* on (under
+*Games & Apps*; *Activity Settings* in older Discord versions).
-**Windows 10/11**
-1. Download **MPCvibedRPC.exe** and run it. There is nothing to install. SmartScreen may warn, because the program
- isn't code-signed: choose *More info > Run anyway*.
+**Windows 10 and 11**
+1. Download **MPRP.exe** and run it; there is nothing to install. SmartScreen may warn, because the program isn't
+ code-signed: choose *More info > Run anyway*. Windows 11's Smart App Control can block it outright
+ ([why](docs/troubleshooting.md#is-the-download-safe)).
2. Play something. If your player isn't found yet, press **Set up the player connection** in the window.
3. Optional: **Start with Windows** (General tab) starts it quietly in the tray when you log in.
**macOS 13 or later** (Apple silicon and Intel)
-1. Download **MPCvibedRPC-macos.zip**, open it and move the app to Applications.
-2. The app isn't notarized by Apple, so the first time it won't open: go to *System Settings > Privacy & Security* and
+1. Download **MPRP-macos.zip**, open it and move the app to Applications.
+2. The app isn't notarized by Apple, so it won't open the first time: go to *System Settings > Privacy & Security* and
choose **Open Anyway**.
3. It lives in the menu bar. For IINA, press **Set up the player connection** once and reopen IINA.
**Linux** (x64 and ARM64)
-1. Download **MPCvibedRPC-linux-amd64** (or `-arm64`), run `chmod +x` on it and start it.
-2. VLC, Celluloid, Haruna and most other video players are found by themselves. mpv: press **Set up the player
+1. Download **MPRP-linux-amd64** (or `-arm64`), make it executable (`chmod +x`) and start it.
+2. VLC, Celluloid, Haruna and most other video players are found by themselves. For mpv, press **Set up the player
connection** (it adds one line to `mpv.conf`); the mpv-mpris script works too.
3. There's no tray icon, and closing the window with its X quits the program. Keep the window open or minimised, or
- let the program start at login (**General** tab), and run it again to bring the window back.
-
-**Plex** (any system): sign in on the **Players** tab. Whatever you play with your Plex account then shows up, on any device.
-
-**Stremio** (any system): sign in on the **Players** tab. What you watch with your Stremio account then shows up, on any device.
+ let it start at login (**General** tab); running it again brings the window back.
-**Jellyfin and Emby** (any system): enter your server's address and sign in on the **Players** tab.
+**Plex, Stremio, Jellyfin and Emby** (any system): sign in on the **Players** tab (for Jellyfin and Emby, enter your
+server's address first). What you play with that account then shows up, on any device.
**Kodi** (any system): in Kodi, turn on *Settings > Services > Control > Allow remote control via HTTP* with a user
-name and password; enter the password (and the address, for a Kodi on another device) under the **Players** tab.
+name and password, then enter the password (and the address, for a Kodi on another device) on the **Players** tab.
## 📺 Players
@@ -91,25 +98,46 @@ name and password; enter the password (and the address, for a Kodi on another de
| Stremio (desktop app, Stremio Web, TV, phone) | ✓ | ✓ | ✓ | sign in on the Players tab |
| Jellyfin, Emby (any app, web or TV) | ✓ | ✓ | ✓ | server address and sign in on the Players tab |
-"One click" is the **Set up the player connection** button in the window. It closes and reopens MPC-HC, MPC-BE or VLC
-after you confirm. Exactly what each player needs, and how it is read, is in
-[How it works](docs/how-it-works.md#players-in-detail).
+"One click" is the **Set up the player connection** button in the window; it closes and reopens MPC-HC, MPC-BE or VLC
+after you confirm. When several players are open, the one playing a video wins. What each player needs, and how it is
+read: [Players in detail](docs/how-it-works.md#players-in-detail).
+
+## 🔧 Settings
+
+Everything is in one window: open it from the tray icon on Windows or the menu bar on macOS; on Linux it is the app's
+own window. Settings save as you change them.
+
+| Tab | What you set there |
+|---|---|
+| General | starting with the system, showing on Discord when the app opens, updates |
+| Players | the players on this computer, and the Plex, Stremio and Jellyfin / Emby sign-ins |
+| Look | how the status reads: style, text lines, progress bar, links, streams |
+| Titles & art | episode titles, anime titles, folder names, **Fix a match** |
+| Privacy | hidden titles and files, which online services may see a title |
+| Advanced | how often players are checked, Restore defaults |
+| Help | Run a check, Copy diagnostics, the log, your stats, About |
+
+Every setting, with its default: [All settings](docs/config.md).
## 🔒 Privacy
-- The status is put together on your computer. Only Discord, the services you turn on or sign in to, and GitHub
- (the update check, which you can switch off) are contacted.
-- To find covers, the **title** (never the file path) is sent to the catalog services you allow. The **Privacy** tab has
- a switch for each one, plus one switch to stay fully offline.
-- **Hide what I'm watching** shows just "Watching a video". **Never show these files** hides folders, names or a whole Plex library completely.
-- Music played in a video player shows as "Listening to" and is never looked up in the movie and TV catalogs.
-- Your status clears itself after a long pause (30 minutes, adjustable).
-- **Your stats** (Help tab) count videos and watch time on your computer only. Nothing is ever sent anywhere: no
- analytics, no tracking. The download count above is GitHub's public count of release downloads.
-- With Plex, the program talks to plex.tv and your Plex server only while you're signed in, and only reads. The same
- goes for Stremio and Stremio's servers, and for Jellyfin / Emby and your own server.
-- [SECURITY.md](SECURITY.md) lists every address the program connects to, and how to verify a download (release files
- come with checksums and a signed build record).
+- Your status is put together on your computer. Only Discord, the services you allow or sign in to, and GitHub (the
+ update check, which you can switch off) are contacted.
+- To find a cover, only the **title** (never the file path) goes to the catalogs you allow, each with its own switch.
+ One switch keeps the program fully offline.
+- **Hide what I'm watching** shows just "Watching a video". **Never show these files** hides folders, names or a whole
+ Plex library.
+- With Plex, Stremio, Jellyfin or Emby the program only reads what you play. On Windows their sign-ins are kept
+ encrypted for your user account.
+- Your stats stay on your computer. No analytics, no tracking.
+
+Every address the program connects to, and how to check a download: [SECURITY.md](SECURITY.md).
+
+
+The Privacy tab
+
+
+
## ❓ Help
@@ -118,21 +146,27 @@ after you confirm. Exactly what each player needs, and how it is read, is in
1. The Discord desktop app (not the browser) is running.
2. "Share my activity" is turned on in Discord (where: see [Getting started](#-getting-started)).
3. Discord runs normally, not as administrator.
-4. The status line at the top of the window says what is missing, for example "No player found".
+4. The status line at the top of the window says what is missing, for example "No player found". **Help > Run a
+ check** tells you what works and what doesn't.
**Reporting a problem:** on the **Help** tab, **Copy diagnostics** copies a report to paste into a
-[new issue](https://github.com/CptPakundo/MPCvibedRPC/issues/new/choose); what it contains is in [Troubleshooting](docs/troubleshooting.md#reporting-a-problem).
+[new issue](https://github.com/CptPakundo/MPRP/issues/new/choose); what it contains is in
+[Troubleshooting](docs/troubleshooting.md#reporting-a-problem).
More problems, by player and service, plus updates and uninstalling: [Troubleshooting](docs/troubleshooting.md).
-## 📚 More
+## 📚 Documentation
-- [How it works](docs/how-it-works.md): title cleanup, cover lookups, and each player in detail.
+- [How it works](docs/how-it-works.md): what shows on Discord, title cleanup, covers, Fix a match, each player.
- [All settings](docs/config.md), with their defaults.
- [Troubleshooting](docs/troubleshooting.md): each player and service, updates, uninstalling.
-- [Security](SECURITY.md): every address the program connects to, how to verify a download, and how to report a
- security problem.
-- [Contributing](CONTRIBUTING.md): bug reports, building and testing.
-- [Development](docs/development.md): building, running it safely, testing, CI and how the code is laid out; [Maintaining](docs/maintaining.md): releasing.
-- [Roadmap](docs/roadmap.md): where the program is heading, and what it leaves out on purpose.
-- [Decisions](docs/decisions.md): why the program behaves the way it does.
+- [Security](SECURITY.md): every address the program connects to, checking a download, reporting a security problem.
+- [Contributing](CONTRIBUTING.md) and [the full docs index](docs/README.md): building, testing, the roadmap and the
+ decisions behind the program.
+
+## 🙏 Credits
+
+The idea and the approach come from [angeloanan/MPC-DiscordRPC](https://github.com/angeloanan/MPC-DiscordRPC); the
+credit for that belongs to its author. Titles, covers and episode names come from TMDB, IMDb, Cinemeta, TVmaze,
+AniList, Kitsu, Wikipedia and Bulbapedia ([notices](THIRD-PARTY-NOTICES.md)). MPRP is free software under the
+[MIT license](LICENSE), with no warranty.
diff --git a/SECURITY.md b/SECURITY.md
index 71149ba..11d45d6 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -53,8 +53,11 @@ the image host the catalog named for it (`image.tmdb.org` for TMDB), and the pla
| The player's site, from its logo on your status | `github.com` (the MPC players), `mpv.io`, `www.videolan.org`, `iina.io`, `kodi.tv`, `www.smplayer.info`, `www.plex.tv`, `www.stremio.com`, `jellyfin.org`, `emby.media` |
## What is kept, and what to know
-The Plex, Stremio, Jellyfin and Emby sign-ins are kept in `config.json` as plain text. A password you type goes to
-your own server once and is never stored. Kodi's password is kept in `config.json` as plain text too, as VLC's is.
+The Plex, Stremio, Jellyfin and Emby sign-ins are kept in `config.json`. On Windows they are encrypted with Windows'
+own per-user encryption (DPAPI): only your user account on this computer can read them, so a copied or backed-up
+`config.json` holds no usable sign-in (on another account or computer they count as signed out). On macOS and Linux
+they are plain text. A password you type goes to your own server once and is never stored. Kodi's and VLC's passwords
+and a TMDB key are kept in `config.json` as plain text on every system.
Your Plex sign-in goes only to plex.tv and to a server that has first shown, without it, that it is the server you
chose. A server shared with you gets the key plex.tv made for it, never your account's.
@@ -79,7 +82,7 @@ limits it to this computer, which keeps other devices out but not web pages you
## Reporting a problem
If you find a security problem, please report it **privately** through
-[GitHub's private vulnerability reporting](https://github.com/CptPakundo/MPCvibedRPC/security/advisories/new)
+[GitHub's private vulnerability reporting](https://github.com/CptPakundo/MPRP/security/advisories/new)
rather than in a public issue. There is no guaranteed response time or fix, but reports are read.
## How updates are checked
@@ -92,14 +95,14 @@ manifest, immutable releases) is an open decision in the
## Checking a download
Release files come with a SHA-256 checksum and a signed build record from GitHub. To check that a downloaded
-`MPCvibedRPC.exe` (or `MPCvibedRPC-macos.zip`, `MPCvibedRPC-linux-amd64`, ...) was built from this repository by its
+`MPRP.exe` (or `MPRP-macos.zip`, `MPRP-linux-amd64`, ...) was built from this repository by its
release workflow:
```
-gh attestation verify MPCvibedRPC.exe --repo CptPakundo/MPCvibedRPC --signer-workflow CptPakundo/MPCvibedRPC/.github/workflows/release.yml
+gh attestation verify MPRP.exe --repo CptPakundo/MPRP --signer-workflow CptPakundo/MPRP/.github/workflows/release.yml
```
-You can also rebuild `MPCvibedRPC.exe` and the Linux programs yourself and compare: every release is published only
+You can also rebuild `MPRP.exe` and the Linux programs yourself and compare: every release is published only
after a second runner rebuilt them from the tag byte for byte. Check out the tag with the files as committed (LF line
endings, for example `git clone -c core.autocrlf=false`), install the Go version named in
`go.mod` (the `go` line), run `tools/ci/reproduce.sh X.Y.Z out` and compare the files' SHA-256 with the
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index c93ba68..6cefe90 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -2,7 +2,7 @@
- **MPC-DiscordRPC** by Christopher Angelo - https://github.com/angeloanan/MPC-DiscordRPC - MIT License (see LICENSE).
This project started from it and keeps its copyright notice.
-- **The Go programming language and standard library** (linked into MPCvibedRPC.exe) - https://go.dev -
+- **The Go programming language and standard library** (linked into MPRP.exe) - https://go.dev -
BSD 3-Clause License, Copyright 2009 The Go Authors. Full text: https://go.dev/LICENSE
- Unicode data used for text normalisation (`internal/jsre/nfd_table.go`, `nfc_table.go`) is derived from the
Unicode Character Database - https://www.unicode.org/license.txt
diff --git a/cmd/mpcvibedrpc/window_test.go b/cmd/mpcvibedrpc/window_test.go
deleted file mode 100644
index 8f2c48e..0000000
--- a/cmd/mpcvibedrpc/window_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package main
-
-import "testing"
-
-// The settings window's going quits the program only when the user closed the program's own window.
-func TestCloseQuits(t *testing.T) {
- for _, c := range []struct {
- name string
- windows int32
- appWindow, inTray, quitting bool
- goos string
- want bool
- }{
- {"closed with its X", 0, true, false, false, "windows", true},
- {"Linux app window", 0, true, false, false, "linux", true},
- {"a window is open again (a reload)", 1, true, false, false, "windows", false},
- {"a tab of the user's browser", 0, false, false, false, "windows", false},
- {"minimised to the tray", 0, true, true, false, "windows", false},
- {"quitting already", 0, true, false, true, "windows", false},
- {"macOS closes to the menu bar", 0, true, false, false, "darwin", false},
- } {
- if got := closeQuits(c.windows, c.appWindow, c.inTray, c.quitting, c.goos); got != c.want {
- t.Errorf("%s: %v, want %v", c.name, got, c.want)
- }
- }
-}
diff --git a/cmd/mpcvibedrpc/accounts.go b/cmd/mprp/accounts.go
similarity index 96%
rename from cmd/mpcvibedrpc/accounts.go
rename to cmd/mprp/accounts.go
index fbb5dc3..90b8321 100644
--- a/cmd/mpcvibedrpc/accounts.go
+++ b/cmd/mprp/accounts.go
@@ -8,10 +8,10 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/server"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/server"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// approval is the part the Plex, Stremio and Jellyfin sign-ins share: a sign-in that waits until the user approves it
diff --git a/cmd/mpcvibedrpc/api.go b/cmd/mprp/api.go
similarity index 80%
rename from cmd/mpcvibedrpc/api.go
rename to cmd/mprp/api.go
index 7dc6aab..e777549 100644
--- a/cmd/mpcvibedrpc/api.go
+++ b/cmd/mprp/api.go
@@ -9,15 +9,15 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/assets"
- "github.com/CptPakundo/MPCvibedRPC/internal/conns"
- "github.com/CptPakundo/MPCvibedRPC/internal/diag"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/server"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/assets"
+ "github.com/CptPakundo/MPRP/internal/conns"
+ "github.com/CptPakundo/MPRP/internal/diag"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/server"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// fn adapts a handler that needs no request body and cannot fail.
@@ -38,19 +38,19 @@ func (a *app) handlers() map[string]server.Handler {
Config: eng.Config(), App: a.st.App(), Status: eng.Status(), Log: a.lg.last(100),
})}
})},
- "start": {Fn: fn(func() any { eng.Start(); return eng.Status() })},
- "stop": {Fn: fn(func() any { eng.Stop(); return eng.Status() })},
- "open": {Fn: fn(func() any { a.openWindow(); return nil })},
- "quit": {Fn: fn(func() any { time.AfterFunc(100*time.Millisecond, a.quit); return nil })},
- "open-folder": {Fn: fn(func() any { winsys.OpenFolder(a.st.Dir); return nil })},
- "clear-cache": {Fn: fn(func() any { eng.ClearArtworkCache(); log("INFO", "Cover cache cleared."); return nil })},
- "stats": {Get: true, Fn: fn(func() any { return eng.Stats() })},
- "connections": {Get: true, Fn: fn(func() any { return map[string]any{"hosts": conns.List()} })},
- "stats-reset": {Fn: fn(func() any { eng.ResetStats(); log("INFO", "Stats reset."); return eng.Stats() })},
- "save": {Fn: a.save},
- "reset": {Fn: func(*jsonx.Obj) (any, error) { return a.reset() }},
- "mpc-web": {Fn: a.setUpPlayers},
- "selfcheck": {Fn: a.selfCheck},
+ "start": {Fn: fn(func() any { eng.Start(); return eng.Status() })},
+ "stop": {Fn: fn(func() any { eng.Stop(); return eng.Status() })},
+ "open": {Fn: fn(func() any { a.openWindow(); return nil })},
+ "quit": {Fn: fn(func() any { time.AfterFunc(100*time.Millisecond, a.quit); return nil })},
+ "open-folder": {Fn: fn(func() any { winsys.OpenFolder(a.st.Dir); return nil })},
+ "clear-cache": {Fn: fn(func() any { eng.ClearArtworkCache(); log("INFO", "Cover cache cleared."); return nil })},
+ "stats": {Get: true, Fn: fn(func() any { return eng.Stats() })},
+ "connections": {Get: true, Fn: fn(func() any { return map[string]any{"hosts": conns.List()} })},
+ "stats-reset": {Fn: fn(func() any { eng.ResetStats(); log("INFO", "Stats reset."); return eng.Stats() })},
+ "save": {Fn: a.save},
+ "reset": {Fn: func(*jsonx.Obj) (any, error) { return a.reset() }},
+ "player-setup": {Fn: a.setUpPlayers},
+ "selfcheck": {Fn: a.selfCheck},
"update-check": {Fn: func(*jsonx.Obj) (any, error) {
r, err := a.checkUpdates(true)
@@ -88,6 +88,7 @@ func (a *app) handlers() map[string]server.Handler {
return a.jellyfin.signInPassword(address, strings.TrimSpace(user), password)
}},
}
+ a.matchHandlers(h)
addAccount(h, "plex", a.plex)
addAccount(h, "stremio", a.stremio)
addAccount(h, "jellyfin", a.jellyfin)
@@ -174,9 +175,9 @@ func (a *app) reset() (any, error) {
// setUpPlayers is "Set up the player connection". A player that was already set up its own way (an mpv or IINA
// connection name, VLC's password and port) is adopted into the settings.
func (a *app) setUpPlayers(body *jsonx.Obj) (any, error) {
- closeMpc, _ := body.M["closeMpc"].(bool)
+ mayClose, _ := body.M["closePlayers"].(bool)
cfg := a.eng.Config()
- r := winsys.EnableMpcWebInterface(cfg.Port, closeMpc, cfg.MpvPipe, cfg.VlcPort, cfg.VlcPassword, cfg.IinaPipe)
+ r := winsys.SetUpPlayers(cfg.Port, mayClose, cfg.MpvPipe, cfg.VlcPort, cfg.VlcPassword, cfg.IinaPipe)
take := map[string]any{}
var adopted []string
if r.MpvPipe != "" && r.MpvPipe != cfg.MpvPipe {
diff --git a/cmd/mpcvibedrpc/api_test.go b/cmd/mprp/api_test.go
similarity index 68%
rename from cmd/mpcvibedrpc/api_test.go
rename to cmd/mprp/api_test.go
index 4efe7dd..cc9c6fd 100644
--- a/cmd/mpcvibedrpc/api_test.go
+++ b/cmd/mprp/api_test.go
@@ -5,8 +5,8 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/assets"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/assets"
+ "github.com/CptPakundo/MPRP/internal/engine"
)
// Every endpoint the settings page calls exists.
@@ -37,11 +37,11 @@ func TestTrayTooltip(t *testing.T) {
s engine.Status
want string
}{
- {engine.Status{}, "MPCvibedRPC - Not showing on Discord"},
- {engine.Status{Running: true, NowPlaying: &title}, "MPCvibedRPC - Sample Show S01E02"},
- {engine.Status{Running: true, Discord: "standby"}, "MPCvibedRPC - Ready"},
- {engine.Status{Running: true, Discord: "waiting"}, "MPCvibedRPC - Waiting for Discord"},
- {engine.Status{Running: true, NowPlaying: &long}, ("MPCvibedRPC - " + long)[:62]},
+ {engine.Status{}, "MPRP - Not showing on Discord"},
+ {engine.Status{Running: true, NowPlaying: &title}, "MPRP - Sample Show S01E02"},
+ {engine.Status{Running: true, Discord: "standby"}, "MPRP - Ready"},
+ {engine.Status{Running: true, Discord: "waiting"}, "MPRP - Waiting for Discord"},
+ {engine.Status{Running: true, NowPlaying: &long}, ("MPRP - " + long)[:62]},
} {
if got := trayTooltip(c.s); got != c.want {
t.Errorf("tooltip %q, want %q", got, c.want)
diff --git a/cmd/mpcvibedrpc/app.go b/cmd/mprp/app.go
similarity index 64%
rename from cmd/mpcvibedrpc/app.go
rename to cmd/mprp/app.go
index e2b1115..99bed06 100644
--- a/cmd/mpcvibedrpc/app.go
+++ b/cmd/mprp/app.go
@@ -12,13 +12,14 @@ import (
"syscall"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/assets"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/server"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/assets"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/notify"
+ "github.com/CptPakundo/MPRP/internal/server"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// app is the running program: the settings, the engine, the local server the window talks to, and the tray.
@@ -29,6 +30,7 @@ type app struct {
log func(level, msg string)
exe string // this program, where the autostart entry and updates point
ipcFile string
+ ipcFormer string // during an update, ipc.json also goes here (formerIPC; "": nowhere else)
browserProfile string // the profile of the browser that shows the settings window
token string // the window's key to the local API (new each launch)
srv *server.Server
@@ -43,10 +45,12 @@ type app struct {
watching atomic.Bool // watchMinimise runs
opened atomic.Int64 // windows asked for so far: one asked for after a window went means it was not the X
winHandle atomic.Uintptr // the settings window as watchMinimise last found it (Windows; 0: not known)
+ winSys *windowSys // nil: the system's window functions (tests stand in for a window)
busyUntil atomic.Int64 // until then (Unix nanoseconds) no update installs itself: see settle
- mu sync.Mutex
- tray *winsys.Tray
+ mu sync.Mutex
+ tray *winsys.Tray
+ notifier *notify.Notifier // Linux: the desktop notification service (made at the first notification)
quitOnce sync.Once
quitting atomic.Bool // quit has begun: an install that fails now must not bring the server's file or the engine back
@@ -54,7 +58,13 @@ type app struct {
}
func run() error {
- st, err := store.New(store.DataDir())
+ former := store.FormerDataDir()
+ dir, other, moved := chooseDataDir(store.DataDir(), former, afterUpdate || updateFailed, pingExisting)
+ if other != nil {
+ handOver(other) // a copy of the former version runs: it is the one to show
+ return nil
+ }
+ st, err := store.New(dir)
if err != nil {
return err
}
@@ -90,11 +100,12 @@ func run() error {
}
lg := newLogger(st.LogPath())
defer lg.close()
- a := &app{st: st, lg: lg, log: lg.log, exe: exe, ipcFile: ipcFile, browserProfile: filepath.Join(st.Dir, "window"),
+ st.Log = lg.log
+ a := &app{st: st, lg: lg, log: lg.log, exe: exe, ipcFile: ipcFile, ipcFormer: formerIPC(dir, former, afterUpdate || updateFailed), browserProfile: filepath.Join(st.Dir, "window"),
token: server.NewToken(), quitDone: make(chan struct{})}
a.busy()
- msg := fmt.Sprintf("MPCvibedRPC %s starting", version)
+ msg := fmt.Sprintf("MPRP %s starting", version)
// An automatic update leaves a marker for the copy it starts: that copy starts quietly in the tray and says so once.
// A start without --after-update that finds one is a start by hand after that copy never got going: the marker is
// stale and goes, so a later update by hand is not taken for an automatic one.
@@ -110,6 +121,9 @@ func run() error {
msg += " in the background"
}
a.log("INFO", msg+".")
+ if moved != "" {
+ a.log("INFO", moved)
+ }
failedUpdate := ""
if updateFailed {
if failedUpdate = failedVersion(st.Dir); failedUpdate != "" {
@@ -127,23 +141,16 @@ func run() error {
} else {
updater.CleanupOld(exe)
}
- if !firstRun && !st.App().WelcomeSeen {
- // an install that existed before the welcome card was added has no need of it
- if p, err := jsonx.Parse(`{"app":{"welcomeSeen":true}}`); err == nil {
- _ = st.Update(p.(*jsonx.Obj))
- }
- }
winsys.CloseWindowBrowser(a.browserProfile) // a window browser left behind by a crash
+ a.writeEarly(firstRun)
a.eng = engine.New(st.Config(), engine.Options{Log: a.log, CacheFile: st.CachePath(), Version: version, StatsFile: st.StatsPath(),
MayRest: func() bool { return a.windows.Load() == 0 }, OnRest: winsys.TrimMemory})
a.plex = &plexAccount{st: st, eng: a.eng, log: a.log}
- // renews a 7-day Plex token (plexJwt) in time; nothing otherwise
- engine.Go(a.log, "The Plex sign-in renewal", func() { a.plex.keepFresh(context.Background(), 0) })
a.stremio = &stremioAccount{st: st, eng: a.eng, log: a.log}
a.jellyfin = &jellyfinAccount{st: st, eng: a.eng, log: a.log}
- a.srv = server.New(server.Options{Token: a.token, Page: assets.UI, CSS: assets.CSS, JS: assets.JS, Icon: assets.Icon, Handlers: a.handlers(), Version: version,
+ a.srv = server.New(server.Options{Token: a.token, Page: assets.UI, CSS: assets.CSS, JS: assets.JS, Icon: assets.Icon, IconPNG: logoPNG(), Handlers: a.handlers(), Version: version,
OnWindow: func(open bool) {
if open {
a.windowOpened()
@@ -155,26 +162,35 @@ func run() error {
if err != nil {
return err
}
- a.writeIPC(port)
+ a.announce(port, firstRun)
a.log("INFO", fmt.Sprintf("Settings available at http://127.0.0.1:%d/", port))
+ // renews a 7-day Plex token (plexJwt) in time; nothing otherwise (it saves the new token: so only once this copy
+ // has shown that it runs, see announce)
+ engine.Go(a.log, "The Plex sign-in renewal", func() { a.plex.keepFresh(context.Background(), 0) })
t := a.startTray()
a.mu.Lock()
a.tray = t
a.mu.Unlock()
- if failedUpdate != "" && t != nil {
- t.Balloon("MPCvibedRPC could not update to "+failedUpdate, "The new version did not start, so "+version+" is back.")
+ if failedUpdate != "" {
+ a.notify("MPRP could not update to "+failedUpdate, "The new version did not start, so "+version+" is back.")
}
- if autoFrom != "" && t != nil {
- if !t.Balloon("MPCvibedRPC updated to "+version, "Installed by itself (you had "+autoFrom+"). Click here to see what's new.") {
- a.log("INFO", "No notice of the automatic update was shown (no tray notifications here).")
+ if autoFrom != "" {
+ if !a.notify("MPRP updated to "+version, "Installed by itself (you had "+autoFrom+"). Click here to see what's new.") {
+ a.log("INFO", "No notice of the automatic update was shown (no notifications here).")
}
}
// The registry is the source of truth for "start with Windows"; keep its path pointing at this copy of the program.
- if st.App().AutoStart {
- engine.Go(a.log, "The run-at-login entry", func() { winsys.RefreshAutoStart(exe) })
- }
+ // An entry of the program's former name is carried over first (it does nothing when there is none).
+ engine.Go(a.log, "The run-at-login entry", func() {
+ if note := winsys.MigrateAutoStart(exe); note != "" {
+ a.log("INFO", note)
+ }
+ if st.App().AutoStart {
+ winsys.RefreshAutoStart(exe)
+ }
+ })
if st.App().StartPresence {
a.eng.Start()
}
@@ -204,13 +220,70 @@ func (a *app) getTray() *winsys.Tray {
return a.tray
}
+// The start's own changes to config.json (startWrites) are made before this copy announces itself (writeIPC), except
+// after an update: every write encrypts the sign-ins (on Windows), and if this copy does not show in time that it runs,
+// the version before is put back and starts again on the same file, and may not read them (a version from before the
+// encryption would take the encrypted text for its tokens). So after an update nothing is written until then.
+func (a *app) writeEarly(firstRun bool) {
+ if !afterUpdate {
+ a.startWrites(firstRun)
+ }
+}
+
+// announce writes ipc.json, which shows that this copy runs, then makes the writes that waited for it (writeEarly).
+func (a *app) announce(port int, firstRun bool) {
+ a.writeIPC(port)
+ if afterUpdate {
+ a.startWrites(firstRun)
+ }
+}
+
+// startWrites are the changes the start makes to config.json: the welcome card marked as seen for an install from
+// before it, and the old Fix a match lines written as fixes. With the engine running already (after an update) it is
+// given the fixes.
+func (a *app) startWrites(firstRun bool) {
+ st := a.st
+ if !firstRun && !st.App().WelcomeSeen {
+ // an install that existed before the welcome card was added has no need of it
+ if p, err := jsonx.Parse(`{"app":{"welcomeSeen":true}}`); err == nil {
+ _ = st.Update(p.(*jsonx.Obj))
+ }
+ }
+ if n, wrote, err := st.MigrateMatchFixes(); err != nil {
+ a.log("WARN", "Could not save the Fix a match lines as fixes ("+err.Error()+"); they still act as before.")
+ } else if wrote {
+ a.log("INFO", fmt.Sprintf("Fix a match: the artworkAliases and artworkOverrides lines became fixes (titles: %d). The old lines stay in the settings file.", n))
+ // the engine (running already after an update) drops the old lines, also when none of them could be kept
+ if a.eng != nil {
+ applySettings(st, a.eng)
+ }
+ }
+}
+
func (a *app) writeIPC(port int) {
b, _ := json.Marshal(ipcInfo{Port: port, Token: a.token, Pid: os.Getpid()})
- // in one step: a second start that reads the file meanwhile must not find half of it and take it for "none running"
- tmp := a.ipcFile + ".tmp"
- if os.WriteFile(tmp, b, 0o600) != nil || os.Rename(tmp, a.ipcFile) != nil {
- _ = os.Remove(tmp)
- _ = os.WriteFile(a.ipcFile, b, 0o600)
+ for _, f := range a.ipcFiles() {
+ // in one step: a second start that reads the file meanwhile must not find half of it and take it for "none running"
+ tmp := f + ".tmp"
+ if os.WriteFile(tmp, b, 0o600) != nil || os.Rename(tmp, f) != nil {
+ _ = os.Remove(tmp)
+ _ = os.WriteFile(f, b, 0o600)
+ }
+ }
+}
+
+// ipcFiles are the places of ipc.json: the data folder's, and during an update maybe a second one (formerIPC).
+func (a *app) ipcFiles() []string {
+ if a.ipcFormer != "" {
+ return []string{a.ipcFile, a.ipcFormer}
+ }
+ return []string{a.ipcFile}
+}
+
+// removeIPCFiles deletes ipc.json from every place writeIPC wrote it.
+func (a *app) removeIPCFiles() {
+ for _, f := range a.ipcFiles() {
+ _ = removeIPC(f)
}
}
@@ -245,8 +318,9 @@ func (a *app) openWindow() {
mode := winsys.OpenWindow(windowURL(a.srv.Port(), a.srv.NewCode()), a.browserProfile)
a.appWindow.Store(mode == "app")
if mode == "app" {
- // the window is a browser's: its taskbar button gets the program's name, icon and command (Windows)
- engine.Go(a.log, "Naming the window", func() { winsys.NameWindow(a.browserProfile) })
+ // the window is a browser's: its taskbar button gets the program's name, icon and command (Windows), whenever
+ // it appears and for as long as the program runs
+ engine.Go(a.log, "Naming the window", func() { winsys.NameWindow(a.browserProfile, a.log) })
}
}
@@ -257,13 +331,15 @@ func (a *app) quit() {
go func() {
a.srv.Close() // ends the page's keep-alive connection, so an open window closes right away
// the port and token are gone with the server: a new copy must not find them while this one winds down
- _ = removeIPC(a.ipcFile)
+ a.removeIPCFiles()
+ winsys.StopWindowIcon()
winsys.CloseWindowBrowser(a.browserProfile) // and no browser is left running for it
a.plex.stopWaiting()
a.stremio.stopWaiting()
a.jellyfin.stopWaiting()
a.eng.Stop()
a.getTray().Close()
+ a.getNotifier().Close()
a.log("INFO", "Quit.")
close(a.quitDone)
}()
diff --git a/cmd/mpcvibedrpc/changelog_test.go b/cmd/mprp/changelog_test.go
similarity index 91%
rename from cmd/mpcvibedrpc/changelog_test.go
rename to cmd/mprp/changelog_test.go
index 5b45a96..9ef9b1f 100644
--- a/cmd/mpcvibedrpc/changelog_test.go
+++ b/cmd/mprp/changelog_test.go
@@ -6,8 +6,8 @@ import (
"testing"
"unicode/utf8"
- "github.com/CptPakundo/MPCvibedRPC/internal/assets"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/assets"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
// The changelog's newest entry is this version (a release cannot ship without one), the entries run newest first,
diff --git a/cmd/mpcvibedrpc/e2e_rollback_test.go b/cmd/mprp/e2e_rollback_test.go
similarity index 84%
rename from cmd/mpcvibedrpc/e2e_rollback_test.go
rename to cmd/mprp/e2e_rollback_test.go
index d89878b..7160bba 100644
--- a/cmd/mpcvibedrpc/e2e_rollback_test.go
+++ b/cmd/mprp/e2e_rollback_test.go
@@ -55,12 +55,12 @@ func TestEndToEndUpdateRollback(t *testing.T) {
rel = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/releases/latest"):
- fmt.Fprintf(w, `{"tag_name":"v3.0.1","body":"notes","html_url":"x","assets":[{"name":"MPCvibedRPC-linux-amd64","browser_download_url":"%[1]s/dl"},{"name":"MPCvibedRPC-linux-amd64.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPCvibedRPC-linux-arm64","browser_download_url":"%[1]s/dl"},{"name":"MPCvibedRPC-linux-arm64.sha256","browser_download_url":"%[1]s/sha"}]}`, rel.URL)
+ fmt.Fprintf(w, `{"tag_name":"v3.0.1","body":"notes","html_url":"x","assets":[{"name":"MPRP-linux-amd64","browser_download_url":"%[1]s/dl"},{"name":"MPRP-linux-amd64.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPRP-linux-arm64","browser_download_url":"%[1]s/dl"},{"name":"MPRP-linux-arm64.sha256","browser_download_url":"%[1]s/sha"}]}`, rel.URL)
case r.URL.Path == "/dl":
w.Write(newBytes)
case r.URL.Path == "/sha":
sum := sha256.Sum256(newBytes)
- fmt.Fprintf(w, "%x MPCvibedRPC\n", sum)
+ fmt.Fprintf(w, "%x MPRP\n", sum)
}
}))
defer rel.Close()
@@ -69,7 +69,8 @@ func TestEndToEndUpdateRollback(t *testing.T) {
os.MkdirAll(home, 0o755)
// nothing is asked and nothing is shown: only the update is under test
os.WriteFile(filepath.Join(home, "config.json"), []byte(`{"port":1,"showArtwork":false,"mpris":false,"app":{"startPresence":false,"checkUpdates":false,"autoUpdate":false,"welcomeSeen":true}}`), 0o644)
- env := append(os.Environ(), "MPCRPC_HOME="+home, "XDG_RUNTIME_DIR="+filepath.Join(dir, "run"), "MPCRPC_UPDATE_API="+rel.URL, "DISPLAY=", "PATH=/nonexistent", "MPCRPC_BROWSER=none", "MPCRPC_FOREGROUND=1")
+ // no session bus (XDG_RUNTIME_DIR holds none): the program must not reach the real one, its players or its notifications
+ env := append(os.Environ(), "MPRP_HOME="+home, "XDG_RUNTIME_DIR="+filepath.Join(dir, "run"), "MPRP_UPDATE_API="+rel.URL, "DISPLAY=", "DBUS_SESSION_BUS_ADDRESS=", "PATH=/nonexistent", "MPRP_BROWSER=none", "MPRP_FOREGROUND=1")
cmd := exec.Command(exe, "--background")
cmd.Env = env
var out bytes.Buffer
@@ -120,7 +121,7 @@ func TestEndToEndUpdateRollback(t *testing.T) {
if v, _ := os.ReadFile(filepath.Join(home, failedMarker)); strings.TrimSpace(string(v)) != "3.0.1" {
t.Errorf("the failed version was not remembered: %q", v)
}
- logText, _ := os.ReadFile(filepath.Join(home, "mpcvibedrpc.log"))
+ logText, _ := os.ReadFile(filepath.Join(home, "mprp.log"))
for _, want := range []string{"The new version 3.0.1 did not start", "The update to 3.0.1 did not start, so 3.0.0 is back"} {
if !strings.Contains(string(logText), want) {
t.Errorf("the log lacks %q:\n%s", want, logText)
diff --git a/cmd/mpcvibedrpc/e2e_test.go b/cmd/mprp/e2e_test.go
similarity index 92%
rename from cmd/mpcvibedrpc/e2e_test.go
rename to cmd/mprp/e2e_test.go
index 0cc349f..93ac25e 100644
--- a/cmd/mpcvibedrpc/e2e_test.go
+++ b/cmd/mprp/e2e_test.go
@@ -179,12 +179,12 @@ func TestEndToEnd(t *testing.T) {
rel = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/releases/latest"):
- fmt.Fprintf(w, `{"tag_name":"v3.0.1","body":"notes","html_url":"x","assets":[{"name":"MPCvibedRPC.exe","browser_download_url":"%[1]s/dl"},{"name":"MPCvibedRPC.exe.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPCvibedRPC-linux-amd64","browser_download_url":"%[1]s/dl"},{"name":"MPCvibedRPC-linux-amd64.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPCvibedRPC-linux-arm64","browser_download_url":"%[1]s/dl"},{"name":"MPCvibedRPC-linux-arm64.sha256","browser_download_url":"%[1]s/sha"}]}`, rel.URL)
+ fmt.Fprintf(w, `{"tag_name":"v3.0.1","body":"notes","html_url":"x","assets":[{"name":"MPRP.exe","browser_download_url":"%[1]s/dl"},{"name":"MPRP.exe.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPRP-linux-amd64","browser_download_url":"%[1]s/dl"},{"name":"MPRP-linux-amd64.sha256","browser_download_url":"%[1]s/sha"},{"name":"MPRP-linux-arm64","browser_download_url":"%[1]s/dl"},{"name":"MPRP-linux-arm64.sha256","browser_download_url":"%[1]s/sha"}]}`, rel.URL)
case r.URL.Path == "/dl":
w.Write(newBytes)
case r.URL.Path == "/sha": // the program only installs a release with a checksum file
sum := sha256.Sum256(newBytes)
- fmt.Fprintf(w, "%x MPCvibedRPC\n", sum)
+ fmt.Fprintf(w, "%x MPRP\n", sum)
}
}))
defer rel.Close()
@@ -194,7 +194,8 @@ func TestEndToEnd(t *testing.T) {
cfg := fmt.Sprintf(`{"port":%d,"pollInterval":250,"showArtwork":false,"clientId":"1","app":{"autoUpdate":false}}`, mpcPort)
os.WriteFile(filepath.Join(home, "config.json"), []byte(cfg), 0o644)
- env := append(os.Environ(), "MPCRPC_HOME="+home, "XDG_RUNTIME_DIR="+xdg, "MPCRPC_UPDATE_API="+rel.URL, "DISPLAY=", "PATH=/nonexistent", "MPCRPC_BROWSER=none", "MPCRPC_FOREGROUND=1")
+ // no session bus (XDG_RUNTIME_DIR holds none): the program must not reach the real one, its players or its notifications
+ env := append(os.Environ(), "MPRP_HOME="+home, "XDG_RUNTIME_DIR="+xdg, "MPRP_UPDATE_API="+rel.URL, "DISPLAY=", "DBUS_SESSION_BUS_ADDRESS=", "PATH=/nonexistent", "MPRP_BROWSER=none", "MPRP_FOREGROUND=1")
cmd := exec.Command(exe, "--background")
cmd.Env = env
var out bytes.Buffer
@@ -270,7 +271,7 @@ func TestEndToEnd(t *testing.T) {
}
if code, dg := a.call(t, "GET", "diagnostics", ""); code != 200 {
t.Fatalf("diagnostics: %d", code)
- } else if text, _ := dg["text"].(string); !strings.Contains(text, "MPCvibedRPC diagnostics") || !strings.Contains(text, "pollInterval = 2000") ||
+ } else if text, _ := dg["text"].(string); !strings.Contains(text, "MPRP diagnostics") || !strings.Contains(text, "pollInterval = 2000") ||
!strings.Contains(text, `"Sample.Movie.2001.1080p.mkv"`) || strings.Contains(text, "/movies/") || strings.Contains(text, home) {
// the file name is kept (a wrong title is traced back to it); its folder path and the data folder are not
t.Fatalf("diagnostics text is wrong or leaks: %s", text)
diff --git a/cmd/mprp/fixes.go b/cmd/mprp/fixes.go
new file mode 100644
index 0000000..b8825f4
--- /dev/null
+++ b/cmd/mprp/fixes.go
@@ -0,0 +1,137 @@
+package main
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/server"
+)
+
+// The window's Fix this match dialog: its search as you type, the other catalogs' covers, and the text of "Tell the
+// project about this". Each answer carries the request number n the window sent, so the window can drop an answer
+// to an older keystroke.
+
+func (a *app) matchHandlers(h map[string]server.Handler) {
+ h["match-search"] = server.Handler{Fn: func(body *jsonx.Obj) (any, error) {
+ q, _ := body.M["q"].(string)
+ list, catalogs, err := a.eng.MatchSearch(q)
+ out := map[string]any{"n": body.M["n"], "results": list, "catalogs": catalogs}
+ if list == nil {
+ out["results"] = []any{}
+ }
+ if catalogs == nil {
+ out["catalogs"] = []string{}
+ }
+ if err != nil {
+ out["error"] = "A catalog did not answer (" + err.Error() + ")."
+ }
+ return out, nil
+ }}
+ h["match-covers"] = server.Handler{Fn: func(body *jsonx.Obj) (any, error) {
+ name, _ := body.M["name"].(string)
+ kind, _ := body.M["kind"].(string)
+ except, _ := body.M["catalog"].(string)
+ year := 0
+ if f, ok := body.M["year"].(float64); ok {
+ year = int(f)
+ }
+ covers := a.eng.MatchCovers(name, year, kind, except)
+ out := map[string]any{"n": body.M["n"], "covers": covers}
+ if covers == nil {
+ out["covers"] = []any{}
+ }
+ return out, nil
+ }}
+ h["match-report"] = server.Handler{Fn: func(body *jsonx.Obj) (any, error) {
+ return map[string]any{"text": fixReport(body, a.eng.Config(), version)}, nil
+ }}
+}
+
+// fixReport is the text of "Tell the project about this": the file's name (never its folder), what it was read as,
+// what it matched by itself, the fix, the catalogs that are on and the version. The window shows it to be looked over
+// and posted by the user; the program sends nothing.
+func fixReport(body *jsonx.Obj, cfg core.Config, version string) string {
+ text := func(o *jsonx.Obj, k string) string {
+ if o == nil {
+ return ""
+ }
+ s, _ := o.M[k].(string)
+ return strings.Join(strings.FieldsFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }), " ")
+ }
+ num := func(k string) int {
+ f, _ := body.M[k].(float64)
+ return int(f)
+ }
+ fx, _ := body.M["fix"].(*jsonx.Obj)
+ var lines []string
+ file := text(body, "file")
+ if i := strings.LastIndexAny(file, `/\`); i >= 0 {
+ file = file[i+1:] // a name only, never a folder
+ }
+ if file == "" {
+ file = "(none: the fix was made for a title that was not playing)"
+ }
+ lines = append(lines, "File name: "+file)
+ read := text(body, "title")
+ if read == "" {
+ read = text(fx, "match")
+ }
+ if s := num("season"); s > 0 {
+ read += ", season " + strconv.Itoa(s)
+ }
+ if e := num("episode"); e > 0 {
+ read += ", episode " + strconv.Itoa(e)
+ }
+ lines = append(lines, "Read as: "+read)
+ before := text(body, "before")
+ if before == "" {
+ before = "nothing"
+ }
+ lines = append(lines, "Matched by itself: "+before)
+ var what []string
+ switch {
+ case text(fx, "entry") != "":
+ what = append(what, strings.TrimSpace(text(fx, "label")+" ("+text(fx, "entry")+")"))
+ case text(fx, "search") != "":
+ what = append(what, `searched as "`+text(fx, "search")+`"`)
+ }
+ if text(fx, "cover") != "" {
+ what = append(what, "their own cover image")
+ }
+ so, eo := 0, 0
+ if fx != nil {
+ f1, _ := fx.M["seasonOffset"].(float64)
+ f2, _ := fx.M["episodeOffset"].(float64)
+ so, eo = int(f1), int(f2)
+ }
+ if o := core.OffsetText(so, eo); o != "" {
+ what = append(what, o)
+ }
+ if onlyFile := fx != nil && fx.M["file"] == true; onlyFile {
+ what = append(what, "for this file only")
+ } else {
+ what = append(what, `for every file read as "`+text(fx, "match")+`"`)
+ }
+ lines = append(lines, "The fix: "+strings.Join(what, "; "))
+ var on []string
+ if cfg.ShowArtwork {
+ for _, s := range core.Sources {
+ if !cfg.SourceOn(s.ID) || s.ID == "jikan" || s.ID == "bulbapedia" {
+ continue
+ }
+ l := s.Label
+ if s.ID == "tmdb" && cfg.TmdbAPIKey == "" {
+ l += " (no key)"
+ }
+ on = append(on, l)
+ }
+ }
+ if len(on) == 0 {
+ on = []string{"none"}
+ }
+ lines = append(lines, "Catalogs on: "+strings.Join(on, ", "))
+ lines = append(lines, "Version: "+version)
+ return strings.Join(lines, "\n")
+}
diff --git a/cmd/mprp/fixes_test.go b/cmd/mprp/fixes_test.go
new file mode 100644
index 0000000..1c0ccc5
--- /dev/null
+++ b/cmd/mprp/fixes_test.go
@@ -0,0 +1,132 @@
+package main
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+)
+
+// catalogStub answers every catalog request: IMDb's suggestions list one show, the others nothing.
+type catalogStub struct {
+ mu sync.Mutex // the lookups ask several catalogs at once
+ hosts []string
+}
+
+// asked is a copy of the hosts asked so far.
+func (c *catalogStub) asked() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]string(nil), c.hosts...)
+}
+
+func (c *catalogStub) RoundTrip(req *http.Request) (*http.Response, error) {
+ c.mu.Lock()
+ c.hosts = append(c.hosts, req.URL.Host)
+ c.mu.Unlock()
+ body := `{}`
+ if strings.Contains(req.URL.Path, "/suggestion/") {
+ body = `{"d":[{"id":"tt0000003","l":"Sample Show","y":2019,"qid":"tvSeries"}]}`
+ }
+ return &http.Response{StatusCode: 200, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+}
+
+func parseObj(t *testing.T, s string) *jsonx.Obj {
+ t.Helper()
+ v, err := jsonx.Parse(s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v.(*jsonx.Obj)
+}
+
+// The dialog's endpoints answer with the request number they were sent, so the window can drop an older answer.
+func TestMatchEndpoints(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.RequestGapMs = map[string]int{}
+ stub := &catalogStub{}
+ a := &app{eng: engine.New(cfg, engine.Options{HTTPClient: &http.Client{Transport: stub}, Log: func(string, string) {}})}
+ h := a.handlers()
+ out, err := h["match-search"].Fn(parseObj(t, `{"q":"Sample Show","n":7}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := out.(map[string]any)
+ if m["n"] != float64(7) || len(m["catalogs"].([]string)) == 0 {
+ t.Errorf("answer: %+v", m)
+ }
+ if s := jsonx.Stringify(toAny(t, m["results"]), 0); !strings.Contains(s, `"entry":"https://www.imdb.com/title/tt0000003/"`) {
+ t.Errorf("results: %s", s)
+ }
+ out, _ = h["match-covers"].Fn(parseObj(t, `{"name":"Sample Show","year":2019,"kind":"series","catalog":"IMDb","n":3}`))
+ if m := out.(map[string]any); m["n"] != float64(3) || m["covers"] == nil {
+ t.Errorf("covers: %+v", m)
+ }
+ for _, host := range stub.asked() {
+ if core.IsSourceID(host) || !strings.Contains(host, ".") {
+ t.Errorf("odd host %q", host)
+ }
+ }
+
+ // every catalog off: no request, and the window is told so by an empty list of catalogs
+ cfg.ShowArtwork = false
+ stub2 := &catalogStub{}
+ a2 := &app{eng: engine.New(cfg, engine.Options{HTTPClient: &http.Client{Transport: stub2}})}
+ out, _ = a2.handlers()["match-search"].Fn(parseObj(t, `{"q":"Sample Show","n":1}`))
+ if m := out.(map[string]any); len(m["catalogs"].([]string)) != 0 || len(stub2.asked()) != 0 {
+ t.Errorf("with lookups off: %+v, %v", m, stub2.asked())
+ }
+}
+
+func toAny(t *testing.T, v any) any {
+ t.Helper()
+ b := jsonMarshal(t, v)
+ p, err := jsonx.Parse(b)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// The report holds the file's name but never its folder, what it was read as and matched, the fix, the catalogs on
+// and the version.
+func TestFixReport(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.DisabledSources = []string{"wikipedia"}
+ body := parseObj(t, `{"file":"D:\\Videos\\Sample Show\\sample.show.s01e02.1080p.mkv","title":"Sample Show","season":1,"episode":2,"before":"The Sample Show (1998)",
+ "fix":{"match":"Sample Show","entry":"https://www.imdb.com/title/tt0000003/","label":"Sample Show (2019) · Show · IMDb","episodeOffset":12}}`)
+ got := fixReport(body, cfg, "0.0.0")
+ want := strings.Join([]string{
+ "File name: sample.show.s01e02.1080p.mkv",
+ "Read as: Sample Show, season 1, episode 2",
+ "Matched by itself: The Sample Show (1998)",
+ `The fix: Sample Show (2019) · Show · IMDb (https://www.imdb.com/title/tt0000003/); episodes +12; for every file read as "Sample Show"`,
+ "Catalogs on: TMDB (no key), IMDb, Cinemeta, TVmaze, AniList, Kitsu",
+ "Version: 0.0.0",
+ }, "\n")
+ if got != want {
+ t.Errorf("report:\n%s\nwant\n%s", got, want)
+ }
+ if strings.Contains(got, "Videos") || strings.Contains(got, `\`) {
+ t.Error("the report holds a folder")
+ }
+ got = fixReport(parseObj(t, `{"fix":{"match":"sample.movie.mkv","file":true,"search":"Sample Film","cover":"https://img.example/a.jpg"}}`), cfg, "0.0.0")
+ if !strings.Contains(got, "File name: (none") || !strings.Contains(got, `The fix: searched as "Sample Film"; their own cover image; for this file only`) {
+ t.Errorf("a fix made by hand:\n%s", got)
+ }
+}
+
+func jsonMarshal(t *testing.T, v any) string {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
diff --git a/cmd/mpcvibedrpc/handover_test.go b/cmd/mprp/handover_test.go
similarity index 92%
rename from cmd/mpcvibedrpc/handover_test.go
rename to cmd/mprp/handover_test.go
index 0728454..ae20816 100644
--- a/cmd/mpcvibedrpc/handover_test.go
+++ b/cmd/mprp/handover_test.go
@@ -10,22 +10,22 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
-// TestCopyStandIn is not a test of its own: started with MPCRPC_TEST_COPY set, the test program plays a new copy of
+// TestCopyStandIn is not a test of its own: started with MPRP_TEST_COPY set, the test program plays a new copy of
// the program after an update. "up" writes ipc.json as a copy that came up does, "exit" ends at once, "hang" neither
// ends nor comes up.
func TestCopyStandIn(t *testing.T) {
- switch os.Getenv("MPCRPC_TEST_COPY") {
+ switch os.Getenv("MPRP_TEST_COPY") {
case "exit":
os.Exit(3)
case "hang":
time.Sleep(time.Minute)
os.Exit(0)
case "up":
- os.WriteFile(os.Getenv("MPCRPC_TEST_IPC"), []byte(fmt.Sprintf(`{"port":1,"token":"x","pid":%d}`, os.Getpid())), 0o600)
+ os.WriteFile(os.Getenv("MPRP_TEST_IPC"), []byte(fmt.Sprintf(`{"port":1,"token":"x","pid":%d}`, os.Getpid())), 0o600)
time.Sleep(time.Minute)
os.Exit(0)
}
@@ -35,7 +35,7 @@ func TestCopyStandIn(t *testing.T) {
func standIn(t *testing.T, mode, ipcFile string) *os.Process {
t.Helper()
c := exec.Command(os.Args[0], "-test.run=^TestCopyStandIn$")
- c.Env = append(os.Environ(), "MPCRPC_TEST_COPY="+mode, "MPCRPC_TEST_IPC="+ipcFile)
+ c.Env = append(os.Environ(), "MPRP_TEST_COPY="+mode, "MPRP_TEST_IPC="+ipcFile)
if err := c.Start(); err != nil {
t.Fatal(err)
}
diff --git a/cmd/mpcvibedrpc/hide_test.go b/cmd/mprp/hide_test.go
similarity index 93%
rename from cmd/mpcvibedrpc/hide_test.go
rename to cmd/mprp/hide_test.go
index 2026d59..a506eb6 100644
--- a/cmd/mpcvibedrpc/hide_test.go
+++ b/cmd/mprp/hide_test.go
@@ -5,9 +5,9 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/capture"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/capture"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// "Hide what I'm watching" from the tray or the menu bar is saved like the switch in the window and reaches the engine.
diff --git a/cmd/mpcvibedrpc/ipc_test.go b/cmd/mprp/ipc_test.go
similarity index 100%
rename from cmd/mpcvibedrpc/ipc_test.go
rename to cmd/mprp/ipc_test.go
diff --git a/cmd/mpcvibedrpc/ipc_windows_test.go b/cmd/mprp/ipc_windows_test.go
similarity index 100%
rename from cmd/mpcvibedrpc/ipc_windows_test.go
rename to cmd/mprp/ipc_windows_test.go
diff --git a/cmd/mpcvibedrpc/jellyfin.go b/cmd/mprp/jellyfin.go
similarity index 98%
rename from cmd/mpcvibedrpc/jellyfin.go
rename to cmd/mprp/jellyfin.go
index 444de0b..c308a4f 100644
--- a/cmd/mpcvibedrpc/jellyfin.go
+++ b/cmd/mprp/jellyfin.go
@@ -6,9 +6,9 @@ import (
"fmt"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/jellyfin"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jellyfin"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// jellyfinSignIn are the settings the Jellyfin / Emby sign-in writes and a sign-out forgets; jellyfinDevice, this
diff --git a/cmd/mpcvibedrpc/jellyfin_test.go b/cmd/mprp/jellyfin_test.go
similarity index 98%
rename from cmd/mpcvibedrpc/jellyfin_test.go
rename to cmd/mprp/jellyfin_test.go
index 4ea35a1..ae15f87 100644
--- a/cmd/mpcvibedrpc/jellyfin_test.go
+++ b/cmd/mprp/jellyfin_test.go
@@ -10,8 +10,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// fakeJellyfinServer is a Jellyfin server (Emby: under /emby, no Quick Connect) for the sign-in. Quick Connect is
diff --git a/cmd/mpcvibedrpc/launch_darwin.go b/cmd/mprp/launch_darwin.go
similarity index 84%
rename from cmd/mpcvibedrpc/launch_darwin.go
rename to cmd/mprp/launch_darwin.go
index 9a92c62..c258917 100644
--- a/cmd/mpcvibedrpc/launch_darwin.go
+++ b/cmd/mprp/launch_darwin.go
@@ -7,7 +7,7 @@ import (
"os/exec"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/proc"
+ "github.com/CptPakundo/MPRP/internal/proc"
)
// prepareSystem gives a copy started at login the user's temporary folder: launchd starts programs without TMPDIR,
@@ -27,9 +27,9 @@ func prepareSystem() {
// Dock, the program is "running" for macOS for as long as this process lives, and opening it again would only bring
// it to the front (which a program without windows of its own ignores). So this process hands over to a detached copy
// and leaves; opening the app again starts a new short-lived copy, which finds the running one and asks it for its
-// window. Started at login (--background) or with MPCRPC_FOREGROUND set, the program simply runs.
+// window. Started at login (--background) or with MPRP_FOREGROUND set, the program simply runs.
func detach() bool {
- if background || serve || afterUpdate || os.Getenv("MPCRPC_FOREGROUND") != "" {
+ if background || serve || afterUpdate || os.Getenv("MPRP_FOREGROUND") != "" {
return false
}
exe, err := os.Executable()
diff --git a/cmd/mpcvibedrpc/launch_other.go b/cmd/mprp/launch_other.go
similarity index 100%
rename from cmd/mpcvibedrpc/launch_other.go
rename to cmd/mprp/launch_other.go
diff --git a/cmd/mpcvibedrpc/logger.go b/cmd/mprp/logger.go
similarity index 100%
rename from cmd/mpcvibedrpc/logger.go
rename to cmd/mprp/logger.go
diff --git a/cmd/mpcvibedrpc/logger_test.go b/cmd/mprp/logger_test.go
similarity index 100%
rename from cmd/mpcvibedrpc/logger_test.go
rename to cmd/mprp/logger_test.go
diff --git a/cmd/mprp/logopng.go b/cmd/mprp/logopng.go
new file mode 100644
index 0000000..fceeec8
--- /dev/null
+++ b/cmd/mprp/logopng.go
@@ -0,0 +1,18 @@
+package main
+
+import (
+ "bytes"
+ "image/png"
+
+ "github.com/CptPakundo/MPRP/internal/logo"
+)
+
+// logoPNG is the logo as a 256 px PNG for the settings page's icon (/icon.png). The browser shows the page's icon on
+// the window's taskbar button, and the .ico it would otherwise take holds only small sizes, which look blurry there.
+func logoPNG() []byte {
+ var b bytes.Buffer
+ if png.Encode(&b, logo.Image(256, false)) != nil {
+ return nil
+ }
+ return b.Bytes()
+}
diff --git a/cmd/mprp/logopng_test.go b/cmd/mprp/logopng_test.go
new file mode 100644
index 0000000..7477273
--- /dev/null
+++ b/cmd/mprp/logopng_test.go
@@ -0,0 +1,18 @@
+package main
+
+import (
+ "bytes"
+ "image/png"
+ "testing"
+)
+
+// The page's 256 px icon (/icon.png) is a PNG of that size.
+func TestLogoPNG(t *testing.T) {
+ img, err := png.Decode(bytes.NewReader(logoPNG()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b := img.Bounds(); b.Dx() != 256 || b.Dy() != 256 {
+ t.Errorf("icon.png is %dx%d, want 256x256", b.Dx(), b.Dy())
+ }
+}
diff --git a/cmd/mpcvibedrpc/main.go b/cmd/mprp/main.go
similarity index 63%
rename from cmd/mpcvibedrpc/main.go
rename to cmd/mprp/main.go
index 5be6859..bc33328 100644
--- a/cmd/mpcvibedrpc/main.go
+++ b/cmd/mprp/main.go
@@ -1,4 +1,4 @@
-// MPCvibedRPC: shows what MPC-HC, MPC-BE, MPC-QT, mpv, VLC or PotPlayer (on macOS also IINA; on Linux any video player
+// MPRP: shows what MPC-HC, MPC-BE, MPC-QT, mpv, VLC or PotPlayer (on macOS also IINA; on Linux any video player
// that offers MPRIS), Kodi, or Plex, Jellyfin, Emby or Stremio once signed in, is playing as a Discord Rich Presence. Runs from
// the tray on Windows and in the background on macOS and Linux; the settings are a small local web page opened in an
// app-style window.
@@ -19,16 +19,18 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/capture"
- "github.com/CptPakundo/MPCvibedRPC/internal/conns"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/artwork"
+ "github.com/CptPakundo/MPRP/internal/capture"
+ "github.com/CptPakundo/MPRP/internal/conns"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// version is set at build time (-ldflags "-X main.version=...").
-var version = "0.9.58"
+var version = "0.9.60"
const preferredPort = 47654
@@ -42,12 +44,14 @@ var (
)
func main() {
+ core.AdoptFormerEnv() // before anything reads the environment: the former version may have started this copy
+ artwork.SetVersion(version)
args := os.Args[1:]
for i := 0; i < len(args); i++ {
switch args[i] {
- case "--home": // a data folder of its own, as MPCRPC_HOME gives (Windows run-at-login passes it this way)
+ case "--home": // a data folder of its own, as MPRP_HOME gives (Windows run-at-login passes it this way)
if i+1 < len(args) {
- os.Setenv("MPCRPC_HOME", args[i+1])
+ os.Setenv("MPRP_HOME", args[i+1])
i++
}
case "--background":
@@ -69,7 +73,7 @@ func main() {
if detach() {
return
}
- if v := os.Getenv("MPCRPC_UPDATE_API"); v != "" { // tests and self-hosted mirrors
+ if v := os.Getenv("MPRP_UPDATE_API"); v != "" { // tests and self-hosted mirrors
updater.APIBase = strings.TrimRight(v, "/")
updater.WebBase = updater.APIBase
}
@@ -89,7 +93,7 @@ func main() {
}
func crash(msg string) {
- f, err := os.OpenFile(filepath.Join(os.TempDir(), "mpcvibedrpc-crash.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
+ f, err := os.OpenFile(filepath.Join(os.TempDir(), "mprp-crash.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err == nil {
fmt.Fprintf(f, "%s %s\n", time.Now().UTC().Format(time.RFC3339), msg)
f.Close()
@@ -123,7 +127,7 @@ func pingExisting(ipcFile string) *ipcInfo {
App string `json:"app"`
Pid int `json:"pid"`
}
- if res.StatusCode != 200 || json.NewDecoder(io.LimitReader(res.Body, 4096)).Decode(&p) != nil || p.App != "MPCvibedRPC" {
+ if res.StatusCode != 200 || json.NewDecoder(io.LimitReader(res.Body, 4096)).Decode(&p) != nil || !isOurApp(p.App) {
return nil
}
// A file left by a copy that crashed can name a port that another copy (one with its own data folder) answers on
@@ -208,3 +212,50 @@ func setHideTitle(st *store.Store, eng *engine.Engine, log func(level, msg strin
log("INFO", "Hide what I'm watching turned off from the menu.")
}
}
+
+// isOurApp says whether the app name a local server gave (/api/ping) is this program's, under its current name or
+// its former one: a copy of the former version that still runs is another copy of this program.
+func isOurApp(name string) bool { return name == core.Name || name == core.FormerName }
+
+// chooseDataDir picks the data folder at the start: dir, the folder of the program's name, unless only the former
+// name's folder (former; "" for a copy with a data folder of its own) is there (with both there, dir is used; during
+// an update formerIPC then lets the old copy see this one in either). Then:
+// - after an update (updating), the former version that started this copy watches ipc.json in that folder to see
+// that this copy came up, so the folder is used where it is this time and moved at a later start;
+// - when a copy that uses it still runs (ping finds it), that copy is given back (other), to be shown as for any
+// second start, and nothing is moved;
+// - otherwise it is moved (or copied) to dir, and note says so for the log.
+func chooseDataDir(dir, former string, updating bool, ping func(ipcFile string) *ipcInfo) (use string, other *ipcInfo, note string) {
+ if former == "" {
+ return dir, nil, ""
+ }
+ if _, err := os.Stat(dir); err == nil {
+ return dir, nil, ""
+ }
+ if fi, err := os.Stat(former); err != nil || !fi.IsDir() {
+ return dir, nil, ""
+ }
+ if updating {
+ return former, nil, "The data folder " + former + " is used where it is during the update; a later start moves it to " + dir + "."
+ }
+ if o := ping(filepath.Join(former, "ipc.json")); o != nil {
+ return dir, o, ""
+ }
+ use, note = store.MoveFormerData(former, dir)
+ return use, nil, note
+}
+
+// formerIPC is a second place for ipc.json during an update ("": none). The copy that started this one watches ipc.json
+// in its own data folder to see that this copy came up, and that may be the former name's folder although this copy
+// uses the new one: a copy of the former version that runs again after a downgrade made that folder anew. So while
+// both folders are there, ipc.json is written to both; whichever the old copy watches, it sees this one, and an
+// update from a version of the new name (which watches the new folder) is not mistaken either.
+func formerIPC(use, former string, updating bool) string {
+ if !updating || former == "" || use == former {
+ return ""
+ }
+ if fi, err := os.Stat(former); err != nil || !fi.IsDir() {
+ return ""
+ }
+ return filepath.Join(former, "ipc.json")
+}
diff --git a/cmd/mprp/notify_test.go b/cmd/mprp/notify_test.go
new file mode 100644
index 0000000..596c9d0
--- /dev/null
+++ b/cmd/mprp/notify_test.go
@@ -0,0 +1,74 @@
+package main
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/notify"
+ "github.com/CptPakundo/MPRP/internal/updater"
+)
+
+// With no tray icon (Linux), a version found in the background that will not install itself is announced once
+// through the desktop's notification service: here a fake one on a fake session bus.
+func TestUpdateNoticeOverTheBus(t *testing.T) {
+ defer func(old bool) { notifyOverBus = old }(notifyOverBus)
+ notifyOverBus = true
+ defer func(old string) { updater.APIBase = old }(updater.APIBase)
+ gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"tag_name":"v99.0.0","body":"notes","html_url":"x","assets":[]}`)
+ }))
+ defer gh.Close()
+ updater.APIBase = gh.URL
+
+ bus := dbustest.New(t)
+ var mu sync.Mutex
+ var shown [][]any
+ bus.Own("org.freedesktop.Notifications", func(m *dbus.Message) dbustest.Reply {
+ mu.Lock()
+ defer mu.Unlock()
+ shown = append(shown, m.Body)
+ return dbustest.Reply{Sig: "u", Body: []any{uint32(len(shown))}}
+ })
+ a, logs := autoApp(t)
+ setApp(t, a.st, `{"checkUpdates":true,"autoUpdate":false}`)
+ a.notifier = ¬ify.Notifier{Address: bus.Address, AppName: "MPRP", Log: a.log}
+ defer a.notifier.Close()
+
+ if _, err := a.checkUpdates(false); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.checkUpdates(false); err != nil { // the same version again: no second notice
+ t.Fatal(err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(shown) != 1 {
+ t.Fatalf("%d notices, want 1; log:\n%s", len(shown), logs())
+ }
+ if title, text := shown[0][3], shown[0][4]; title != "MPRP 99.0.0 is available" ||
+ text != "You have "+version+". Click here to see what's new and install it." {
+ t.Errorf("notice %q / %q", title, text)
+ }
+ if !strings.Contains(logs(), "Showed an update notice.") {
+ t.Errorf("log:\n%s", logs())
+ }
+}
+
+// Without a tray icon and away from Linux (macOS built without Cocoa), nothing is shown and nothing is asked.
+func TestNoNoticeWithoutTrayOrBus(t *testing.T) {
+ defer func(old bool) { notifyOverBus = old }(notifyOverBus)
+ notifyOverBus = false
+ a, _ := autoApp(t)
+ if a.notify("title", "text") {
+ t.Error("shown with neither a tray icon nor a notification service")
+ }
+ if a.getNotifier() != nil {
+ t.Error("a notifier was made")
+ }
+}
diff --git a/cmd/mpcvibedrpc/players_doc_test.go b/cmd/mprp/players_doc_test.go
similarity index 95%
rename from cmd/mpcvibedrpc/players_doc_test.go
rename to cmd/mprp/players_doc_test.go
index c89618d..8c4f2e3 100644
--- a/cmd/mpcvibedrpc/players_doc_test.go
+++ b/cmd/mprp/players_doc_test.go
@@ -14,7 +14,7 @@ func TestPlayersAreNamedEverywhere(t *testing.T) {
files := []string{
"README.md", "SECURITY.md",
"docs/how-it-works.md", "docs/troubleshooting.md", "docs/development.md", "docs/config.md",
- "cmd/mpcvibedrpc/main.go", // the header comment
+ "cmd/mprp/main.go", // the header comment
"tools/mkrsrc/main.go", // the exe's file description
"internal/assets/ui.js", // the welcome and help texts
"internal/engine/engine.go", // the package comment and Status.Player
diff --git a/cmd/mpcvibedrpc/plex.go b/cmd/mprp/plex.go
similarity index 98%
rename from cmd/mpcvibedrpc/plex.go
rename to cmd/mprp/plex.go
index 74f8dbb..be35f4f 100644
--- a/cmd/mpcvibedrpc/plex.go
+++ b/cmd/mprp/plex.go
@@ -6,9 +6,9 @@ import (
"fmt"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/plex"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/plex"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// plexSignIn are the settings a Plex sign-in writes and a sign-out forgets; plexClient, this install's identifier on
diff --git a/cmd/mpcvibedrpc/plex_test.go b/cmd/mprp/plex_test.go
similarity index 99%
rename from cmd/mpcvibedrpc/plex_test.go
rename to cmd/mprp/plex_test.go
index 603def6..19dafa7 100644
--- a/cmd/mpcvibedrpc/plex_test.go
+++ b/cmd/mprp/plex_test.go
@@ -13,8 +13,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// fakePlexTV hands out a sign-in code that is approved on the third check (or never, when approve is false).
diff --git a/cmd/mprp/rename_test.go b/cmd/mprp/rename_test.go
new file mode 100644
index 0000000..e817f91
--- /dev/null
+++ b/cmd/mprp/rename_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The carrying over of an install made under the program's former name, at the start.
+func TestChooseDataDir(t *testing.T) {
+ noCopy := func(string) *ipcInfo { return nil }
+ setup := func(t *testing.T, withFormer, withNew bool) (dir, former string) {
+ base := t.TempDir()
+ dir, former = filepath.Join(base, "MPRP"), filepath.Join(base, "MPCvibedRPC")
+ if withFormer {
+ os.MkdirAll(former, 0o700)
+ os.WriteFile(filepath.Join(former, "config.json"), []byte(`{"port":13580}`), 0o600)
+ }
+ if withNew {
+ os.MkdirAll(dir, 0o700)
+ }
+ return dir, former
+ }
+
+ t.Run("a new install", func(t *testing.T) {
+ dir, former := setup(t, false, false)
+ if use, other, note := chooseDataDir(dir, former, false, noCopy); use != dir || other != nil || note != "" {
+ t.Errorf("use %q other %v note %q", use, other, note)
+ }
+ })
+ t.Run("a copy with a data folder of its own never moves anything", func(t *testing.T) {
+ dir, former := setup(t, true, false)
+ if use, _, note := chooseDataDir(dir, "", false, noCopy); use != dir || note != "" {
+ t.Errorf("use %q note %q", use, note)
+ }
+ if _, err := os.Stat(former); err != nil {
+ t.Error("the former folder was touched")
+ }
+ })
+ t.Run("already moved", func(t *testing.T) {
+ dir, former := setup(t, true, true)
+ if use, _, note := chooseDataDir(dir, former, false, noCopy); use != dir || note != "" {
+ t.Errorf("use %q note %q", use, note)
+ }
+ })
+ t.Run("the first start under the new name moves the folder", func(t *testing.T) {
+ dir, former := setup(t, true, false)
+ use, other, note := chooseDataDir(dir, former, false, noCopy)
+ if use != dir || other != nil || !strings.HasPrefix(note, "Moved the data folder") {
+ t.Fatalf("use %q other %v note %q", use, other, note)
+ }
+ if b, err := os.ReadFile(filepath.Join(dir, "config.json")); err != nil || string(b) != `{"port":13580}` {
+ t.Error("the settings did not come along")
+ }
+ })
+ t.Run("during an update from the former version the folder stays where the old copy looks", func(t *testing.T) {
+ dir, former := setup(t, true, false)
+ asked := false
+ use, other, note := chooseDataDir(dir, former, true, func(string) *ipcInfo { asked = true; return nil })
+ if use != former || other != nil || !strings.Contains(note, "during the update") || asked {
+ t.Errorf("use %q other %v note %q asked %v", use, other, note, asked)
+ }
+ if _, err := os.Stat(dir); err == nil {
+ t.Error("the new folder was made during the update")
+ }
+ })
+ t.Run("updating while both folders exist: the new folder, with ipc.json in both", func(t *testing.T) {
+ // a copy of the former version that runs again after a downgrade made its folder anew, and updates itself
+ dir, former := setup(t, true, true)
+ use, other, note := chooseDataDir(dir, former, true, noCopy)
+ if use != dir || other != nil || note != "" {
+ t.Fatalf("use %q other %v note %q", use, other, note)
+ }
+ mirror := formerIPC(use, former, true)
+ if mirror != filepath.Join(former, "ipc.json") {
+ t.Fatalf("formerIPC = %q", mirror)
+ }
+ a := &app{ipcFile: filepath.Join(use, "ipc.json"), ipcFormer: mirror, token: "t"}
+ a.writeIPC(4321)
+ // the old copy, whichever folder it watches, sees this copy come up
+ for _, f := range []string{a.ipcFile, mirror} {
+ if !copyCameUp(f, os.Getpid(), make(chan struct{}), time.Second) {
+ t.Errorf("%s does not show this copy", f)
+ }
+ }
+ a.removeIPCFiles()
+ for _, f := range []string{a.ipcFile, mirror} {
+ if _, err := os.Stat(f); err == nil {
+ t.Errorf("%s is left behind", f)
+ }
+ }
+ // no second place outside an update, or when the former folder is the one in use, or is not there
+ if formerIPC(use, former, false) != "" || formerIPC(former, former, true) != "" || formerIPC(use, "", true) != "" ||
+ formerIPC(use, filepath.Join(t.TempDir(), "none"), true) != "" {
+ t.Error("a second ipc.json outside an update while both folders are there")
+ }
+ })
+ t.Run("a copy of the former version still runs: it is shown and nothing moves", func(t *testing.T) {
+ dir, former := setup(t, true, false)
+ running := &ipcInfo{Port: 1234, Token: "t", Pid: 42}
+ var askedFor string
+ use, other, note := chooseDataDir(dir, former, false, func(f string) *ipcInfo { askedFor = f; return running })
+ if other != running || note != "" || askedFor != filepath.Join(former, "ipc.json") {
+ t.Errorf("use %q other %v note %q asked for %q", use, other, note, askedFor)
+ }
+ if _, err := os.Stat(dir); err == nil {
+ t.Error("the folder was moved from under a running copy")
+ }
+ })
+}
+
+// A running copy answers /api/ping with its name: the current one and the former one both count as this program.
+func TestPingExistingKnowsTheFormerName(t *testing.T) {
+ for _, c := range []struct {
+ app string
+ want bool
+ }{{"MPRP", true}, {"MPCvibedRPC", true}, {"SomethingElse", false}, {"", false}} {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"app": c.app, "pid": 7})
+ }))
+ u, _ := url.Parse(srv.URL)
+ port, _ := strconv.Atoi(u.Port())
+ f := filepath.Join(t.TempDir(), "ipc.json")
+ b, _ := json.Marshal(ipcInfo{Port: port, Token: "t", Pid: 7})
+ os.WriteFile(f, b, 0o600)
+ if got := pingExisting(f) != nil; got != c.want {
+ t.Errorf("app %q: found %v, want %v", c.app, got, c.want)
+ }
+ srv.Close()
+ }
+}
diff --git a/cmd/mpcvibedrpc/selfcheck.go b/cmd/mprp/selfcheck.go
similarity index 97%
rename from cmd/mpcvibedrpc/selfcheck.go
rename to cmd/mprp/selfcheck.go
index 7549adb..de924c6 100644
--- a/cmd/mpcvibedrpc/selfcheck.go
+++ b/cmd/mprp/selfcheck.go
@@ -9,11 +9,11 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/capture"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/capture"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
// checkItem is one line of "Run a check" (Help tab). Its text never holds a title or a file name.
diff --git a/cmd/mpcvibedrpc/selfcheck_test.go b/cmd/mprp/selfcheck_test.go
similarity index 96%
rename from cmd/mpcvibedrpc/selfcheck_test.go
rename to cmd/mprp/selfcheck_test.go
index 242e65c..3b717b6 100644
--- a/cmd/mpcvibedrpc/selfcheck_test.go
+++ b/cmd/mprp/selfcheck_test.go
@@ -7,10 +7,10 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
// checkApp is an app whose engine sees no player, no Discord and no catalog on this computer.
diff --git a/cmd/mprp/startwrites_test.go b/cmd/mprp/startwrites_test.go
new file mode 100644
index 0000000..64b4f50
--- /dev/null
+++ b/cmd/mprp/startwrites_test.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
+)
+
+// run() announces this copy (ipc.json) before anything in it writes config.json: a write placed above a.announce
+// would happen before the copy has shown that it runs, which after an update the version put back may not read. Only
+// writeEarly, which writes nothing after an update (TestStartWritesWaitForIPCAfterAnUpdate), comes before.
+func TestRunAnnouncesBeforeItWrites(t *testing.T) {
+ b, err := os.ReadFile("app.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ src := strings.ReplaceAll(string(b), "\r\n", "\n")
+ start := strings.Index(src, "\nfunc run() error {\n")
+ if start < 0 {
+ t.Fatal("no func run in app.go")
+ }
+ body := src[start:]
+ body = body[:strings.Index(body, "\n}\n")]
+ announce := strings.Index(body, "a.announce(")
+ if announce < 0 || strings.Count(body, "a.announce(") != 1 {
+ t.Fatal("run() must call a.announce once")
+ }
+ if early := strings.Index(body, "a.writeEarly("); early < 0 || early > announce {
+ t.Error("run() must call a.writeEarly before a.announce")
+ }
+ // every Store method that writes config.json, and the callers that write through one
+ for _, w := range []string{"st.Update(", "st.SetSettings(", "st.SetHidden(", "st.Reset(", ".MigrateMatchFixes(",
+ "a.startWrites(", "keepFresh(", "applySettings(", "setHideTitle(", "setStreamTitle("} {
+ for from := 0; ; {
+ i := strings.Index(body[from:], w)
+ if i < 0 {
+ break
+ }
+ if from+i < announce {
+ t.Errorf("run() calls %s before a.announce: it would write config.json before ipc.json", w)
+ }
+ from += i + len(w)
+ }
+ }
+}
+
+// When every old Fix a match line is left out after an update, the engine that runs already drops them too: the
+// migration wrote an empty list, and the settings are applied although no fix was written.
+func TestStartWritesAppliesWhenNoOldLineIsKept(t *testing.T) {
+ dir := t.TempDir()
+ old := `{"artworkOverrides": {"sample show": "C:/covers/show.jpg"}, "app": {"welcomeSeen": true, "checkUpdates": false}}`
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(old), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ st, err := store.New(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ eng := engine.New(st.Config(), engine.Options{Log: func(string, string) {}})
+ if c0 := eng.Config(); len(c0.Fixes()) != 1 {
+ t.Fatalf("before: the engine has the fixes %+v, want the old line", c0.Fixes())
+ }
+ a := &app{st: st, eng: eng, log: func(string, string) {}}
+ a.startWrites(false)
+ if c1 := eng.Config(); len(c1.Fixes()) != 0 {
+ t.Errorf("after: the engine still has the fixes %+v", c1.Fixes())
+ }
+}
+
+// After an update nothing is written to config.json before ipc.json shows that this copy runs: every write encrypts
+// the sign-ins, and the version before, put back if this copy does not come up, may not read them. A normal start
+// makes the same writes before.
+func TestStartWritesWaitForIPCAfterAnUpdate(t *testing.T) {
+ const old = `{"artworkAliases": {"sample show": "Sample Series"}, "app": {"checkUpdates": false}}`
+ for _, updating := range []bool{true, false} {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(old), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ st, err := store.New(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ saved := afterUpdate
+ afterUpdate = updating
+ t.Cleanup(func() { afterUpdate = saved })
+ a := &app{st: st, log: func(string, string) {}, ipcFile: st.IPCPath(), token: "t"}
+ written := func() bool {
+ b, _ := os.ReadFile(st.File)
+ return string(b) != old
+ }
+
+ a.writeEarly(false)
+ if written() == updating {
+ t.Errorf("updating %v: config.json written before ipc.json: %v", updating, written())
+ }
+ a.announce(4321, false)
+ if _, err := os.Stat(a.ipcFile); err != nil {
+ t.Errorf("updating %v: no ipc.json", updating)
+ }
+ b, _ := os.ReadFile(st.File)
+ if !strings.Contains(string(b), `"matchFixes"`) || !st.App().WelcomeSeen {
+ t.Errorf("updating %v: the start's writes were not made:\n%s", updating, b)
+ }
+ }
+}
diff --git a/cmd/mpcvibedrpc/stremio.go b/cmd/mprp/stremio.go
similarity index 95%
rename from cmd/mpcvibedrpc/stremio.go
rename to cmd/mprp/stremio.go
index 18e4b03..cd76999 100644
--- a/cmd/mpcvibedrpc/stremio.go
+++ b/cmd/mprp/stremio.go
@@ -6,9 +6,9 @@ import (
"fmt"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/stremio"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/stremio"
)
// stremioAccount drives "Sign in to Stremio": a code the user approves on stremio.com in their browser, after which
diff --git a/cmd/mpcvibedrpc/stremio_test.go b/cmd/mprp/stremio_test.go
similarity index 97%
rename from cmd/mpcvibedrpc/stremio_test.go
rename to cmd/mprp/stremio_test.go
index 2f38f3c..ab7d6f8 100644
--- a/cmd/mpcvibedrpc/stremio_test.go
+++ b/cmd/mprp/stremio_test.go
@@ -12,8 +12,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// fakeStremioLink hands out a sign-in code that is approved on the third check, and ends sessions on logout.
diff --git a/cmd/mpcvibedrpc/tray.go b/cmd/mprp/tray.go
similarity index 57%
rename from cmd/mpcvibedrpc/tray.go
rename to cmd/mprp/tray.go
index ac06f07..c1db62d 100644
--- a/cmd/mpcvibedrpc/tray.go
+++ b/cmd/mprp/tray.go
@@ -1,9 +1,12 @@
package main
import (
- "github.com/CptPakundo/MPCvibedRPC/internal/assets"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "runtime"
+
+ "github.com/CptPakundo/MPRP/internal/assets"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/notify"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// startTray puts up the tray icon (Windows) or the menu bar icon (macOS); elsewhere there is none.
@@ -31,7 +34,7 @@ func (a *app) startTray() *winsys.Tray {
// trayTooltip is the icon's tooltip and the menu's status line (Windows cuts tooltips at 63 characters).
func trayTooltip(s engine.Status) string {
- t := "MPCvibedRPC - "
+ t := "MPRP - "
switch {
case !s.Running:
t += "Not showing on Discord"
@@ -47,3 +50,30 @@ func trayTooltip(s engine.Status) string {
}
return t
}
+
+// notifyOverBus: with no tray icon, notifications go to the desktop's notification service over D-Bus (Linux).
+var notifyOverBus = runtime.GOOS == "linux"
+
+// notify shows a notification; a click on it opens the settings window. Windows shows it next to the tray icon, macOS
+// through the menu bar app, Linux through the desktop's notification service. It reports whether it was shown.
+func (a *app) notify(title, text string) bool {
+ if t := a.getTray(); t != nil {
+ return t.Balloon(title, text)
+ }
+ if !notifyOverBus {
+ return false
+ }
+ a.mu.Lock()
+ if a.notifier == nil {
+ a.notifier = ¬ify.Notifier{AppName: "MPRP", OnClick: a.openWindow, Log: a.log}
+ }
+ n := a.notifier
+ a.mu.Unlock()
+ return n.Show(title, text)
+}
+
+func (a *app) getNotifier() *notify.Notifier {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.notifier
+}
diff --git a/cmd/mpcvibedrpc/update.go b/cmd/mprp/update.go
similarity index 95%
rename from cmd/mpcvibedrpc/update.go
rename to cmd/mprp/update.go
index c9bde7e..bd45263 100644
--- a/cmd/mpcvibedrpc/update.go
+++ b/cmd/mprp/update.go
@@ -12,10 +12,10 @@ import (
"sync/atomic"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/proc"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/proc"
+ "github.com/CptPakundo/MPRP/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// updates is what the program knows about newer versions.
@@ -42,7 +42,7 @@ func (u *updates) newer() *updater.Info {
// checkUpdates asks GitHub for a newer version: when the window asks (manual), or in the background while
// "Check for updates automatically" is on. A version found in the background is offered by an open settings window
// at once (its page asks for the state every second); with no window open, and when it will not install itself, it is
-// announced next to the tray icon once.
+// announced once in a notification (see notify).
func (a *app) checkUpdates(manual bool) (*updater.Info, error) {
s := a.st.App()
if !manual && !(s.CheckUpdates && s.UpdateRepo != "") {
@@ -67,12 +67,11 @@ func (a *app) checkUpdates(manual bool) (*updater.Info, error) {
first := a.upd.notified != r.Latest
a.upd.notified = r.Latest
a.upd.mu.Unlock()
- t := a.getTray()
- if first && t != nil && winsys.IsWindows { // the macOS menu bar icon has no notifications
- if t.Balloon("MPCvibedRPC "+r.Latest+" is available", "You have "+version+". Click here to see what's new and install it.") {
- a.log("INFO", "Showed an update notice next to the tray icon.")
+ if first {
+ if a.notify("MPRP "+r.Latest+" is available", "You have "+version+". Click here to see what's new and install it.") {
+ a.log("INFO", "Showed an update notice.")
} else {
- a.log("WARN", "Windows did not show the update notice.")
+ a.log("WARN", "The update notice was not shown (no notifications here, or the system refused it).")
}
}
return r, nil
@@ -270,7 +269,7 @@ func (a *app) installUpdate(quiet func() bool) error {
wasRunning := a.eng.Status().Running
a.eng.Stop()
a.log("INFO", "Update downloaded; restarting.")
- _ = removeIPC(a.ipcFile)
+ a.removeIPCFiles()
// goOn puts this copy back to work when the new one cannot take over
goOn := func() {
if !a.quitting.Load() { // a quit that began meanwhile has closed the server and stopped the engine for good
diff --git a/cmd/mpcvibedrpc/update_sched_test.go b/cmd/mprp/update_sched_test.go
similarity index 98%
rename from cmd/mpcvibedrpc/update_sched_test.go
rename to cmd/mprp/update_sched_test.go
index 1d38624..a3d9ef5 100644
--- a/cmd/mpcvibedrpc/update_sched_test.go
+++ b/cmd/mprp/update_sched_test.go
@@ -6,7 +6,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
// The check by itself follows the wall clock: due at once when none went out yet, six hours after one that
diff --git a/cmd/mpcvibedrpc/update_test.go b/cmd/mprp/update_test.go
similarity index 95%
rename from cmd/mpcvibedrpc/update_test.go
rename to cmd/mprp/update_test.go
index 8cdd186..b6302bb 100644
--- a/cmd/mpcvibedrpc/update_test.go
+++ b/cmd/mprp/update_test.go
@@ -8,10 +8,10 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
- "github.com/CptPakundo/MPCvibedRPC/internal/updater"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/store"
+ "github.com/CptPakundo/MPRP/internal/updater"
)
// An automatic update only restarts the program when that interrupts nobody: nothing shown on Discord (a cleared
diff --git a/cmd/mpcvibedrpc/window.go b/cmd/mprp/window.go
similarity index 52%
rename from cmd/mpcvibedrpc/window.go
rename to cmd/mprp/window.go
index cd25b89..7a49141 100644
--- a/cmd/mpcvibedrpc/window.go
+++ b/cmd/mprp/window.go
@@ -4,25 +4,46 @@ import (
"runtime"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/winsys"
+ "github.com/CptPakundo/MPRP/internal/winsys"
)
// The settings window's X quits the program, and minimising it sends it to the tray (minimizeToTray, Windows).
// Both apply only to the program's own app window (not to a tab of the user's browser) and not on macOS, where the
// window closes to the menu bar as Mac apps do.
-var (
- // windowGoneWait is how long the program waits after the last window's connection ended before it takes that as
- // the window's X: a reload or a broken connection (the page reconnects within about a second) comes back in time.
- windowGoneWait = 3 * time.Second
+// windowSys is what the window code asks of the system, and its waits. Tests give an app one of their own (app.winSys).
+type windowSys struct {
+ find func(profileDir string) uintptr // the settings window's handle (Windows; 0: not found)
+ state func(h uintptr) (exists, minimised bool)
+ close func(h uintptr) bool // asks the window to close; false: the request could not be delivered
+ quit func(a *app) // what the X does
+ goos string
+
+ // goneWait is how long the program waits after the last window's connection ended before it takes that as the
+ // window's X: a reload or a broken connection (the page reconnects within about a second) comes back in time.
+ goneWait time.Duration
// goneCheck is how long a window that still stands after its page went is watched for going (Windows): the X
// destroys the window, a reload keeps it.
- goneCheck = time.Second
- goneEvery = 25 * time.Millisecond
+ goneCheck, goneEvery time.Duration
// minimiseEvery is how often an open window is checked for being minimised; notFoundEvery when it was not found.
- minimiseEvery = 250 * time.Millisecond
- notFoundEvery = 2 * time.Second
-)
+ minimiseEvery, notFoundEvery time.Duration
+ // closeFailedAfter: a window the program closed (minimised to the tray) that still stands this long after, and is
+ // no longer minimised, did not close (a page dialog, a refused close): its X quits again.
+ closeFailedAfter time.Duration
+}
+
+var systemWindow = windowSys{
+ find: winsys.SettingsWindow, state: winsys.WindowState, close: winsys.CloseWindow, quit: (*app).quit, goos: runtime.GOOS,
+ goneWait: 3 * time.Second, goneCheck: time.Second, goneEvery: 25 * time.Millisecond,
+ minimiseEvery: 250 * time.Millisecond, notFoundEvery: 2 * time.Second, closeFailedAfter: 2 * time.Second,
+}
+
+func (a *app) win() *windowSys {
+ if a.winSys != nil {
+ return a.winSys
+ }
+ return &systemWindow
+}
// windowOpened counts a window's page that connected.
func (a *app) windowOpened() {
@@ -35,31 +56,32 @@ func (a *app) windowOpened() {
// windowClosed counts a window's page that went. When it was the last, the window may have been closed with its X:
// then the program quits. On Windows that is known at once: the window itself is gone (a reload keeps it).
// Otherwise, and when the window still stands after goneCheck, the program quits once no page is back within
-// windowGoneWait. A window asked for in the meantime (still loading) keeps it.
+// goneWait (see windowSys). A window asked for in the meantime (still loading) keeps it.
func (a *app) windowClosed() {
if a.windows.Add(-1) > 0 {
return
}
// as things were when it went: a window opened again from the tray meanwhile clears inTray
inTray, opened, h := a.inTray.Load(), a.opened.Load(), a.winHandle.Load()
+ w := a.win()
quitIfClosed := func() {
- if a.opened.Load() == opened && closeQuits(a.windows.Load(), a.appWindow.Load(), inTray, a.quitting.Load(), runtime.GOOS) {
+ if a.opened.Load() == opened && closeQuits(a.windows.Load(), a.appWindow.Load(), inTray, a.quitting.Load(), w.goos) {
a.log("INFO", "The settings window was closed: quitting.")
- a.quit()
+ w.quit(a)
}
}
if h == 0 {
- time.AfterFunc(windowGoneWait, quitIfClosed)
+ time.AfterFunc(w.goneWait, quitIfClosed)
return
}
go func() {
- for end := time.Now().Add(goneCheck); time.Now().Before(end); time.Sleep(goneEvery) {
- if exists, _ := winsys.WindowState(h); !exists {
+ for end := time.Now().Add(w.goneCheck); time.Now().Before(end); time.Sleep(w.goneEvery) {
+ if exists, _ := w.state(h); !exists {
quitIfClosed()
return
}
}
- time.AfterFunc(windowGoneWait, quitIfClosed) // the window still stands: a reload, or a page that lost its connection
+ time.AfterFunc(w.goneWait, quitIfClosed) // the window still stands: a reload, or a page that lost its connection
}()
}
@@ -72,12 +94,14 @@ func closeQuits(windows int32, appWindow, inTray, quitting bool, goos string) bo
// watchMinimise runs while a window is open (Windows): a window that gets minimised is closed instead when
// minimizeToTray is on, so it lives on in the tray icon. One runs at a time (a.watching).
func (a *app) watchMinimise() {
+ w := a.win()
var h uintptr
wasMin, missed := false, false
+ var closedAt time.Time // when the program closed the window (minimised to the tray)
for {
- wait := minimiseEvery
+ wait := w.minimiseEvery
if missed {
- wait = notFoundEvery
+ wait = w.notFoundEvery
}
time.Sleep(wait)
if a.windows.Load() == 0 || a.quitting.Load() {
@@ -89,23 +113,34 @@ func (a *app) watchMinimise() {
h, wasMin = 0, false
}
if h == 0 {
- if h = winsys.SettingsWindow(a.browserProfile); h == 0 {
+ if h = w.find(a.browserProfile); h == 0 {
missed = true
continue
}
missed = false
a.winHandle.Store(h) // for windowClosed
}
- exists, min := winsys.WindowState(h)
+ exists, min := w.state(h)
if !exists {
h, wasMin = 0, false
+ closedAt = time.Time{}
a.winHandle.Store(0)
continue
}
if min && !wasMin && a.st.App().MinimizeToTray {
a.inTray.Store(true) // its going is not the X: the program stays
- winsys.CloseWindow(h)
- a.log("INFO", "The settings window was minimized to the tray.")
+ if w.close(h) {
+ closedAt = time.Now()
+ a.log("INFO", "The settings window was minimized to the tray.")
+ } else {
+ a.inTray.Store(false)
+ a.log("WARN", "The settings window could not be closed to the tray; it stays minimized.")
+ }
+ }
+ // a close that did not happen (the window stands again, restored) must not keep the X from quitting later
+ if !closedAt.IsZero() && !min && time.Since(closedAt) >= w.closeFailedAfter && a.inTray.CompareAndSwap(true, false) {
+ closedAt = time.Time{}
+ a.log("INFO", "The settings window did not close to the tray; its X quits again.")
}
wasMin = min
}
diff --git a/cmd/mprp/window_test.go b/cmd/mprp/window_test.go
new file mode 100644
index 0000000..3c09b9a
--- /dev/null
+++ b/cmd/mprp/window_test.go
@@ -0,0 +1,234 @@
+package main
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// The settings window's going quits the program only when the user closed the program's own window.
+func TestCloseQuits(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ windows int32
+ appWindow, inTray, quitting bool
+ goos string
+ want bool
+ }{
+ {"closed with its X", 0, true, false, false, "windows", true},
+ {"Linux app window", 0, true, false, false, "linux", true},
+ {"a window is open again (a reload)", 1, true, false, false, "windows", false},
+ {"a tab of the user's browser", 0, false, false, false, "windows", false},
+ {"minimised to the tray", 0, true, true, false, "windows", false},
+ {"quitting already", 0, true, false, true, "windows", false},
+ {"macOS closes to the menu bar", 0, true, false, false, "darwin", false},
+ } {
+ if got := closeQuits(c.windows, c.appWindow, c.inTray, c.quitting, c.goos); got != c.want {
+ t.Errorf("%s: %v, want %v", c.name, got, c.want)
+ }
+ }
+}
+
+// fakeWindow stands in for the settings window: whether it exists and is minimised, and whether a close is refused.
+type fakeWindow struct {
+ mu sync.Mutex
+ exists, min bool
+ refuse bool // a close is delivered but the window stays (a page dialog)
+ undelivered bool // a close cannot even be delivered
+ closes int
+}
+
+func (w *fakeWindow) set(f func(w *fakeWindow)) { w.mu.Lock(); f(w); w.mu.Unlock() }
+
+func (w *fakeWindow) closed() int { w.mu.Lock(); defer w.mu.Unlock(); return w.closes }
+
+// The short waits of the tests.
+const (
+ testGoneWait = 300 * time.Millisecond
+ testGoneCheck = 150 * time.Millisecond
+ testCloseFailed = 60 * time.Millisecond
+)
+
+// fakeSys is the system's window functions with w in place of the window, short waits, and an X that counts its
+// quits (a counted quit marks its app as quitting, so nothing real runs).
+func fakeSys(w *fakeWindow) (sys *windowSys, quits func() int32) {
+ n := &atomic.Int32{}
+ sys = &windowSys{
+ find: func(string) uintptr {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.exists {
+ return 7
+ }
+ return 0
+ },
+ state: func(h uintptr) (bool, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return h == 7 && w.exists, w.exists && w.min
+ },
+ close: func(uintptr) bool {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.undelivered {
+ return false
+ }
+ w.closes++
+ if !w.refuse {
+ w.exists = false
+ }
+ return true
+ },
+ quit: func(a *app) { n.Add(1); a.quitting.Store(true) },
+ goos: "windows",
+ goneWait: testGoneWait, goneCheck: testGoneCheck, goneEvery: 5 * time.Millisecond,
+ minimiseEvery: 5 * time.Millisecond, notFoundEvery: 5 * time.Millisecond, closeFailedAfter: testCloseFailed,
+ }
+ return sys, n.Load
+}
+
+// windowApp is a program with its app window open (one page connected); h is the window as watchMinimise found it.
+func windowApp(t *testing.T, sys *windowSys, h uintptr) *app {
+ a, _ := autoApp(t)
+ a.winSys = sys
+ a.appWindow.Store(true)
+ a.windows.Store(1)
+ a.winHandle.Store(h)
+ t.Cleanup(func() { a.quitting.Store(true); a.windows.Store(0) }) // no late timer quits; a watcher ends
+ return a
+}
+
+// The order of the two signs of the X: the page's /api/alive connection drops, and (Windows) the window itself goes.
+func TestWindowXOrder(t *testing.T) {
+ w := &fakeWindow{exists: true}
+ sys, quits := fakeSys(w)
+ after := func(d time.Duration) int32 { time.Sleep(d); return quits() }
+ drop := func(a *app) { a.windowClosed() } // the page's connection ends (it counts the page out)
+
+ // The window is already gone when its connection drops: quit at once, without waiting for a reload.
+ w.set(func(w *fakeWindow) { w.exists = false })
+ drop(windowApp(t, sys, 7))
+ if n := after(100 * time.Millisecond); n != 1 {
+ t.Fatalf("window gone first: %d quits within 100 ms, want 1", n)
+ }
+
+ // The connection drops first and the window goes a moment later.
+ w.set(func(w *fakeWindow) { w.exists = true })
+ drop(windowApp(t, sys, 7))
+ time.Sleep(40 * time.Millisecond)
+ w.set(func(w *fakeWindow) { w.exists = false })
+ if n := after(80 * time.Millisecond); n != 2 {
+ t.Fatalf("window gone after its page: %d quits, want 2 (before the reload wait)", n)
+ }
+
+ // A reload: the window stands and its page comes back within the wait.
+ w.set(func(w *fakeWindow) { w.exists = true })
+ a := windowApp(t, sys, 7)
+ drop(a)
+ time.Sleep(50 * time.Millisecond)
+ a.windows.Add(1)
+ if n := after(testGoneCheck + testGoneWait + 100*time.Millisecond); n != 2 {
+ t.Fatalf("a reload quit the program (%d quits)", n)
+ }
+
+ // The window stands but its page never comes back: quit after the window check and the reload wait.
+ drop(windowApp(t, sys, 7))
+ if n := after(testGoneCheck + testGoneWait/2); n != 2 {
+ t.Fatalf("quit before the reload wait was over (%d quits)", n)
+ }
+ if n := after(testGoneWait); n != 3 {
+ t.Fatalf("a page that never came back: %d quits, want 3", n)
+ }
+
+ // The window is not known (Linux, or not found yet): only the reload wait decides.
+ drop(windowApp(t, sys, 0))
+ if n := after(testGoneWait / 2); n != 3 {
+ t.Fatalf("no window known: quit before the reload wait (%d quits)", n)
+ }
+ if n := after(testGoneWait); n != 4 {
+ t.Fatalf("no window known: %d quits, want 4", n)
+ }
+ a = windowApp(t, sys, 0)
+ drop(a)
+ a.windows.Add(1) // reloaded
+ if n := after(testGoneWait + 100*time.Millisecond); n != 4 {
+ t.Fatalf("no window known, page back: %d quits, want 4", n)
+ }
+
+ // A window asked for meanwhile (from the tray, still loading) keeps the program.
+ a = windowApp(t, sys, 0)
+ drop(a)
+ a.opened.Add(1)
+ if n := after(testGoneWait + 100*time.Millisecond); n != 4 {
+ t.Fatalf("a window asked for meanwhile: %d quits, want 4", n)
+ }
+
+ // The program closed the window itself (minimised to the tray): not the X.
+ w.set(func(w *fakeWindow) { w.exists = false })
+ a = windowApp(t, sys, 7)
+ a.inTray.Store(true)
+ drop(a)
+ if n := after(testGoneWait + 100*time.Millisecond); n != 4 {
+ t.Fatalf("minimised to the tray: %d quits, want 4", n)
+ }
+}
+
+// Minimising sends the window to the tray; a close that did not happen must not keep a later X from quitting.
+func TestMinimiseToTray(t *testing.T) {
+ w := &fakeWindow{exists: true}
+ sys, quits := fakeSys(w)
+ waitFor := func(what string, cond func() bool) {
+ t.Helper()
+ for end := time.Now().Add(2 * time.Second); !cond(); time.Sleep(5 * time.Millisecond) {
+ if time.Now().After(end) {
+ t.Fatal("timed out waiting for " + what)
+ }
+ }
+ }
+ start := func() *app { // a window open, watched for being minimised
+ a := windowApp(t, sys, 0)
+ setApp(t, a.st, `{"minimizeToTray":true}`)
+ a.watching.Store(true)
+ go a.watchMinimise()
+ waitFor("the window to be found", func() bool { return a.winHandle.Load() == 7 })
+ return a
+ }
+
+ // It closes: the page's going is not the X.
+ a := start()
+ w.set(func(w *fakeWindow) { w.min = true })
+ waitFor("the close", func() bool { return w.closed() == 1 })
+ if !a.inTray.Load() {
+ t.Fatal("inTray not set")
+ }
+ a.windowClosed()
+ time.Sleep(testGoneWait + 100*time.Millisecond)
+ if quits() != 0 {
+ t.Fatal("minimising to the tray quit the program")
+ }
+
+ // The close is refused (the window stays, and the user brings it back): its X quits again.
+ w.set(func(w *fakeWindow) { w.exists, w.min, w.refuse, w.closes = true, false, true, 0 })
+ a = start()
+ w.set(func(w *fakeWindow) { w.min = true })
+ waitFor("the close", func() bool { return w.closed() == 1 })
+ time.Sleep(3 * testCloseFailed)
+ if !a.inTray.Load() {
+ t.Fatal("still minimised (it may be closing slowly): inTray must stay")
+ }
+ w.set(func(w *fakeWindow) { w.min = false }) // restored by the user
+ waitFor("inTray to clear", func() bool { return !a.inTray.Load() })
+ w.set(func(w *fakeWindow) { w.exists = false }) // the user's X
+ a.windowClosed()
+ waitFor("the quit", func() bool { return quits() == 1 })
+
+ // The close cannot be delivered at all: the window stays minimised and inTray is not left set.
+ w.set(func(w *fakeWindow) { w.exists, w.min, w.refuse, w.undelivered, w.closes = true, false, false, true, 0 })
+ a = start()
+ w.set(func(w *fakeWindow) { w.min = true })
+ time.Sleep(50 * time.Millisecond)
+ if a.inTray.Load() {
+ t.Fatal("inTray left set although the close never went out")
+ }
+}
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..9677b30
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,30 @@
+# MPRP documentation
+
+Start with the [README](../README.md) for what the program does and how to get it. The pages below go further.
+
+## Using it
+| Page | Read it for |
+|---|---|
+| [How it works](how-it-works.md) | the window and the menu, what shows on Discord, text lines, clean titles and covers, Fix a match, streams, privacy, and each player in detail |
+| [All settings](config.md) | every setting with its default, grouped by the window's tabs, and the ones kept only in `config.json` |
+| [Troubleshooting](troubleshooting.md) | problems by player and service, updates, where the settings are, uninstalling, reporting a problem |
+| [Security](../SECURITY.md) | every address the program connects to, what is kept on your computer, checking a download, reporting a security problem |
+
+## Working on it
+| Page | Read it for |
+|---|---|
+| [Contributing](../CONTRIBUTING.md) | the ground rules for every change, quick start, working on Windows |
+| [Development](development.md) | building, running a throwaway copy safely, the packages, how players are read, the engine, testing, CI |
+| [Maintaining](maintaining.md) | releasing, screenshots, previewing the README, downloading release files |
+| [How AI was used](ai.md) | who did what, how the work is checked, working with AI agents on it |
+| [AGENTS.md](../AGENTS.md) | the short guide for AI coding tools |
+
+## Why it is the way it is
+| Page | Read it for |
+|---|---|
+| [Decisions](decisions.md) | the product decisions, each with its reason |
+| [Roadmap](roadmap.md) | principles, what comes next, what the program leaves out on purpose, open decisions |
+| [Designs](design/settings-window.md) | the settings window's look, and the designs behind [Fix a match](design/fix-a-match.md) and [Text lines](design/presence-templates.md) |
+| [Research](research/discord-rich-presence.md) | what Discord's status card can show, and [immutable releases](research/immutable-releases.md) |
+
+The player logos in [players/](players/) have fixed addresses that every install fetches; they are not documentation.
diff --git a/docs/ai.md b/docs/ai.md
index f39f491..ce7186b 100644
--- a/docs/ai.md
+++ b/docs/ai.md
@@ -1,6 +1,6 @@
# How AI was used
-MPCvibedRPC is AI-generated ("vibe coded"). This page says what that means here, so you can judge it for yourself.
+MPRP is AI-generated ("vibe coded"). This page says what that means here, so you can judge it for yourself.
## Who did what
- **The AI** (Claude, by Anthropic) wrote the code, the tests, the CI workflows and the
@@ -51,4 +51,4 @@ What has held up while developing this project with AI agents (any tool, any mod
- macOS and Linux are mostly tested on CI runners, not on real desktops; Stremio has only been tested against fakes
built from its source code.
- AI-written code can be wrong in ways tests do not catch. If you find such a case, please
- [open an issue](https://github.com/CptPakundo/MPCvibedRPC/issues/new/choose).
+ [open an issue](https://github.com/CptPakundo/MPRP/issues/new/choose).
diff --git a/docs/config.md b/docs/config.md
index 7b0da31..042b617 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -1,15 +1,15 @@
-# Settings reference
+# All settings
Every setting with its default and what it does, grouped by the settings window's tabs. The window covers the main
ones and saves them as you change them. The others go in `config.json`:
-- Windows: `%LOCALAPPDATA%\MPCvibedRPC\config.json`
-- macOS: `~/Library/Application Support/MPCvibedRPC/config.json`
-- Linux: `~/.local/share/MPCvibedRPC/config.json`
+- Windows: `%LOCALAPPDATA%\MPRP\config.json`
+- macOS: `~/Library/Application Support/MPRP/config.json`
+- Linux: `$XDG_DATA_HOME/MPRP/config.json`, else `~/.local/share/MPRP/config.json`
`config.json` is JSON: use the names below and write values as the Default column does, for example
`{"artworkSources": ["imdb", "tvmaze"]}`. The settings of the General tab go inside `"app"`:
`{"app": {"checkUpdates": false}}`. Anything missing falls back to its default. Settings marked *(config.json only)*
-are not in the window.
+are not in the window. Every other page is listed in the [docs index](README.md).
## General
@@ -22,8 +22,8 @@ These live under `"app"` in `config.json`. The update switches and **Check now**
| `minimizeToTray` | `true` | **Minimize to the tray** (Windows): minimizing the window closes it, and the program stays in the tray. Off: it minimizes to the taskbar. Either way, the window's X quits the program (on macOS it closes to the menu bar). |
| `startPresence` | `true` | **Show on Discord when the app opens.** Otherwise it waits until you press Show on Discord. |
| `checkUpdates` | `true` | **Check for updates automatically:** as the program starts, then every six hours ([how updates work](troubleshooting.md#updates)). |
-| `autoUpdate` | `true` | **Install updates automatically** (Windows and Linux, with `checkUpdates` on): a found update installs itself once nothing is playing and no settings window is open (the program runs minimised to the tray or started at login; closing the window quits it on Windows and Linux). Off: the window and a tray notice offer it, and **Install** installs it. |
-| `updateRepo` | `"CptPakundo/MPCvibedRPC"` | *(config.json only)* The GitHub repository (`owner/repo`) that publishes releases. A release is only installed when it carries a `.sha256` checksum file for the download; otherwise the window links to its page. |
+| `autoUpdate` | `true` | **Install updates automatically** (Windows and Linux, with `checkUpdates` on): a found update installs itself once nothing is playing and no settings window is open (the program runs minimised to the tray or started at login; closing the window quits it on Windows and Linux). Off: the window and a notification offer it, and **Install** installs it. |
+| `updateRepo` | `"CptPakundo/MPRP"` | *(config.json only)* The GitHub repository (`owner/repo`) that publishes releases. A release is only installed when it carries a `.sha256` checksum file for the download; otherwise the window links to its page. |
## Players
@@ -53,7 +53,7 @@ folder on macOS and Linux. A full path or `~/...` is used as it is. See
| Setting | Default | What it does |
|---|---|---|
| `activityType` | `"watching"` | **Style.** `"watching"`: "Watching ..." with a real progress bar. `"playing"`: the classic "Playing ..." with an elapsed-time counter. |
-| `titleAsName` | `true` | **Show the title as the activity name:** "Watching " instead of "Watching Media Player Classic". |
+| `titleAsName` | `true` | **Show the title as the activity name:** "Watching " instead of "Watching MPRP". |
| `streamTitle` | `"auto"` | **Show the title on my streams:** `"auto"` while Discord shares your screen, `"always"`, or `"off"`. [Details](#streamtitle). |
| `textProgressBar` | `true` | **Text progress bar while paused or streaming:** `▰▰▰▱▱▱ 12:34 / 45:00` while paused; `▰▰▰▱▱▱ of 45:00` (and the speed when it is not 1x) in the stream form. Sent again each time the bar fills another cell. |
| `progressWidth` | `12` | *(config.json only)* Width of that text bar (0 to 40). |
@@ -61,7 +61,9 @@ folder on macOS and Linux. A full path or `~/...` is used as it is. See
| `richInfo` | `true` | **Genres, rating and director** on the extra lines. `false` leaves just the year or episode. |
| `linkButton` | `true` | **Link to the title's page** (IMDb, AniList, ...): a "View on ..." button, clickable text lines and cover, a second button when there is another page, and the player's logo linking its site. If Discord refuses these links, they are left out from then on. |
| `letterboxdLink` | `false` | **Link to Letterboxd when it has the title:** with `linkButton` on, the button and lines open the Letterboxd page instead. Asks letterboxd.com once per title (by its IMDb id, or a film's TMDB id); the answer is kept with the cover. |
-| `episodeInDetails` | `false` | **Also show S01E02 in the title line** (Discord already shows a badge when the card is expanded). |
+| `textLines` | `"standard"` | **Text lines:** the two lines under the title, and a film's cover text. `"standard"` (the usual lines), `"short"`, `"detailed"` or `"custom"` (`customLines`). [Details](#textlines). |
+| `customLines` | `{}` | **Custom** text lines: `episodeDetails` and `episodeState` (an episode's first and second line), `movieDetails`, `movieState` and `movieCover` (a film's lines and cover text), for example `{"episodeDetails": "{code} · {episodeTitle}"}`. A missing line is empty; a missing cover text is `{title}[ ({year})]`. [Details](#textlines). |
+| `episodeInDetails` | `false` | **Also show S01E02 in the title line** (Discord already shows a badge when the card is expanded). Only with Standard text lines. |
### streamTitle
- `"auto"`: the stream form ("Playing ", so viewers see "Streaming ") only while Discord shares your
@@ -70,10 +72,29 @@ folder on macOS and Linux. A full path or `~/...` is used as it is. See
What the stream form looks like and how a share is detected: [On your streams](how-it-works.md#on-your-streams).
+### textLines
+The two text lines under the title while the title is the activity name, and a film's cover text (shown when you point
+at the cover):
+
+| Choice | Episode | Film |
+|---|---|---|
+| `"standard"` | `Sample Episode` / `Sample Arc · Drama, Comedy · ★ 8.3` | `2020 · Drama, Comedy` / `★ 7.1 · Dir. Sample Name` |
+| `"short"` | `S01E02 · Sample Episode` / nothing | `2020` / `Dir. Sample Name` |
+| `"detailed"` | `S01E02 · Sample Episode` / `Drama, Comedy · ★ 8.3 · on VLC media player` | `2020 · Drama, Comedy · 1:52:10` / `★ 7.1 · Dir. Sample Name · on VLC media player` |
+
+`"custom"` uses `customLines`, written with these placeholders: `{title}`, `{year}`, `{genres}`, `{rating}` (`★ 7.1`),
+`{director}` (`Dir. Sample Name`, films), `{player}`, `{length}`, and for episodes `{code}` (`S01E02`, or a special's own
+words), `{season}`, `{episode}`, `{episodeTitle}` and `{seasonName}`. A part in `[ ]` drops out when a placeholder in it
+is empty, a part between ` · ` separators that ends up empty is dropped with its separator, an unknown name stays as
+typed, and each line is cut to 128 characters. `richInfo` off empties `{genres}`, `{rating}` and `{director}`.
+
+Never shaped: the name ("Watching Sample Show"), the pause line, an episode's cover text (Discord turns it into the
+S1E2 badge), the stream form, a song, a hidden title, and the lines with `titleAsName` off or the Playing style.
+
## Titles & art
-The title read from the file name is looked up online. In the window, **Fix a match** holds `artworkAliases` and
-`artworkOverrides`, and **More** holds `tmdbApiKey` and `folderEpisodeNumbers`.
+The title read from the file name is looked up online. In the window, **Fix a match** holds `matchFixes`, and **More**
+holds `tmdbApiKey` and `folderEpisodeNumbers`.
| Setting | Default | What it does |
|---|---|---|
@@ -81,8 +102,9 @@ The title read from the file name is looked up online. In the window, **Fix a ma
| `catalogTitle` | `true` | **Use the catalog's spelling of titles**, including punctuation a file name can't hold. `false` keeps the title as read from the file name. |
| `animeTitles` | `"auto"` | **Anime titles**, for anime found on AniList: `"auto"` uses the AniList name (English or romaji) the file name resembles most; `"english"` or `"romaji"` always use that one; `"file"` keeps the file's spelling. |
| `useFolderName` | `true` | **Use the folder name when the file is just an episode number** (skipping `Season 1` style folders). Also names a Blu-ray or DVD from the folder that holds `BDMV` or `VIDEO_TS`, or from the disc's own title or label ([how](how-it-works.md#blu-ray-and-dvd)). |
-| `artworkAliases` | `{}` | **Search under another name**, for example `{"filename title": "Catalog Title"}`. |
-| `artworkOverrides` | `{}` | **Pin a cover image**, for example `{"some title": "https://example.com/poster.jpg"}`. |
+| `matchFixes` | `[]` | **Fix a match:** one fix per title or file, made in the window. Each has `match` (the title read from the file name, or with `"file": true` a file's exact name; a file fix wins), `entry` (a pinned IMDb, TMDB, TVmaze, AniList or Kitsu page) or `search` (another name to search under), `cover` (an image address instead of the catalog's cover), `seasonOffset` and `episodeOffset` (added to the numbers read from the file before the catalogs are asked), and `label` and `poster` (how the window describes the entry). [How it works](how-it-works.md#fixing-a-match). |
+| `artworkAliases` | `{}` | *(legacy)* "Search under another name" lines, such as `{"filename title": "Catalog Title"}`. Read once with `matchFixes` (each title becomes a fix); kept for a downgrade. |
+| `artworkOverrides` | `{}` | *(legacy)* "Pin a cover image" lines, such as `{"some title": "https://example.com/poster.jpg"}`. Read once with `matchFixes`; kept for a downgrade. |
| `tmdbApiKey` | `""` | **TMDB API key**, free at . TMDB is skipped unless this is set. |
| `folderEpisodeNumbers` | `false` | **Number episodes by their place in the season folder**, for files with a running production code, instead of the catalog's count. |
| `artworkSources` | `["tmdb", "imdb", "cinemeta", "tvmaze", "anilist", "kitsu", "wikipedia"]` | *(config.json only)* Cover sources, asked at the same time; the first in this list with an exact title match wins. |
@@ -130,20 +152,21 @@ If a title still has no cover, the log says what each source returned. Then add
| Setting | Default | What it does |
|---|---|---|
-| `clientId` | `"427863248734388224"` | **Discord application ID** (it holds the `mpc-hc` images below). For your own name and artwork, create an app at and paste its Application ID here. |
+| `clientId` | `"1575219115981934734"` | **Discord application ID**: the project's own application, named MPRP (an install that saved the former default, `427863248734388224`, uses this one). For your own name and artwork, create an app at and paste its Application ID here. |
| `pollInterval` | `5000` | **Check every (ms).** The status is only sent when something changes. mpv, IINA, Kodi and MPRIS players also report a pause, seek or new file at once. While Discord and the window are closed, a check only looks whether Discord has started ([Resting](how-it-works.md#resting-while-discord-is-closed)). |
| `plexJwt` | `false` | *(config.json only)* Sign in to Plex with its newer tokens: they last 7 days and are renewed in time with a key of this install's own (`plexKey`), as Plex's developer documentation describes. Off: the long-lived token Plex still accepts. Takes effect at the next **Sign in to Plex**. |
**Restore defaults** and **Open settings folder** are under **Advanced > Maintenance**.
### Discord art assets
-*(config.json only.)* These are uploaded to the Discord application whose `clientId` you use.
+*(config.json only.)* Keys of images uploaded to a Discord application of your own (`clientId`). The default
+application has none: covers and player logos are sent as addresses.
| Setting | Default | What it does |
|---|---|---|
| `largeImageKey` | `"mpc-hc"` | Shown when no cover is found. While it is the default, players with a logo in `docs/players` (mpv, VLC, IINA, PotPlayer, Kodi, SMPlayer, Plex, Stremio, Jellyfin, Emby) show that logo instead. |
| `smallImageKey` | `"mpc-hc"` | Small corner icon when a cover is shown. While it is the default, players outside the MPC family show their own logo there, or none. |
-| `appName` | `"Media Player Classic"` | Name used when `titleAsName` is off, and the text of the images. While it is the default, other players are named as themselves (mpv, VLC media player, Plex, ...). |
+| `appName` | `"Media Player Classic"` | The images' hover text, and the name the window's preview shows for an application of your own (Discord shows the application's name). While it is the default, other players are named as themselves (mpv, VLC media player, Plex, ...). |
### File-name cleanup
*(config.json only.)* Smart mode (the default) strips release junk (BluRay, 1080p, x265, HDR, audio tags, release
@@ -158,8 +181,12 @@ groups) and finds titles, seasons and episodes. Basic mode only applies the swit
## Written by the program
-Not typed: the sign-ins on the **Players** tab and the window write these. The sign-ins are kept in `config.json` as
-plain text, as other apps keep theirs; the window and **Copy diagnostics** never show them (diagnostics only say
+Not typed: the sign-ins on the **Players** tab and the window write these. On Windows the sign-ins' tokens and keys
+(`plexToken`, `plexKey`, `stremioKey`, `jellyfinToken`) are kept encrypted with Windows' per-user DPAPI, as `dpapi:`
+and the encrypted bytes in base64: only the same user on the same computer can read them, and a value that cannot be
+decrypted (a `config.json` from another user or computer) counts as signed out; it stays in the file until a new
+sign-in or a sign-out replaces it. A plain value (macOS and Linux keep it that way) is read as it is, and on
+Windows encrypted at the next save. The window and **Copy diagnostics** never show them (diagnostics only say
whether you are signed in).
| Setting | Default | What it does |
diff --git a/docs/decisions.md b/docs/decisions.md
index b27364d..2b67fe6 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -7,6 +7,10 @@ roadmap; open questions are its [Open decisions](roadmap.md#open-decisions-the-m
## Behaviour
- **MPC-HC comes first.** It is the player the program was made for: anything new is added after it and must not
change how it behaves. *Why:* the people who use it with MPC-HC should never notice that other players arrived.
+- **The default Discord application is the project's own** (2026-11-25, from 0.9.60), named MPRP. An install that
+ saved the former default (the upstream project's "Media Player Classic") moves to it; an application the user made
+ stays. *Why:* every install depends on it, and the former one was not the project's to keep; it named only MPC and
+ held no image the program uses, so nothing on the card is lost.
- **Discord is only contacted once something plays** ("Discord on standby" until then). *Why:* nothing to show means
nothing to send, and an idle program should not hold a connection.
- **The window's X quits the program; minimizing sends it to the tray** (2026-11-20, from a user's wish).
@@ -104,7 +108,8 @@ roadmap; open questions are its [Open decisions](roadmap.md#open-decisions-the-m
the check goes out as the program starts. With no window open nothing is asked: the update installs itself as
above, though never in the first ten seconds after the start. *Why:* a line at the top and a button on a tab were
easy to miss; whoever has the window open can decide on the spot, and a program that has only just started cannot
- know yet whether something plays or a window is about to open.
+ know yet whether something plays or a window is about to open. No popup of its own opens without a window
+ (2026-11-25): every system shows a notification instead (an update is available, or one installed itself).
## Privacy
- **Copy diagnostics keeps titles and file names**, and leaves out folder paths, web address details, server names,
@@ -116,6 +121,10 @@ roadmap; open questions are its [Open decisions](roadmap.md#open-decisions-the-m
another user or computer cannot be read, so those sign-ins ask to be made again. macOS and Linux keep plain text;
the full system key store was not chosen. *Why:* it protects a copied or backed-up `config.json` for the price of
one standard-library call, with no new window or password.
+- **The secrets typed in the window stay plain text** (`vlcPassword`, `kodiPassword`, `tmdbApiKey`; 2026-11-25). *Why:*
+ the user types them and the window shows them back; VLC and Kodi keep the same passwords as plain text in their own
+ settings; only the sign-ins, which the user never sees, are worth taking from a copied file; and the recorded store
+ reference data (frozen) holds `tmdbApiKey` as typed.
- **The cover cache forgets a title 90 days after it was last played.** *Why:* the cache speeds up lookups, but it
must not turn into a list of everything ever watched.
- **Every online service can be switched off**, and one switch makes the program fully offline. *Why:* each lookup
@@ -129,6 +138,16 @@ roadmap; open questions are its [Open decisions](roadmap.md#open-decisions-the-m
comes back only if that code has to grow materially.
## Releases
+- **The program is called MPRP, "Media Player Rich Presence"** (2026-11-25; it was called MPCvibedRPC before). The
+ rename covers everything: the program, the repository and Go module, the release files, the data folder, the
+ run-at-login entry, the window's identity and the environment variables (`MPRP_*`). An install from before carries
+ over by itself at its first normal start: its data folder and run-at-login entry are moved to the new name (a start
+ switched off in Task Manager stays off; after an in-app update from the former version the folder moves at the
+ next start), and every release also publishes its program files under the former names, so copies that update
+ themselves find them, until the maintainer drops those names (`tools/ci/former-names.txt`). Going back to a version
+ from before the rename starts it with default settings and signed out: the data stays in the new folder, and the
+ next update to a current version uses it again. The upstream credit and MPC-HC's own names are unchanged. *Why:*
+ the program long since serves many players and services, not only the MPC family; the new name says what it is, and the maintainer wanted it to apply to everything.
- **Versions are three-part, and stay 0.9.x until 1.0.** *Why:* the updater compares three numbers, so a fix takes the next number.
- **The README shows GitHub's own download count** (2026-10-25); the project's exact count of people (without its own
downloads) stays on the `stats` branch ([how](development.md#ci)). The program itself never reports anything. *Why:*
diff --git a/docs/design/fix-a-match.md b/docs/design/fix-a-match.md
index 0fc335f..39d7962 100644
--- a/docs/design/fix-a-match.md
+++ b/docs/design/fix-a-match.md
@@ -1,7 +1,8 @@
# Fix a match: design proposal
-A proposal for redesigning the **Fix a match** setting (Titles & art), with the research behind it. It is not built
-yet; its [decisions](#decisions) are settled, and the work is listed in the roadmap's [Next up](../roadmap.md#next-up).
+A proposal for redesigning the **Fix a match** setting (Titles & art), with the research behind it. The first version is
+built (version 0.9.60) as described here, with the differences listed under [As built](#as-built); its
+[decisions](#decisions) are settled.
The window's look is described in [settings-window.md](settings-window.md): the dialog and the list follow it (neutral
greys, the blurple accent only on the selected row and the main button, no pills, capitals, stripes or shadows, short
help texts).
@@ -135,7 +136,7 @@ fix saved by a new version is not seen by an older one; the changelog says so.
not Wikipedia, Jikan or Bulbapedia; deduplicated; cached); page addresses resolved by ID so episode titles work from
the pinned entry; `Covers(entry)`; fixes still read before the `media.Junk` return; the offset applied where season
and episode reach the catalogs.
-3. `cmd/mpcvibedrpc` API: POST `match-search` and `match-covers`, each answer carrying a request number so the window
+3. `cmd/mprp` API: POST `match-search` and `match-covers`, each answer carrying a request number so the window
drops answers to older keystrokes; the status carries the read title, the file's base name, season, episode and the
closest results (no folders); the Tell the project text is built from the same data.
4. `internal/assets`: the dialog and the list replace the two text boxes; `why.go` says "Matched as you chose: ...".
@@ -156,7 +157,8 @@ text with no path; `TestPageScriptParses`.
- Offsets meet folder numbers and the frozen golden data. The parser is not touched, offsets apply after it, and 0 and
0 is the old path. `pickSeasonEntry`'s rules (the earliest entry wins) stay: an offset moves the number, not the
entry choice.
-- Saving restarts the engine (`ApplySettings`); check that the card does not blink. Next up 1 is the same work.
+- Saving makes the cover and title finder again (`ApplySettings`; `matchFixes` reaches `lookups`) and sends the status
+ again, without a restart; check that the card does not blink.
- A pinned page can disappear from its catalog. Fall back to searching the read title, with a WARN line.
## Decisions
@@ -167,3 +169,15 @@ program never sends anything itself).
2. **Sharing.** "Opt-in ability to Tell the project." The user prepares, copies and posts the report.
3. **Covers.** "Other catalogs' covers from the start." The cover step offers them in the first version.
4. **Offsets.** "In the first version." A season and episode offset per fix.
+
+## As built
+Where the first version (0.9.60) differs from the plan above:
+- **The dialog's first results** come from a search of the read title as the dialog opens (mostly answered from the
+ request cache the lookup filled), not from `a.closest`, which keeps only names and no covers or pages.
+- **Two more fields per fix**, `label` and `poster`: how the window describes the pinned entry and its cover in the
+ list, without asking the catalog again.
+- **The legacy lines** act as before even before they are written as fixes: while config.json has no `matchFixes`,
+ the maps are read as fixes (`core.Config.Fixes`). The window no longer shows the two text boxes, but the store still
+ takes and checks them, as its recorded tests expect.
+- **A pinned IMDb page** is read from IMDb's suggestions, else Cinemeta, else TVmaze (shows), whichever is on; a
+ catalog that does not answer is asked again later rather than replaced by a search.
diff --git a/docs/design/presence-templates.md b/docs/design/presence-templates.md
index 7c5222b..a3e602b 100644
--- a/docs/design/presence-templates.md
+++ b/docs/design/presence-templates.md
@@ -1,7 +1,7 @@
# Text lines: design proposal
-A proposal for "Presence templates: a user-written layout of the status lines", with the research behind it. It is
-not built yet; its [decisions](#decisions) are settled, and the work is in the roadmap's [Next up](../roadmap.md#next-up). The window's look follows
+A proposal for "Presence templates: a user-written layout of the status lines", with the research behind it. The
+first version is built (version 0.9.60), with the differences listed under [As built](#as-built); its [decisions](#decisions) are settled. The window's look follows
[settings-window.md](settings-window.md). In the window and the docs the feature is called **Text lines**, because
"template" and "presence" are not words the window uses.
@@ -105,7 +105,7 @@ They start filled with the lines of the choice that was on before. The cover tex
4. Spaces are trimmed, the line is cut to 128 and padded to two; an empty line is left out.
**Saving.** As everywhere, the change saves itself, but a text field saves when it loses focus or after a pause of a
-second, not on each key: a save restarts the run (see Risks).
+second, not on each key: each save sends the status again (see Risks).
**What it touches.** Genres, rating and director still empties `{genres}`, `{rating}` and `{director}` when off. "Also
show S01E02 in the title line" only applies to Standard and hides itself for the others, because the other choices
@@ -153,8 +153,8 @@ included). **Later:** a music line (`{title}` only, for "Listening to"); text li
with "Show the title as the activity name" off.
**Risks.**
-- A save restarts the engine and reconnects to Discord (roadmap Next up 1). The save on blur or pause limits it; Next up
- 1 removes it.
+- Each save sends the status again (no restart: `ApplySettings` redoes what a setting reaches), and Discord takes about
+ five changes in 20 seconds. The save on blur or pause limits it.
- A custom second line can hide what the badge shows or repeat it: the help says so through the sample, not a warning.
- A later change to Standard does not move custom lines with it: custom lines are the user's.
- Users can write odd lines. That is the feature; the 128 cut and the empty-line rule keep Discord from refusing them.
@@ -167,3 +167,12 @@ Settled by the maintainer on 2026-11-25; the first version is part of version 0.
3. **Missing values.** "[ ] sections plus dropped separators."
4. **Value format.** "With today's marks": `★ 7.1`, `Dir. Sample Name`.
5. **Presets.** "Standard, Short, Detailed."
+
+## As built
+Where the first version (0.9.60) differs from the plan above:
+- **The Playing style keeps today's lines.** Without the stream form the Playing style has no title in its name (it is
+ "Playing MPRP" with the title as its first line), so it is the same case as "Show the title as the
+ activity name" off: text lines would remove the title.
+- **Custom starts from the choice before** only while its lines are empty; lines written earlier are kept.
+- **The shared table** is `internal/core/testdata/lines.json`; the page's test (`TestPageBehaviour`) runs it through the
+ page's own code.
diff --git a/docs/development.md b/docs/development.md
index 155032b..22a3b12 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -1,6 +1,6 @@
# Development
-How MPCvibedRPC is built, tested and kept working. For using it, see the [README](../README.md); for the rules that
+How MPRP is built, tested and kept working. For using it, see the [README](../README.md); for the rules that
apply to every change, [CONTRIBUTING.md](../CONTRIBUTING.md) (and [AGENTS.md](../AGENTS.md) for AI tools); for
releasing and screenshots, [maintaining.md](maintaining.md).
@@ -14,7 +14,7 @@ Terms these docs use:
| standby | "Discord on standby": showing is on, but nothing plays yet, so Discord has not been contacted. |
| resting | Discord is closed and no settings window is open: a check only looks whether Discord has started. |
| golden data | Recorded reference outputs in `internal/*/testdata/*.gz` that the parsers and lookups are checked against. Frozen: never regenerate it. |
-| throwaway copy | A copy of the program run with a data folder of its own (`MPCRPC_HOME`), so it cannot touch an installed copy. See [Running the program safely](#running-the-program-safely). |
+| throwaway copy | A copy of the program run with a data folder of its own (`MPRP_HOME`), so it cannot touch an installed copy. See [Running the program safely](#running-the-program-safely). |
| smoke test | CI starts the real built program on its own system and checks it from outside (`tools/ci/smoke.ps1`, `smoke-unix.sh`). |
| live jobs | CI jobs that install real players and media servers on a throwaway runner and run the engine against them. |
| canary | The weekly CI run against the newest players, server images and catalog services; it opens an issue when something outside changed. |
@@ -26,15 +26,15 @@ version in `go.mod` (the `go` line) and no internet beyond that.
Windows (the resource step adds the icon and version details; it is optional):
- go run ./tools/mkrsrc -version X.Y.Z -out cmd/mpcvibedrpc/rsrc_windows_amd64.syso
- go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=X.Y.Z" -o MPCvibedRPC.exe ./cmd/mpcvibedrpc
+ go run ./tools/mkrsrc -version X.Y.Z -out cmd/mprp/rsrc_windows_amd64.syso
+ go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=X.Y.Z" -o MPRP.exe ./cmd/mprp
`-H=windowsgui` makes it a windowed program, so no console flashes up. You can build it from any OS
(`GOOS=windows`).
Linux:
- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=X.Y.Z" -o MPCvibedRPC-linux-amd64 ./cmd/mpcvibedrpc
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=X.Y.Z" -o MPRP-linux-amd64 ./cmd/mprp
macOS: the app is built on a Mac **with cgo** by `tools/ci/package-macos.sh VERSION OUTDIR` (`CGO_ENABLED=1`; both
processor types in one program, the app icon, an ad-hoc signature, a zip). The menu bar icon and the settings window
@@ -46,7 +46,7 @@ Flags of the program:
| Flag | What it does |
|---|---|
| `--background` | Start in the tray. |
-| `--home ` | A data folder of its own, like `MPCRPC_HOME`. |
+| `--home ` | A data folder of its own, like `MPRP_HOME`. |
| `--after-update` | Set on the copy an update started. |
| `--update-failed` | Set on the old copy that an update put back (see [Updates](#updates)). |
| `--version` | Print the version and exit. |
@@ -56,14 +56,14 @@ Flags of the program:
Never touch a real setup while testing ([the rule](../CONTRIBUTING.md#ground-rules)). Use throwaway copies and the
fakes below.
-- **A throwaway copy.** `MPCRPC_HOME=` (or `--home `) gives a copy its own data folder **and
+- **A throwaway copy.** `MPRP_HOME=` (or `--home `) gives a copy its own data folder **and
its own autostart value name**, so it never touches an installed copy. A config such as
`{"app":{"openWindow":false,"startPresence":false,"checkUpdates":false,"welcomeSeen":true}}` keeps it quiet.
- **Keep `checkUpdates` off in test copies.** With it on, a copy without a window installs what its update server
offers ten seconds after its start and shows a real operating-system notification. To try the update dialog, start
with it off, open the page, then switch it on there (that checks at once), or trigger a check through
`api/update-check`.
-- **The page.** The API port and token are in `/ipc.json`; the page is
+- **The page.** The API port and token are in `/ipc.json`; the page is
`http://127.0.0.1:/?t=`. (The program itself opens its window with a one-time code, `?c=`, so the token
is not on the browser's command line; the page keeps the token in `sessionStorage` and takes it out of its address.)
To test window states without Discord, override `window.fetch` for `/api/status` (or `/api/plex*`,
@@ -73,21 +73,22 @@ fakes below.
`vlcPassword` empty.
- **Resting.** A throwaway copy rests whenever Discord is closed and its window is closed (no player is asked then).
To test players with Discord closed, keep the window open.
-- **Update checks.** `MPCRPC_UPDATE_API=http://127.0.0.1:` with `tools/ci/fake-http.ps1` (on CI). On a Windows
+- **Update checks.** `MPRP_UPDATE_API=http://127.0.0.1:` with `tools/ci/fake-http.ps1` (on CI). On a Windows
PC its HttpListener may be refused without admin rights; a small Go server in a scratch folder can serve the same
three answers.
-- **Other variables.** `MPCRPC_BROWSER=none` opens no window (tests, CI); any other value names the browser to show
- the window in (one that understands `--app`). `MPCRPC_FOREGROUND=1` keeps a macOS copy from handing over to a
- detached one.
+- **Other variables.** `MPRP_BROWSER=none` opens no window (tests, CI); any other value names the browser to show
+ the window in (one that understands `--app`). `MPRP_FOREGROUND=1` keeps a macOS copy from handing over to a
+ detached one. Each `MPRP_*` variable that is not set takes the value of its former name (`MPCRPC_*`, listed in
+ `core.FormerEnv`): a copy of the former version starts the copy it updated itself to with its own environment.
- **Portable players.** Use portable builds in a scratch folder and verify their published checksums: MPC-QT
(`portable.txt`), MPC-BE (an ini next to the exe), mpv (`portable_config\`), VLC (a `portable\` folder next to
`vlc.exe`; start it with `--no-qt-privacy-ask`, or a first-run dialog keeps it from closing normally). Check
`%APPDATA%`, `%LOCALAPPDATA%` and `HKCU\Software` afterwards. Make test videos with mpv's encoder from `lavfi` test
sources, with generic names.
- **Accounts.** Never sign in to a real account ([the rule](../CONTRIBUTING.md#ground-rules)). Every reader has fakes:
- Plex in `internal/plex`, `cmd/mpcvibedrpc/plex_test.go` and `internal/engine/plex_test.go`; Stremio in
- `internal/stremio`, `cmd/mpcvibedrpc/stremio_test.go` and `internal/engine/rest_test.go`; Jellyfin / Emby in
- `internal/jellyfin`, `cmd/mpcvibedrpc/jellyfin_test.go` and `internal/engine/jellyfin_test.go`. A small fake server on
+ Plex in `internal/plex`, `cmd/mprp/plex_test.go` and `internal/engine/plex_test.go`; Stremio in
+ `internal/stremio`, `cmd/mprp/stremio_test.go` and `internal/engine/rest_test.go`; Jellyfin / Emby in
+ `internal/jellyfin`, `cmd/mprp/jellyfin_test.go` and `internal/engine/jellyfin_test.go`. A small fake server on
127.0.0.1 can drive the window's sign-in in a throwaway copy (keep showing on Discord off).
- **Leave nothing running.** Quit test copies, stop only processes you started, delete scratch tests before a full
test run, and check the real data folders afterwards.
@@ -97,28 +98,28 @@ These skip unless their variable is set. CI sets them for its throwaway players
| Test | Variables | What it does |
|---|---|---|
-| `TestLivePlayer` (`internal/engine`) | `MPCRPC_LIVE_PLAYER` (the name shown: mpv, IINA, VLC, Celluloid, Plex, ...), `MPCRPC_LIVE_TITLE` | Runs the engine against a real player, with the test's own fake Discord. |
-| | `MPCRPC_LIVE_PORT`, `MPCRPC_LIVE_MPV_PIPE`, `MPCRPC_LIVE_IINA_PIPE` | The MPC port and the mpv / IINA pipe to ask. |
-| | `MPCRPC_LIVE_VLC_PASSWORD`, `MPCRPC_LIVE_VLC_PORT` | VLC's web interface. |
-| | `MPCRPC_LIVE_KODI_PASSWORD`, `MPCRPC_LIVE_KODI_ADDRESS` | Kodi's web server (the address is optional). |
-| | `MPCRPC_LIVE_PLEX_ADDRESS`, `MPCRPC_LIVE_PLEX_TOKEN` | A Plex server. |
-| | `MPCRPC_LIVE_JELLYFIN_ADDRESS`, `_USER`, `_PASSWORD` | Signs in to a Jellyfin or Emby server with the password. |
-| | `MPCRPC_LIVE_EVENTS` (`pipe`, `kodi` or `mpris`) | **Changes the player's state:** pauses the real player and wants the pause shown at once from the player's own event, then resumes it. |
-| `TestLiveJellyfin` (`internal/jellyfin`) | `MPCRPC_LIVE_JELLYFIN_ADDRESS`, `_USER`, `_PASSWORD`, `_PRODUCT` (`Jellyfin` or `Emby`), `MPCRPC_LIVE_TITLE` | Signs in to a real server (a wrong password first, then the password, and Quick Connect on Jellyfin), follows what the user plays, signs out. |
-| `TestLivePotPlayer` (`internal/potplayer`, Windows) | `MPCRPC_LIVE_POTPLAYER=1` | Asks a real PotPlayer that plays a local file and checks that it sends the file's path. |
-| `TestLiveCatalogs` (`internal/artwork`) | `MPCRPC_LIVE_CATALOGS=1` | One long-known title per keyless catalog, through the program's own search and episode code (the canary; the real titles are kept in that file). |
-| `TestAutostartRegistryRoundTrip` (`internal/winsys`, Windows) | `MPCRPC_TEST_REGISTRY=1` | **Touches the real setup:** writes a real `HKCU\...\Run` value (for a throwaway data folder's value name, never the plain `MPCvibedRPC` one) and removes it again. |
-
-Example: `MPCRPC_LIVE_PLAYER=mpv MPCRPC_LIVE_TITLE="Sample Movie" go test -count=1 -run TestLivePlayer -v ./internal/engine`
+| `TestLivePlayer` (`internal/engine`) | `MPRP_LIVE_PLAYER` (the name shown: mpv, IINA, VLC, Celluloid, Plex, ...), `MPRP_LIVE_TITLE` | Runs the engine against a real player, with the test's own fake Discord. |
+| | `MPRP_LIVE_PORT`, `MPRP_LIVE_MPV_PIPE`, `MPRP_LIVE_IINA_PIPE` | The MPC port and the mpv / IINA pipe to ask. |
+| | `MPRP_LIVE_VLC_PASSWORD`, `MPRP_LIVE_VLC_PORT` | VLC's web interface. |
+| | `MPRP_LIVE_KODI_PASSWORD`, `MPRP_LIVE_KODI_ADDRESS` | Kodi's web server (the address is optional). |
+| | `MPRP_LIVE_PLEX_ADDRESS`, `MPRP_LIVE_PLEX_TOKEN` | A Plex server. |
+| | `MPRP_LIVE_JELLYFIN_ADDRESS`, `_USER`, `_PASSWORD` | Signs in to a Jellyfin or Emby server with the password. |
+| | `MPRP_LIVE_EVENTS` (`pipe`, `kodi` or `mpris`) | **Changes the player's state:** pauses the real player and wants the pause shown at once from the player's own event, then resumes it. |
+| `TestLiveJellyfin` (`internal/jellyfin`) | `MPRP_LIVE_JELLYFIN_ADDRESS`, `_USER`, `_PASSWORD`, `_PRODUCT` (`Jellyfin` or `Emby`), `MPRP_LIVE_TITLE` | Signs in to a real server (a wrong password first, then the password, and Quick Connect on Jellyfin), follows what the user plays, signs out. |
+| `TestLivePotPlayer` (`internal/potplayer`, Windows) | `MPRP_LIVE_POTPLAYER=1` | Asks a real PotPlayer that plays a local file and checks that it sends the file's path. |
+| `TestLiveCatalogs` (`internal/artwork`) | `MPRP_LIVE_CATALOGS=1` | One long-known title per keyless catalog, through the program's own search and episode code (the canary; the real titles are kept in that file). |
+| `TestAutostartRegistryRoundTrip` (`internal/winsys`, Windows) | `MPRP_TEST_REGISTRY=1` | **Touches the real setup:** writes a real `HKCU\...\Run` value (for a throwaway data folder's value name, never the plain `MPRP` one) and removes it again. |
+
+Example: `MPRP_LIVE_PLAYER=mpv MPRP_LIVE_TITLE="Sample Movie" go test -count=1 -run TestLivePlayer -v ./internal/engine`
## Where things are
-### The program: `cmd/mpcvibedrpc`
+### The program: `cmd/mprp`
| File | Job |
|---|---|
| `main.go` | flags, single instance, `var version` |
| `app.go` | the `app` type: start-up and quit order |
-| `api.go` | the local API handlers (`state`, `status`, `save`, `reset`, `start`, `stop`, `mpc-web`, `diagnostics`, `update-*`, `quit`, ...) |
+| `api.go` | the local API handlers (`state`, `status`, `save`, `reset`, `start`, `stop`, `player-setup`, `diagnostics`, `update-*`, `quit`, ...) |
| `update.go` | update checks, install, automatic installs, the hand-over (`handOverTo`) |
| `selfcheck.go` | **Help > Run a check** (its lines never hold a title) |
| `window.go` | the window's X quits; minimizing sends it to the tray (`minimizeToTray`) |
@@ -132,11 +133,12 @@ Example: `MPCRPC_LIVE_PLAYER=mpv MPCRPC_LIVE_TITLE="Sample Movie" go test -count
### Packages: `internal/`
| Package | Job |
|---|---|
-| `engine` | the check loop: asks the players, builds and sends the activity, pause clearing, hide rules, preview, status for the window |
+| `engine` | the check loop: asks the players, builds and sends the activity, pause clearing, hide rules, preview, settings changes without a restart (`apply.go`), status for the window |
| | `engine.go` types, Start/Stop, Status · `players.go` `fetchPlayer` and its `picker` · `tick.go` · `discord.go` · `events.go` player events · `remote.go` the Plex, Stremio and Jellyfin watchers, resting · `folder.go` the folder listing for `folderEpisodeNumbers` (read once per file, again when the folder changed) · `disc.go` a disc's own name at a drive's root (`bdmt_*.xml`, the volume label) · `stats.go` `stats.json`, counts only (taken under `e.mu`, written after it is released) |
| `core` | settings and defaults (`config.go`), file-name parsing (`parse.go`), the activity (`activity.go`), preview, privacy rules, catalog services (`sources.go`), every other outside address (`hosts.go`), player logos (`icons.go`), titles written like file names (`names.go`) |
| `mpvipc`, `pipe` | mpv JSON IPC (mpv, MPC-QT, IINA); named pipes on Windows, Unix sockets elsewhere (shared with `discord`) |
-| `mpris`, `dbus` | Linux players through MPRIS (an allowlist of video players) and their signals (`watch.go`); a minimal D-Bus client; `dbus/dbustest` is a fake bus |
+| `mpris`, `dbus` | Linux players through MPRIS (an allowlist of video players) and their signals (`watch.go`); a minimal D-Bus client (`Receive` reads a connection in the background, for calls and signals at once); `dbus/dbustest` is a fake bus |
+| `notify` | Linux: the update notices through the desktop's notification service (`org.freedesktop.Notifications` on the session bus), with the logo as pixels (the `image-data` hint); a click calls back to open the window |
| `vlchttp` | VLC's web interface, read-only |
| `potplayer` | PotPlayer (Windows): window messages from its control header `InternalSimpleCmd.h`, read-only |
| `kodi` | Kodi's JSON-RPC and its notifications on TCP 9090 (`watch.go`), read-only |
@@ -149,11 +151,12 @@ Example: `MPCRPC_LIVE_PLAYER=mpv MPCRPC_LIVE_TITLE="Sample Movie" go test -count
| `proc` | starting a helper process hidden (Windows) or detached (`Detach`, `DetachVisible`: the window's browser, the macOS `--serve` copy) |
| `discord` | Discord's local IPC protocol |
| `artwork`, `jsre` | catalog lookups and episode titles; a regex engine with JavaScript semantics that the matching rules rely on |
-| `store`, `jsonx` | `config.json`, the window's layout (`schema.go`), validation; a JSON reader/writer that keeps key order and unknown keys and prints numbers like JavaScript |
+| `store`, `jsonx` | `config.json`, the window's layout (`schema.go`), validation; carrying an install's data folder over from the program's former name (`move.go`); a JSON reader/writer that keeps key order and unknown keys and prints numbers like JavaScript |
| `server`, `assets` | the local API on 127.0.0.1 (per-launch token, host check, CSP); the page (`ui.html`, `ui.css`, `ui.js`, embedded; its look: [design/settings-window.md](design/settings-window.md)) and `changelog.json` |
| `winsys` | the operating system; see the next table |
| `diag` | **Copy diagnostics**: keeps titles and file names, leaves out folder paths, URL paths and queries, server names, sign-ins, keys and the Never show list |
| `updater` | GitHub release check, download, checksum, swap and restore of the program file |
+| `logo` | the program's icon (a play triangle over a progress bar), drawn in whole numbers so every system makes the same pixels: `tools/mkico` and the macOS menu bar (`Template`) use it |
`internal/winsys`, by topic. The macOS and Linux parts live in untagged files where possible, so their logic is tested
on every system.
@@ -162,21 +165,21 @@ on every system.
|---|---|
| `tray.go` (`TrayOptions`), `tray_windows.go` | the tray (Windows) |
| `run.go` | helper commands without a console, the running players, system details for diagnostics |
-| `macapp_darwin.go` | macOS (cgo only): the menu bar icon and the settings window (WebKit) |
+| `macapp_darwin.go` | macOS (cgo only): the menu bar icon, the settings window (WebKit) and the notifications (`UNUserNotificationCenter`, only as an app bundle) |
| `window.go`, `browser*.go` | the window's browser, opening a URL or folder |
-| `taskbar_windows.go` | the browser window's taskbar button gets the program's name, icon and start command (set from outside once it appears) |
-| `autostart*.go` | start at login: the registry's Run key, a LaunchAgent, XDG autostart (`autostart_unix.go`) |
+| `taskbar_windows.go` | the browser window's taskbar button gets the program's name, icon and start command (set from outside: from the first window on, a hook thread gives every taskbar window of a browser process that uses the window profile the identity and the built-in icon whenever it appears, and keeps the icon on it, through the shell hook and WinEvents, which it listens to only while a settings window is there or coming; it logs when the window first has the icon and what failed) |
+| `autostart*.go` | start at login: the registry's Run key, a LaunchAgent, XDG autostart (`autostart_unix.go`), and carrying an entry of the former name over (`MigrateAutoStart`) |
| `single_*.go` | single instance (mutex, file lock) |
-| `mpcsetup.go` (`EnableMpcWebInterface`), `setup_unix.go`, `mpvconf.go`, `vlcconf.go` | **Set up the player connection** |
+| `playersetup.go` (`SetUpPlayers`), `setup_unix.go`, `mpvconf.go`, `vlcconf.go` | **Set up the player connection** |
### Tools and docs
| Path | Job |
|---|---|
| `tools/mkrsrc` | exe resources (version info, icon, DPI manifest) |
-| `tools/mkico` | the icon generator (`-icns`: the macOS app icon; `-dot`: the update dot) |
+| `tools/mkico` | writes the icons from `internal/logo`: `internal/assets/icon.ico`, `icon-update.ico` (`-dot`), `docs/images/icon.png` (`-png`) and the macOS app icon (`-icns`); a test fails when a committed one is out of date |
| `tools/relnotes` | the release text, rendered from the changelog |
| `tools/doclinks` | only a test: every relative link and anchor in the Markdown files resolves |
-| `tools/screenshots` | `demo.js` for the README pictures ([Screenshots](maintaining.md#screenshots)) |
+| `tools/screenshots` | `take.js` takes the README pictures, with `demo.js`'s made-up playback ([Screenshots](maintaining.md#screenshots)) |
| `tools/downloads` | the project's own download count (on the `stats` branch; see [CI](#ci)) |
| `tools/ci` | the CI scripts; see the list below |
| `docs/` | user docs (`how-it-works.md`, `config.md`, `troubleshooting.md`), `roadmap.md`, `decisions.md`, `ai.md`, `design/` (design proposals and the window's look), `research/` (reports on Discord's card and on immutable releases), this file, `maintaining.md`, images and player logos (`players/`, named by `core/icons.go`; sources in `THIRD-PARTY-NOTICES.md`). **Every install fetches the logos from `docs/players/.png` on the `master` branch** (`PlayerIconBase`): never move, rename or delete a logo or rename `master`; adding one is fine |
@@ -188,6 +191,8 @@ on every system.
- `reproduce.sh`: rebuilds the programs from a tag and compares them byte for byte (`sums` and `same` give the release
workflow's comparison).
- `verify-release.ps1`: checks a release, first its draft, then the public one.
+- `former-names.txt`: the release file names (and environment variables) of the program's former name, which every
+ release still carries for copies installed before the rename, until the maintainer drops them.
- `version.sh`: the version from `main.go` (see [maintaining.md](maintaining.md#releasing)).
- `dev-download.sh`: every development download of a release file, recorded in the ledger.
- `canary-report.sh`: the canary's issue. `package-macos.sh`: the .app.
@@ -229,7 +234,7 @@ reads what plays.
- Tests set `Options.KodiEvents` and `Options.MPRISBus`, so no real Kodi or bus is reached.
### Plex
-- **Sign-in** (`cmd/mpcvibedrpc/plex.go`): a token through a plex.tv PIN the user approves in their browser; the
+- **Sign-in** (`cmd/mprp/plex.go`): a token through a plex.tv PIN the user approves in their browser; the
window never receives the token.
- **Server:** the watcher looks the chosen server up on plex.tv (`clients.plex.tv/api/v2/resources`, or uses
`plexAddress`) and checks `/identity` without the token. The token goes only to the server that answered with the
@@ -278,12 +283,14 @@ reads what plays.
- VLC 3 rounds `time` to whole seconds (position x length is used); VLC 4 uses a flat playlist.
- With the default app name, the tooltip names mpv and VLC as themselves, and the default corner icon (MPC's logo) is
left out for players outside the MPC family.
-- The default Discord application (`clientId`) was registered by the upstream project, not by this one: every install
- depends on it staying there. It holds only a few images (`default`, `pause_small`, `play_small`, `stop_small` and
- `mpcbe_logo`, checked 2026-11-21); the player logos, the MPC family's too, are fetched from `docs/players` (below).
+- The default Discord application (`clientId`, `core.DefaultClientID`) is the project's own, registered by the
+ maintainer and named MPRP: every install depends on it. Installs from before saved the former default, the upstream
+ project's application (`core.FormerClientID`); `store.settingsObj` reads it as the current one. The former
+ application held only a few images (`default`, `pause_small`, `play_small`, `stop_small` and `mpcbe_logo`, checked
+ 2026-11-21) and the new one none; the player logos, the MPC family's too, are fetched from `docs/players` (below).
### Set up the player connection
-`winsys.EnableMpcWebInterface`:
+`winsys.SetUpPlayers`:
- **MPC-HC, MPC-BE:** web interface on (registry and ini; they are closed and reopened after the user confirms), and
this-PC-only when the button switches it on.
- **mpv:** `input-ipc-server` in the `mpv.conf` it reads (a name the user set is kept and adopted).
@@ -292,7 +299,7 @@ reads what plays.
exit.
- **MPC-QT** needs nothing.
-On macOS and Linux (`winsys.enableUnix`):
+On macOS and Linux (`winsys.setUpUnix`):
- **mpv:** the full socket path in `~/.config/mpv/mpv.conf`.
- **IINA:** `enableAdvancedSettings` and an `input-ipc-server` row in `userOptions` through
`defaults write com.colliderli.iina` (an existing row is kept and adopted; IINA is not closed, the user reopens it).
@@ -307,6 +314,23 @@ stat elsewhere; never a connection) and no settings window holds `/api/alive` (`
(`winsys.TrimMemory`) hands memory back. A window opening calls `engine.Wake`. Tests get no resting unless they set
`MayRest`.
+**Settings changes** (`apply.go`, `ApplySettings`): the run goes on, and only what the changed settings reach is
+redone, so the status does not blink, the pause clock stays, and Discord's connection stays open. Each field of
+`core.Config` says its reach in a `reach` tag:
+
+| Reach | Redone | Settings |
+|---|---|---|
+| `check` | nothing: the next check reads it, and the status is sent again | the look (`activityType`, `titleAsName`, `streamTitle`, the progress bar, `pauseClearMinutes`, the file-name cleanup, `episodeInDetails`, `folderEpisodeNumbers`, `useFolderName`, the Discord art names), `pollInterval` |
+| `lookups` | the cover and title finder is made again (lookups under way end quietly) | every setting `internal/artwork` reads (the catalogs, sources, aliases, overrides, `tmdbApiKey`, `richInfo`, the links, episode titles), the catalog addresses, `hideTitle`, `hideFiles` |
+| `players` | the player watch and the Plex, Stremio, Jellyfin and Emby watchers start again | the players' ports, pipes and passwords, `mpris`, `plexAddress`, the sign-ins (`plexToken`, `stremioKey`, `jellyfinToken`) and the accounts they follow |
+| `discord` | the connection is let go (its status cleared); the next check connects again | `clientId` |
+| `none` | nothing | names for the window (`plexUser`, `plexServerName`, `jellyfinUserName`, `jellyfinServerName`), `plexJwt`, `plexKey` |
+
+The screen-share watch starts or stops when `streamTitle` turns to or from "auto". No setting restarts the run. Tests:
+`internal/engine/apply_test.go` (`TestSettingsChangeKeepsTheDiscordConnection`, `TestClientIDChangeReconnectsToDiscord`,
+and `TestSettingsReachWhatReadsThem`, which fails when `internal/artwork`, the watchers or the Discord login read a
+setting whose reach does not make them again).
+
**Clearing** (`tick.go`):
- A status counts as shown from the moment it is sent, also when Discord's answer does not come (it may have been
applied).
@@ -321,7 +345,9 @@ the cover finder and the API. The rules that keep them in step:
late cover, a send Discord did not take).
2. Only a change by the player restarts the pause limit or brings back a status cleared after a long pause.
3. Every place that takes `e.mu` again after asking Discord checks that its run is still the current one
- (`e.cur == r`) before it books anything.
+ (`e.cur == r`) before it books anything; a Discord answer also checks that its connection was not let go for new
+ settings meanwhile (`discGen`). A check that read settings older than the current ones sends nothing (`cfgGen`):
+ a title hidden a moment ago must not go out.
4. The clear after a long pause is booked when Discord took it, not before.
5. A send Discord did not take waits `retryAfter` (5 s, doubling to a minute) before the next try.
6. `basicMode` and `noLinks` hold for the file they were found out for (`modeKey`).
@@ -334,7 +360,7 @@ Tests: `internal/engine/state_test.go`. `TestStatusConverges` runs random orders
against the fakes and checks that Discord ends up showing exactly what the player's last state calls for. After a
change to the check loop, run it with more orders:
- MPCRPC_CONVERGE_SEEDS=500 go test -count=1 -run TestStatusConverges ./internal/engine
+ MPRP_CONVERGE_SEEDS=500 go test -count=1 -run TestStatusConverges ./internal/engine
## The stream title
`streamTitle` ("auto", "always", "off"): Discord names a stream after a Playing activity only, so the engine builds the
@@ -361,7 +387,7 @@ Playing form while Discord shares the screen ([users' view](how-it-works.md#on-y
- **Automatic install** (`autoUpdate`, on by default; Windows and Linux): at a quiet moment (`quietMoment`: nothing
shown on Discord, no settings window; never in the first ten seconds after the start or after a window was asked for,
`settle`). The new copy starts in the tray (`auto-updated` marker in the data folder) and says so once.
-- **Hand-over** (`handOverTo` in `cmd/mpcvibedrpc/update.go`): the old copy frees the window, tray, port and
+- **Hand-over** (`handOverTo` in `cmd/mprp/update.go`): the old copy frees the window, tray, port and
single-instance lock and waits for the new copy's `ipc.json`. If it does not come, it puts the old program file back,
writes `update-failed` (the version, which is not installed by itself again) and starts itself again with
`--update-failed`.
@@ -385,9 +411,11 @@ Playing form while Discord shares the screen ([users' view](how-it-works.md#on-y
log line, `diag`, and the repository description and topics. `TestPlayersAreNamedEverywhere` catches a missed text.
### A new setting
-A field with a `json` tag in `core.Config` and its default in `DefaultConfig()`; a `Field` in `store/schema.go` if it
-belongs in the window (int fields need Min/Max; `secret` for passwords and keys); a row in `docs/config.md` with the
-default in JSON form (`TestEverySettingIsDocumented`); `diag.summarise` if the value is private (shown as "(set)").
+A field with a `json` tag and a `reach` tag ([settings changes](#the-engine)) in the right group of `core.Config`
+(`Settings`, `Accounts` for what a sign-in writes, `Secrets` for its tokens and keys, `Hooks` for catalog addresses)
+and its default in `DefaultConfig()` (`TestEverySettingHasAReach`); a `Field` in `store/schema.go` if it belongs in the
+window (int fields need Min/Max; `secret` for passwords and keys); a row in `docs/config.md` with the default in JSON
+form (`TestEverySettingIsDocumented`); `diag.summarise` if the value is private (shown as "(set)").
Defaults that change behaviour for existing users need the maintainer's decision and a line in the release notes.
### A new catalog service
@@ -414,11 +442,17 @@ run a copy or a real player without touching an installed setup: [Running the pr
**Tests that tie texts to the code** (keep them passing; they fail when a doc falls behind):
- `TestEverySettingIsDocumented` (`internal/store`): every setting has its row and default in [config.md](config.md).
-- `TestPlayersAreNamedEverywhere` (`cmd/mpcvibedrpc`): every text that lists the players names them all.
+- `TestEverySettingHasAReach` and `TestSettingsReachWhatReadsThem` (`internal/engine`): every setting has a `reach`, and
+ the settings the cover finder, the watchers and the Discord login read make them again when they change.
+- `TestPlayersAreNamedEverywhere` (`cmd/mprp`): every text that lists the players names them all.
- `TestEveryHostIsListed` and `TestSecurityListsEveryHost` (`internal/core`): every outside address the code and the
page name is in `core.Hosts` or `core.Sources`, and `SECURITY.md` names each.
- `TestPageScriptParses` (`internal/assets`): `node --check` on `ui.js` (skips without Node.js).
-- `TestChangelog` (`cmd/mpcvibedrpc`): the newest changelog entry is the version in `main.go`.
+- `TestPageBehaviour` (`internal/assets`): runs `ui.js` in a small fake DOM with a stubbed `fetch`
+ (`testdata/page_test.js`): the saver, the status sync, Text lines and Fix a match; it also runs the shared text-lines
+ table (`internal/core/testdata/lines.json`, which `TestExpandFollowsTheSharedTable` runs through the program's own
+ code), so the page's sample and the card fill a line alike. Skips without Node.js.
+- `TestChangelog` (`cmd/mprp`): the newest changelog entry is the version in `main.go`.
- `tools/relnotes`'s test: the release text renders from `internal/assets/changelog.json`.
- `TestLinksResolve` (`tools/doclinks`): every relative link and `#anchor` in every Markdown file resolves (GitHub's
anchor rules; links to other websites are not followed).
@@ -438,7 +472,8 @@ run a copy or a real player without touching an installed setup: [Running the pr
folder under /tmp there (`sockDir`).
- Run `go test -race` somewhere that supports it (Linux CI) after concurrency changes.
- **Window script changes need the real page opened** ([how](#running-the-program-safely)): unit tests cover the
- server side only, and `TestPageScriptParses` only catches a script that does not parse.
+ server side, `TestPageScriptParses` only catches a script that does not parse, and `TestPageBehaviour` checks a
+ few behaviours in a fake DOM, not the look.
## CI
The workflows are in `.github/workflows/`. **CI is the only place macOS and Linux run for real**, so read those logs
@@ -497,7 +532,10 @@ A Go security fix means bumping the patch version in `go.mod` alone: every `setu
### Known flaky checks
These have failed without a code change; read the log, then re-run once:
-- The **Chocolatey Kodi download** in `players-windows` (TLS errors from its mirror). The canary uses the same job.
+- The **Chocolatey downloads** in `players-windows` (TLS errors from a mirror, seen for Kodi): `live-windows.sh` tries
+ each install three times, 30 seconds apart, so a failure that gets through has lasted over a minute. Each try counts
+ only when the program is really there afterwards (choco has answered success without it), and a final failure prints
+ the install log's relevant lines. The canary uses the same job.
- The macOS **IINA pause check** in `players` timed out once (5 s) and passed on a re-run.
- `TestEpisodeWithoutTitleIsAskedAgainWhilePlaying` (it counts sends) and two timing tests each failed once in a
full-suite run that came right after heavy work. Run the single test again before suspecting the change.
@@ -509,8 +547,14 @@ Everything below has only run against fakes, or not at all. Anyone with the setu
- A viewer seeing "Streaming " with no other Playing program running.
- The **update dialog** in the real settings window, the tray's update notice, and the tray icon's sharpness at 200 %
display scaling.
+- The **update notices on Linux and macOS**: a real desktop's notification service (GNOME, KDE Plasma, dunst), its
+ click and how it shows the logo, and the macOS notification centre for the ad-hoc signed app (its permission prompt and click). The D-Bus
+ messages are tested against a fake bus; the macOS code is only compiled on CI.
- **Copy diagnostics** in a normal browser window (not the `--app=` window).
- **Start with Windows** after it was switched off in Task Manager's Startup list.
+- **An install from before the rename** on a real system: its data folder moved (or copied while a file is held),
+ its run-at-login entry carried over (the Windows registry with a start switched off in Task Manager, a macOS
+ LaunchAgent, a Linux autostart file), and a second start while a copy of the former version still runs.
- **Set up the player connection** end to end (it writes MPC-HC's registry values).
- **MPC-QT's multi-window mode** with a portable build and the live engine test.
- **mpv on a real Linux desktop.**
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index d2a65bc..8112099 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -2,7 +2,8 @@
The details behind what the [README](../README.md) promises: what shows on Discord, how titles are cleaned up, where
covers and episode names come from, and how each player is read. Every setting with its default is in
-[All settings](config.md).
+[All settings](config.md); problems are in [Troubleshooting](troubleshooting.md); every page is listed in the
+[docs index](README.md).
## The window and the menu
**The tray menu** (Windows) and **the menu bar menu** (macOS) hold:
@@ -22,11 +23,11 @@ minimised, or let the program start at login; running it again brings the window
|---|---|
| General | starting with the system, showing on Discord when the app opens, updates |
| Players | the players on this computer, and the Plex, Stremio and Jellyfin / Emby sign-ins |
-| Look | how the status looks: style, progress bar, info lines, links, streams |
+| Look | how the status looks: style, progress bar, info lines, text lines, links, streams |
| Titles & art | episode titles, title spelling, anime titles, folder names, **Fix a match**, a TMDB key |
| Privacy | hiding titles and files, clearing after a pause, which online services may see a title, Recent connections |
| Advanced | the Discord application ID, how often players are checked, Maintenance (Restore defaults, Open settings folder) |
-| Help | Run a check, Copy diagnostics, the log, your stats, credits |
+| Help | Run a check, Copy diagnostics, the log, your stats, About (version, links, credits and licence) |
Settings save as you change them; **Restore defaults** (Advanced > Maintenance) resets them all after asking. Closing
the window with its X quits the program (on macOS it closes to the menu bar); minimizing it on Windows sends it to the
@@ -39,6 +40,11 @@ tray.
- **The second line** shows the season and episode with the episode's title (`S01E03 · Episode title`), or the year
for a movie. For an episode with a known season, the image tooltip reads "Season 1, Episode 3", which Discord turns
into S1E3.
+- **Text lines.** **Look > Text lines** chooses the two lines under the title: **Standard** (as above), **Short**
+ (`S01E02 · Episode title`, a film's year and director), **Detailed** (adds the length and `on `) or
+ **Custom**, five lines of your own written with placeholders such as `{episodeTitle}` or `[on {player}]`, with a sample
+ as you type. Custom can also shape a film's cover text. The name, the pause line, an episode's cover text (the badge),
+ the stream form and songs stay as they are. [Details](config.md#textlines).
- **Clickable title and cover.** With **Look > Link to the title's page** on (the default) and the title found in a
catalog that has a page (IMDb, AniList, ...), both text lines and the cover open that page, next to a "View on IMDb"
style button. A second button opens another page of the title when there is one (IMDb next to Letterboxd or
@@ -52,7 +58,7 @@ tray.
- **Preview.** While a status shows, the block at the top of the window shows how it looks on Discord: the title
lines, the cover with the player's logo, the progress bar and the link buttons, built from what was actually sent
(so it also shows the basic fallback). The second line is underlined (dotted) when it is a link. **Wrong title or
- cover?** below it leads to **Titles & art > Fix a match**.
+ cover?** below it opens [Fix this match](#fixing-a-match) for what plays.
- **Music.** A song played in a video player (`.mp3`, `.flac` and the like) shows as "Listening to " (with
the title hidden: "Listening to music"). It is never looked up in the catalogs and is not counted in the stats. A
video playing in another player comes first.
@@ -66,7 +72,7 @@ tray.
number at the top shows every version's.
- **Updates.** The program looks for a new version as it starts and every six hours, and asks or installs it by itself:
see [Troubleshooting > Updates](troubleshooting.md#updates).
-- The log is `mpcvibedrpc.log` (also on the **Help** tab).
+- The log is `mprp.log` (also on the **Help** tab).
## Titles and covers
@@ -178,10 +184,24 @@ A disc's video files are named by number (`BDMV\STREAM\00062.m2ts`, `BDMV\PLAYLI
A camcorder's discs and cards (`AVCHD`) and labels that say nothing (`BDROM`, `DVD_VIDEO`) are left as they are.
### Fixing a match
-Still no cover, or the wrong one? Use **Titles & art > Fix a match**: search under another name, or pin your own cover
-image. Each line starts with the title as the program read it, which the log shows after `Playing:` (for a Blu-ray
-file named `00062.m2ts` that is `00062`): `00062 = Sample Movie`. A line applies to every file read as that title.
-The log also lists what each catalog returned. A free TMDB key (**Titles & art > More**) improves some matches.
+Wrong title or cover? Choose **Wrong title or cover?** under the preview while it plays. **Fix this match** says what
+the file was read as and what it matched, and searches the catalogs that are on under Privacy as you type (at most
+three, after a short pause), with each entry's cover, year, kind and catalog. Pick the right one and **Use this**:
+- The fix pins that catalog entry, so the cover, the catalog's spelling and the episode titles come from it. The last
+ row, **Search as ... instead**, searches under another name without pinning an entry.
+- It applies to **every file read as that title** (all episodes follow), or to **only this file** (its exact name; it
+ stops matching if the file is renamed). A fix for the file wins.
+- **Fixed** then offers the cover: the entry's own, one of the same title from the other catalogs, or an image address
+ of your own. **Episodes don't line up?** adds a season and episode offset to the numbers read from the file before
+ the catalogs are asked (a second season numbered from 1 in the files but from 13 in the catalog needs +12); the card
+ then shows the catalog's numbers. **Undo** takes the fix back.
+- **Tell the project about this** (only if you choose it) shows a short report: the file name (never its folder), what
+ it was read as, the automatic match, your fix, the catalogs on and the version. You copy it, look it over and post it
+ on GitHub yourself; the program sends nothing.
+
+**Titles & art > Fix a match** lists every fix with **Edit** and **Remove** (the bar offers Undo), and **Add a fix** makes
+one for a title that is not playing: type it as the log shows it after `Playing:` (for a Blu-ray file named
+`00062.m2ts` that is `00062`). The log also lists what each catalog returned. A free TMDB key (**Titles & art > More**) improves some matches.
## On your streams
When you share your screen, Discord names the stream after your *Playing* status and after no other kind, so
@@ -275,8 +295,8 @@ What was tried with which player, and how, is in [What has been tried](#what-has
### Plex
- **Signing in:** **Players > Sign in to Plex** opens plex.tv in your browser, and you approve the sign-in there (the
- program never sees your password). The program introduces itself to Plex as "MPCvibedRPC" and keeps the sign-in in
- `config.json`; **Sign out** or **Restore defaults** asks plex.tv to end the sign-in, then removes it from this
+ program never sees your password). The program introduces itself to Plex as "MPRP" and keeps the sign-in in
+ `config.json` (encrypted for your user account on Windows); **Sign out** or **Restore defaults** asks plex.tv to end the sign-in, then removes it from this
computer (also when plex.tv does not answer). The program may stay listed on Plex's *Authorized Devices* page,
where its entry can be deleted.
- **Your server:** it follows your server; choose another one under the button (your own servers come first, then
@@ -290,7 +310,7 @@ What was tried with which player, and how, is in [What has been tried](#what-has
### Stremio
- **Signing in:** **Players > Sign in to Stremio** works the way Stremio's TV apps do: stremio.com opens in your
browser and you approve a code there (the program never sees your password). The account's key is kept in
- `config.json`; **Sign out** (or **Restore defaults**) ends that session on Stremio's side and removes it.
+ `config.json` (encrypted on Windows, as above); **Sign out** (or **Restore defaults**) ends that session on Stremio's side and removes it.
- **What it reads:** Stremio has no live "now playing" for other apps, so the program reads the account's library:
every 20 seconds it asks which entries changed, and fetches only those.
- Stremio's player updates the entry of what you watch when it starts, pauses, resumes and stops, and every 180 seconds
@@ -308,8 +328,8 @@ What was tried with which player, and how, is in [What has been tried](#what-has
where you are already signed in (profile > Quick Connect). The program waits up to 10 minutes.
- **Use a password instead** is the way for Emby (no Quick Connect) or a Jellyfin server with Quick Connect off. The
password goes to your own server once and is never stored.
-- **What is kept:** only the server's access token, in `config.json` as plain text like other apps keep theirs; the
- window and **Copy diagnostics** never show it. **Sign out** and **Restore defaults** end the session on the server
+- **What is kept:** only the server's access token, in `config.json` (encrypted for your user account on Windows,
+ plain text on macOS and Linux); the window and **Copy diagnostics** never show it. **Sign out** and **Restore defaults** end the session on the server
and forget the sign-in.
- **What it reads:** the server's session list, every 5 seconds while you are signed in. Only your own sessions count
(an administrator would see everyone's); music, audiobooks and photos are skipped; a playing session beats a paused
diff --git a/docs/images/icon.png b/docs/images/icon.png
index b17707c..f61a531 100644
Binary files a/docs/images/icon.png and b/docs/images/icon.png differ
diff --git a/docs/images/window-main.jpg b/docs/images/window-main.jpg
index 21b6655..402e37b 100644
Binary files a/docs/images/window-main.jpg and b/docs/images/window-main.jpg differ
diff --git a/docs/images/window-plex.jpg b/docs/images/window-plex.jpg
index 88d20e3..0f3ee9c 100644
Binary files a/docs/images/window-plex.jpg and b/docs/images/window-plex.jpg differ
diff --git a/docs/images/window-privacy.jpg b/docs/images/window-privacy.jpg
index e13e064..c694e8e 100644
Binary files a/docs/images/window-privacy.jpg and b/docs/images/window-privacy.jpg differ
diff --git a/docs/maintaining.md b/docs/maintaining.md
index 961d8cb..10d7a70 100644
--- a/docs/maintaining.md
+++ b/docs/maintaining.md
@@ -1,6 +1,6 @@
# Maintaining
-For maintainers: how MPCvibedRPC is released, how its screenshots are taken, how the README is previewed and how
+For maintainers: how MPRP is released, how its screenshots are taken, how the README is previewed and how
release files are downloaded. Building, testing and running the program safely are in [development.md](development.md);
the rules for everyone are in [CONTRIBUTING.md](../CONTRIBUTING.md).
@@ -26,7 +26,7 @@ Steps 1-2 are done where the change was made. Steps 3-4 (from the merge to the v
version and the maintainer's go-ahead.
1. **Branch and change.**
- - Bump `var version` in `cmd/mpcvibedrpc/main.go`. Nothing else carries the version: the workflows run
+ - Bump `var version` in `cmd/mprp/main.go`. Nothing else carries the version: the workflows run
`tools/ci/version.sh`, which reads it from `main.go`, works out `NEXT` (the next patch version, which the smoke
test's self-update installs) and, on a tag, fails when the tag does not match. Docs use `X.Y.Z`.
- Add the version's entry at the top of `internal/assets/changelog.json` (short lines, one emoji each, at most 130
@@ -51,22 +51,29 @@ version and the maintainer's go-ahead.
would merge at once.
2. **Merge:** `gh pr merge --rebase --delete-branch`. GitHub may refuse to rebase a branch that holds merge
commits (seen once with merged helper branches): use `--merge` then, or rebase the branch locally first.
- 3. **Tag** the merged commit with an annotated tag and push it. An annotated tag stores the tagger's name and email,
+ 3. **Rename the repository first if the name changed** (repository settings; the maintainer's go-ahead). The code
+ names the repository it updates from (`DefaultUpdateRepo` in `internal/store/store.go`, and the player logos'
+ address), and the release workflow's first step fails unless the repository already has that name.
+ 4. **Tag** the merged commit with an annotated tag and push it. An annotated tag stores the tagger's name and email,
so tag with the same neutral identity used for commits, never a personal email:
- `git -c user.name="" -c user.email="" tag -a vX.Y.Z -m "MPCvibedRPC X.Y.Z"`, then
+ `git -c user.name="" -c user.email="" tag -a vX.Y.Z -m "MPRP X.Y.Z"`, then
`git push origin vX.Y.Z`.
- 4. **The release workflow** (`.github/workflows/release.yml`) checks the tag against `main.go`, runs the tests,
- builds the programs on Windows, Linux and macOS runners and smoke-tests each on its own system (Windows: tray,
+ 5. **The release workflow** (`.github/workflows/release.yml`) checks the repository's name and the tag against
+ `main.go`, runs the tests, builds the programs on Windows, Linux and macOS runners and smoke-tests each on its
+ own system (Windows: tray,
Discord pipe, resting while Discord is closed, DPI awareness, version details, autostart, a self-update against a
fake server; macOS and Linux: the API, login item, player setup, a second start, and on macOS opening the app
- like the Finder does). It writes the `.sha256` files, attests the builds and publishes a **draft**.
- 5. **`reproduce`** rebuilds the exe and both Linux programs from the tag on another runner at the same time
+ like the Finder does). It writes the `.sha256` files, adds a byte-identical copy of each program file under the
+ former name for copies installed before the rename (`tools/ci/former-names.txt`, which says when they go),
+ attests the builds and publishes a **draft**.
+ 6. **`reproduce`** rebuilds the exe and both Linux programs from the tag on another runner at the same time
(`tools/ci/reproduce.sh`); only `verify` waits for it.
- 6. **`verify`** checks that the rebuilt files' checksums equal the release's (byte for byte), then runs
- `tools/ci/verify-release.ps1` on the draft: the ten assets, every checksum and build record, the exe's version.
- Only if these pass is the release made public (and latest). Then come the checks that need it public: that it is
- the latest release, and a real self-update from the previous release.
- 7. **A draft that fails** stays a draft (nobody's updater sees it): fix, then delete the draft and the tag, or
+ 7. **`verify`** checks that the rebuilt files' checksums equal the release's (byte for byte), then runs
+ `tools/ci/verify-release.ps1` on the draft: the eighteen assets (the copies under the former name the same files
+ byte for byte), every checksum and build record, the exe's version. Only if these pass is the release made
+ public (and latest). Then come the checks that need it public: that it is the latest release, and a real
+ self-update from the previous release.
+ 8. **A draft that fails** stays a draft (nobody's updater sees it): fix, then delete the draft and the tag, or
publish it by hand once checked.
4. **Read the `verify` job's log** (`gh run view --log`) and report. Nothing needs re-running locally after a release.
5. **Repository details.** A release with new features also updates the repository description and topics
@@ -79,6 +86,10 @@ version and the maintainer's go-ahead.
`gh run view --attempt 1 --log` (or `--log-failed`).
- A release run whose macOS job is cancelled with "not acquired by Runner" built nothing and left no draft:
`gh run rerun --failed` is the remedy.
+- **The public `verify` stage's update check.** When GitHub's API refuses the previous release's check (rate limit),
+ that release falls back to the website, and a release of the former name does not follow the website's redirect
+ after a rename, so it is offered nothing. `verify-release.ps1` tries the check four times, 30 seconds apart; if it
+ still fails, re-run the job later (a release run: with the maintainer's word).
- Versions stay `0.9.x`, three-part: the updater compares three numbers.
## Downloading release files
@@ -99,18 +110,22 @@ To check a release without downloading anything, GitHub lists each file's sha256
## Screenshots
The README's pictures (`docs/images/window-main.jpg`, `window-privacy.jpg`; `window-plex.jpg` is used by
-[troubleshooting](troubleshooting.md)) are taken again when the part of the window they show changes:
+[troubleshooting](troubleshooting.md)) are taken again when the part of the window they show changes. Build the
+program, then:
-1. Build the program and start it as a throwaway copy ([how](development.md#running-the-program-safely)), with showing
- on Discord off and `{"app": {"seenVersion": ""}}` in its `config.json` so the What's new box stays closed.
-2. Open its settings page (the address and token are in `ipc.json` in that folder) in dark mode, at the size the
- program itself uses: Edge's `--window-size=660,800` (`internal/winsys/window.go`). That is the outer window; about
- 35 px go to the title bar and border, which leaves a 660 x 760 page. A high-DPI screen gives sharper pictures.
-3. For `window-main.jpg`, paste `tools/screenshots/demo.js` into the page's console: it shows a made-up
- "Sample Show" playing and sample stats, and nothing is sent anywhere. Take the General tab. For
- `window-privacy.jpg` (Privacy tab, scrolled to "Services that may see your titles") and `window-plex.jpg`
- (Players tab, scrolled to Plex), reload the page first, so showing on Discord is off.
-4. Save them 800 pixels wide (800 x 921). Only made-up titles; nothing from a real library or account.
+ node tools/screenshots/take.js dist/MPRP.exe
+
+It needs Node.js 22 or later and Edge or Chrome (found in the usual places; `MPRP_SHOT_BROWSER` names another one),
+and writes the three pictures into `docs/images` (`--out` another folder). It starts a throwaway copy
+([how](development.md#running-the-program-safely)) with a temporary data folder, no window of its own, showing on
+Discord, update checks and autostart off and its players pointed nowhere, and opens the settings page in a headless
+browser with a temporary profile: dark, at the program's own page size (660 x 760, from Edge's `--window-size=660,800`
+in `internal/winsys/window.go`) and 800 pixels wide (800 x 921). `window-main.jpg` is the General tab with the made-up
+"Sample Show" from `tools/screenshots/demo.js` (it only changes what the page is told; nothing is sent anywhere);
+`window-privacy.jpg` is the Privacy tab at "Services that may see your titles", `window-plex.jpg` the end of the
+Players tab. The player logos come from this checkout's `docs/players`. At the end it quits the copy and deletes both
+temporary folders. JPEG quality 70 (`--quality`) keeps them near 50-65 KB each. Look at the pictures before
+committing them: only made-up titles, nothing from a real library or account.
## Previewing the README
`gh api markdown -f mode=markdown -f text="$(cat README.md)"` renders it the way GitHub does. `mode=gfm` misleads: it
diff --git a/docs/research/discord-rich-presence.md b/docs/research/discord-rich-presence.md
index 765c461..7667a14 100644
--- a/docs/research/discord-rich-presence.md
+++ b/docs/research/discord-rich-presence.md
@@ -1,4 +1,4 @@
-# Discord Rich Presence: what the card can show and what MPCvibedRPC sends
+# Discord Rich Presence: what the card can show and what MPRP sends
A research report, written 2026-11-21 and checked against the code on 2026-11-25. Its sources are Discord's public
developer documentation, what was seen on real profiles and streams, and this repository. Nothing here comes from
diff --git a/docs/research/immutable-releases.md b/docs/research/immutable-releases.md
index 66c4b85..891fc09 100644
--- a/docs/research/immutable-releases.md
+++ b/docs/research/immutable-releases.md
@@ -2,7 +2,7 @@
Read 2026-11-11 against GitHub's documentation ("Preventing changes to your releases" and the concept page "Immutable
releases"). The setting is off; this page is the background for the roadmap's
-[open decision 2](../roadmap.md#open-decisions-the-maintainers).
+[open decision 1](../roadmap.md#open-decisions-the-maintainers).
## Answer
They fit. The release flow already does what GitHub recommends: `release.yml` uploads every file to a **draft**
diff --git a/docs/roadmap.md b/docs/roadmap.md
index dc14051..f5a5e79 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -1,6 +1,6 @@
# Roadmap
-Where MPCvibedRPC is heading, what it deliberately leaves out, and the outside changes it has to watch. It comes from
+Where MPRP is heading, what it deliberately leaves out, and the outside changes it has to watch. It comes from
a research pass over Discord's documentation, the projects the program reads from, similar presence tools and their
users, and distribution channels (last reviewed 2026-11-25, with 0.9.58).
@@ -23,54 +23,11 @@ Every goal has to fit these:
## Next up
Work anyone can pick up without a decision from the maintainer (work that waits on one is under [Open decisions](#open-decisions-the-maintainers)). Each entry says what and where, and how to tell it is
done. (Work in progress is a branch and pull request: [CONTRIBUTING](../CONTRIBUTING.md#picking-up-work).)
-1. **A settings change restarts the run and reconnects to Discord** (`internal/engine/engine.go`, `ApplySettings`).
- Restart only what a setting needs, so the status does not blink and Discord's rate limit is not hit. Done when a
- change that touches no player or Discord setting leaves the connection open (an engine test against the fake Discord).
-2. **Behaviour tests for the settings page's script** (`internal/assets/ui.js`): a few tests with a stubbed `fetch` for
- the saver and the status sync. Today only `TestPageScriptParses` (`node --check`) covers it.
-3. **Tests for how the window's X quits** (`cmd/mpcvibedrpc/window.go`): the order of the dropped `/api/alive`
- connection and the window-handle polling. Also check whether `inTray` stays true when closing the window fails; if
- it does, a later X would not quit.
-4. **Historic names in the code.** The API's `mpc-web`, `winsys.EnableMpcWebInterface` and `Status.MPC` cover every
- player. Rename them; the page and the server ship together, so they change together. Done when no name says MPC for
- a thing that serves all players.
-5. **Split `core.Config`.** User settings, sign-in secrets and test hooks are one flat struct, compared with
- `reflect.DeepEqual` to decide a restart (`engine.go`). Separate them so a secret or a hook cannot cause a restart.
-6. **The settings window in Chrome, Brave or Vivaldi** instead of Edge: does the taskbar identity (name, pin, icon)
+1. **The settings window in Chrome, Brave or Vivaldi** instead of Edge: does the taskbar identity (name, pin, icon)
apply there?
-7. **MPC-QT's multi-window mode** with a portable build and the live engine test.
-8. **The stream title on Linux:** research how to tell that Discord shares the screen (PipeWire, the screen-cast
+2. **MPC-QT's multi-window mode** with a portable build and the live engine test.
+3. **The stream title on Linux:** research how to tell that Discord shares the screen (PipeWire, the screen-cast
portal). Today Linux chooses always or never ([decision](decisions.md#behaviour)).
-9. **CI: the Chocolatey Kodi download** (TLS errors from its mirror) fails `players-windows` now and then, and the
- canary uses it. Add a retry or another source ([known flaky checks](development.md#known-flaky-checks)).
-10. **Fix a match, first version** (settled 2026-11-25; part of version 0.9.60). Build what
- [design/fix-a-match.md](design/fix-a-match.md) describes: the dialog and the list with the scope choice, covers from
- the other catalogs, offsets and "Tell the project". *Where:* `internal/artwork`, the `cmd/mpcvibedrpc` API,
- `internal/assets` (the window), `core.Config` and the store schema (`matchFixes`), the docs. Done when the dialog and
- the list replace the two text boxes, old `artworkAliases` and `artworkOverrides` lines still act as before (they
- become fixes once), and the tests the design names pass.
-11. **Presence templates, first version** (settled 2026-11-25; part of version 0.9.60). Build
- [design/presence-templates.md](design/presence-templates.md): the Text lines row with Standard, Short, Detailed and
- Custom, including a film's cover text. *Where:* `internal/core` (`lines.go`, `BuildActivity`), the store schema
- (`textLines`, `customLines`), `internal/assets` (Look tab), the docs. Done when Standard reproduces the recorded
- golden data byte for byte, Custom lines show on the card, and the tests the design names pass.
-12. **The update notices on Linux and macOS** (settled 2026-11-25; part of version 0.9.60). Windows already shows three
- native notifications through the tray (`Tray.Balloon`): "updated to " once after an automatic update
- (`cmd/mpcvibedrpc/app.go`, `autoFrom`), "could not update to ..." after a rollback, and " is available"
- when automatic installs are off (`update.go`). Linux and macOS show none (`Balloon` returns false in
- `internal/winsys/tray_other.go` and `macapp_darwin.go`). Bring the same three there: Linux through the desktop
- notification service over D-Bus (`org.freedesktop.Notifications`, with `internal/dbus`), macOS through the menu bar
- app (cgo; tested on CI only). A click opens the settings window as on Windows. Done when each system shows the
- three notices, tests cover the D-Bus message against a fake bus, and the docs and changelog say so.
-13. **Sign-ins encrypted on Windows** (settled 2026-11-25; part of version 0.9.60). Encrypt the secrets in `config.json`
- with the per-user Windows DPAPI (`CryptProtectData` / `CryptUnprotectData` through `syscall`, standard library only):
- `plexToken`, `plexKey`, `stremioKey` and `jellyfinToken` (the sign-ins), and, to decide while building, the secrets
- typed in the window (`vlcPassword`, `kodiPassword`, `tmdbApiKey`). *Where:* `internal/store` (load and save),
- `core.Config`, SECURITY.md, `docs/config.md`. Existing plain values are read as before and encrypted at the next
- write; a config copied to another user or computer cannot be decrypted, so those sign-ins count as signed out and
- ask to sign in again; macOS and Linux are unchanged. Done when a saved config holds no plain secret on Windows, a
- plain one still loads, an undecryptable one reads as signed out (a test with a fake decrypter), and Diagnostics
- still leaves the values out.
## Goals
@@ -84,9 +41,8 @@ changed how often it saves playback, and Jellyfin, IINA and Kodi shipped new maj
as Flathub ships them (their makers' newest releases, `live-flathub.sh`).
### 2. Own the foundations
-- **Discord application**: the default application ID belongs to the project this one started from, which has been
- inactive since 2022. If it is deleted, every install loses its status at once. Register a project-owned application
- and keep the old ID as a fallback. *Needs the maintainer.*
+- **Discord application**: *done in 0.9.60.* The default is the project's own application (MPRP), registered by the
+ maintainer; installs that saved the former default (the upstream project's, inactive since 2022) use it too.
- **Go toolchain**: move to the newest Go release every February and August; the supported operating systems follow
Go's (Go 1.27: macOS 13 or later).
- **Plex sign-in**: Plex is moving to short-lived tokens (7 days, Ed25519 device keys). Old tokens still work and no end
@@ -102,7 +58,7 @@ The updater checks a checksum from the same release, so anyone able to publish a
that rebuilds the Windows and Linux files from the tag and compares them byte for byte.
- *Status:* done: the pins, read-only workflows by default, and the rebuild (`tools/ci/reproduce.sh`; a release is only
published when every program file matches).
-- *Left:* the signed manifest (needs the maintainer's key) and immutable releases (open decision 2).
+- *Left:* the signed manifest (needs the maintainer's key) and immutable releases (open decision 1).
- Not planned: checking GitHub's build attestations inside the program (much security code, a moving format, narrow
benefit). The attestations stay available to check by hand.
@@ -116,8 +72,8 @@ The updater checks a checksum from the same release, so anyone able to publish a
- MPC-HC's web interface answers any web page once switched on (no password, open to all origins). The Privacy tab and
SECURITY.md say so.
- Keep sign-ins out of plain text in `config.json`.
- - *Status:* settled 2026-11-25 as Windows' per-user DPAPI encryption (Next up 13); macOS and Linux stay as they are,
- and the full system key store (the macOS Keychain, the Secret Service) is not planned.
+ - *Status:* done on Windows: the sign-ins are encrypted with the per-user DPAPI (settled 2026-11-25). macOS and
+ Linux stay as they are, and the full system key store (the macOS Keychain, the Secret Service) is not planned.
### 5. Readable by a human, decisions in the open
- A public record of the product decisions and of the non-goals below, with the reason for each.
@@ -155,8 +111,8 @@ Each of these sank or burdened a similar tool, or breaks a principle:
an allowlist, if ever.
- Built-in scrobbling (Trakt, Simkl, AniList); at most a local event hook that other tools can read.
- Watch-together features (they need servers) and a stored history of titles (the stats stay counts only).
-- A Microsoft Store edition (its sandbox breaks the MPC-HC setup and self-update) and Flathub (its rules on
- AI-generated apps and its sandbox), unless real demand appears.
+- A Microsoft Store edition (its sandbox breaks the MPC-HC setup and self-update) and Flathub (its manifests and
+ submissions must not be AI-written, which this project's are, and its sandbox), unless real demand appears.
## Considered and left
Ideas weighed and not done, each with its reason, so nobody has to weigh them again:
@@ -180,15 +136,13 @@ Ideas weighed and not done, each with its reason, so nobody has to weigh them ag
- **An episode number in the basic fallback status:** the recorded golden data pins it without one.
## Open decisions (the maintainer's)
-1. Register a project-owned Discord application.
-2. Turn on immutable releases (a repository setting; [how they fit the release flow](research/immutable-releases.md)).
-3. Keep an offline signing key and sign each stable release (one manual step each).
-4. Turn `plexJwt` on by default. It needs one real Plex sign-in to test it first (goal 2), which needs someone with a Plex
+1. Turn on immutable releases (a repository setting; [how they fit the release flow](research/immutable-releases.md)).
+2. Keep an offline signing key and sign each stable release (one manual step each).
+3. Turn `plexJwt` on by default. It needs one real Plex sign-in to test it first (goal 2), which needs someone with a Plex
account to try it; the maintainer has none.
-5. A popup for a found update when no settings window is open. Today the program updates itself silently, or shows the
- tray notice when automatic installs are off.
-Settled: the macOS minimum is 13. On 2026-11-25 the maintainer settled the Fix a match redesign, presence templates (both in Next up), the notice after an automatic update (on by default) and the sign-ins' storage: encrypted with Windows' DPAPI on Windows, plain on macOS and Linux, not the full key store (goal 4).
+Settled: the macOS minimum is 13. On 2026-11-25 the maintainer registered the project's own Discord application,
+the default from 0.9.60 ([decision](decisions.md#behaviour)). On 2026-11-25 the maintainer settled the Fix a match redesign and presence templates (both built in 0.9.60), the notice after an automatic update (on by default) and the sign-ins' storage: encrypted with Windows' DPAPI on Windows, plain on macOS and Linux, not the full key store (goal 4). A popup for a found update with no window open is not needed: every system shows a notification ([decision](decisions.md#the-window-and-the-tray)).
## Watch list
Outside facts the program depends on, with the date they were last checked.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 0f8c4fd..8474320 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -2,7 +2,8 @@
Problems and questions, by player and service. The [README](../README.md#-help) has the first checks, and every setting
is listed in [All settings](config.md). **Help > Run a check** tells you in a few lines what works and what does not
-(Discord, your players, the cover catalogs and updates); it never shows a title.
+(Discord, your players, the cover catalogs and updates); it never shows a title. Every other page is listed
+in the [docs index](README.md).
## Nothing shows on Discord
@@ -11,7 +12,7 @@ is listed in [All settings](config.md). **Help > Run a check** tells you in a fe
- IINA isn't found: after setting it up, quit IINA completely (IINA > Quit IINA) and open it again.
- MPC-QT needs no setup (it is read through its own connection); MPC-BE is set up like MPC-HC, with the same button.
- macOS 15 or later: a Plex, Jellyfin, Emby or Kodi server on your home network can't be reached until you allow it.
- Answer **Allow** when macOS asks, or turn MPCvibedRPC on under System Settings > Privacy & Security > Local Network.
+ Answer **Allow** when macOS asks, or turn MPRP on under System Settings > Privacy & Security > Local Network.
- "Discord on standby" is normal: showing is on, and the program contacts Discord only once something plays. If it
stays on "Waiting for Discord" while a video plays, use the Discord desktop app (not the browser) and check that
"Share my activity" is on ([where](../README.md#-getting-started)).
@@ -21,7 +22,7 @@ is listed in [All settings](config.md). **Help > Run a check** tells you in a fe
- More than one Discord (Stable, PTB, Canary) open: the status goes to the one that started first, which may be signed
in to another account. Close the ones you don't use.
- You can't click your own "View on ..." button or links on your profile; that's how Discord works. Others can.
-- "Watching Media Player Classic" instead of the title: turn on **Look > Show the title as the activity name**. The
+- "Watching MPRP" instead of the title: turn on **Look > Show the title as the activity name**. The
name after "Watching" is the Discord application's name unless that switch puts the title there.
- mpv-based players (mpv.net, for example) can be read like mpv when they open the same connection: add
`input-ipc-server=mpvsocket` to that player's own `mpv.conf` (not tested with each of them). Players that drive
@@ -42,6 +43,11 @@ is listed in [All settings](config.md). **Help > Run a check** tells you in a fe
and enter the same on the **Players** tab (the address too, for a Kodi on another device). The window says when Kodi
refuses the password, or when something else answers at the address.
- Kodi's web server uses port 8080, like VLC's: if both run, change one of them.
+
+**Smart App Control** (Windows 11, under Windows Security > App & browser control) blocks programs that are not
+code-signed until Microsoft's reputation service knows them, without a *Run anyway* choice, and each new version
+starts unknown. Where it is on, the program may not start, and an update may fail and put the old version back.
+Microsoft describes it in [SmartScreen reputation](https://learn.microsoft.com/windows/apps/package-and-deploy/smartscreen-reputation).
- On Linux, Kodi is also found through MPRIS without any of this.
- A pause in Kodi shows at once when Kodi's *Allow remote control from applications on this system* is on (the
default; *on other systems* for a Kodi on another device): its notifications come on port 9090. Without it, the
@@ -123,18 +129,22 @@ stays in the menu bar); minimizing it on Windows sends it to the tray.
## Wrong title or no cover
-The log (**Help** tab, or `mpcvibedrpc.log` in the settings folder) shows each title next to the file name it was read
+The log (**Help** tab, or `mprp.log` in the settings folder) shows each title next to the file name it was read
from, for example `Playing: Sample Show · S01E02 (MPC-HC: "Sample.Show.S01E02.1080p.mkv")`, and lists what each catalog
-returned. Under **Titles & art > Fix a match** you can search under another name or pin your own cover image: start
-each line with the title as the log shows it after `Playing:` ([an example](how-it-works.md#fixing-a-match)). A free
+returned. While it plays, **Wrong title or cover?** under the preview opens Fix this match: search, pick the right
+entry, and the fix applies to every file read as that title or to that file only ([how](how-it-works.md#fixing-a-match)). A free
TMDB key (**Titles & art > More**) improves some matches. A show found only by TVmaze can take about a minute to get its
cover the first time: TVmaze answers a search slowly until it has it cached.
+Text but no pictures on the card in a third-party Discord app (Vesktop, Legcord and the like): such apps may not show
+cover images from outside addresses; the official Discord app does. This was reported for a similar program and has
+not been tried with MPRP.
+
## Where are my settings? How do I remove it?
-Everything is in `%LOCALAPPDATA%\MPCvibedRPC` (macOS: `~/Library/Application Support/MPCvibedRPC`; Linux:
-`~/.local/share/MPCvibedRPC`): settings, log, cover cache, your stats, and the window's own browser profile (your
-regular browser is left alone). **Open settings folder** (**Advanced > Maintenance**) opens it. Every setting with its
+Everything is in `%LOCALAPPDATA%\MPRP` (macOS: `~/Library/Application Support/MPRP`; Linux:
+`$XDG_DATA_HOME/MPRP`, else `~/.local/share/MPRP`): settings, log, cover cache, your stats, and the window's own
+browser profile (your regular browser is left alone). **Open settings folder** (**Advanced > Maintenance**) opens it. Every setting with its
default is in [docs/config.md](config.md).
To uninstall:
@@ -155,6 +165,10 @@ To uninstall:
- **With the window open:** the window asks at once, with what is new: **Update now** or **Not now**. It asks once for
each version; after **Not now** a line at the top of the window keeps saying so, and its **See what's new** button
brings the question back.
+- **Without the window:** a notification says once that a new version is available (when it does not install itself),
+ that it installed itself, or that it failed and the old version is back. Click it to open the window. Windows shows
+ it next to the tray icon, Linux through the desktop's notification service (none: no notification), macOS through
+ the notification centre, which asks once whether MPRP may notify (System Settings > Notifications).
- **Automatic install** (Windows and Linux; **Install updates automatically**, on by default): the update installs
itself as soon as nothing is playing and no settings window is open (the program then runs minimised to the tray, or
was started at login), restarts in the tray and says so once. Closing the window quits the program on Windows and
@@ -162,7 +176,8 @@ To uninstall:
tray icon (macOS: the menu bar icon) shows a red dot. **Update now** in the window does it at once.
- **Safety:** every update is checked against its checksum. The copy that installed it waits until the new version has
come up; if it has not within half a minute, the old version is put back and started again, and a notice says so.
- That version is not installed by itself a second time (a newer one is).
+ That version is not installed by itself a second time (a newer one is). On Windows 11, Smart App Control (below) can
+ be why a new version does not start.
- **macOS:** the window links to the download.
- After an update the window shows what's new once; the version number at the bottom of the window shows every version.
@@ -178,4 +193,4 @@ them.
On the **Help** tab, **Copy diagnostics** copies the version, the settings you changed, how the current title was found
(the file name, what was read from it, which catalog matched) and the recent log. It names the titles and file names you
played (that is how a wrong title is traced); folder paths, sign-ins and keys are left out. Paste it into a
-[new issue](https://github.com/CptPakundo/MPCvibedRPC/issues/new/choose).
+[new issue](https://github.com/CptPakundo/MPRP/issues/new/choose).
diff --git a/go.mod b/go.mod
index b06e926..7a94224 100644
--- a/go.mod
+++ b/go.mod
@@ -1,3 +1,3 @@
-module github.com/CptPakundo/MPCvibedRPC
+module github.com/CptPakundo/MPRP
go 1.27.4
diff --git a/internal/artwork/anime_episodes_test.go b/internal/artwork/anime_episodes_test.go
index 5201597..c0f923a 100644
--- a/internal/artwork/anime_episodes_test.go
+++ b/internal/artwork/anime_episodes_test.go
@@ -13,7 +13,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakeAnimeCatalogs answers like TVmaze, Jikan (MyAnimeList) and Cinemeta for a long-running anime, "Sample Saga"
diff --git a/internal/artwork/artwork.go b/internal/artwork/artwork.go
index 364c547..75ab522 100644
--- a/internal/artwork/artwork.go
+++ b/internal/artwork/artwork.go
@@ -15,7 +15,7 @@ import (
"net/http"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Options configures an Artwork finder.
@@ -64,22 +64,8 @@ type Artwork struct {
late map[string]bool
warned map[string]bool
runtimes map[string]int
- aliases map[string]string
- overrides map[string]string
-}
-
-func mapByTitle(m map[string]string) map[string]string {
- out := map[string]string{}
- for k, v := range m {
- out[normTitle(k)] = v
- }
- return out
-}
-
-// fixed tells whether the user gave title an alias or a pinned cover (Fix a match).
-func (a *Artwork) fixed(title string) bool {
- nt := normTitle(title)
- return a.aliases[nt] != "" || a.overrides[nt] != ""
+ fixes fixIndex
+ suggested map[string]suggestEntry // Suggest's and Covers' answers of the last minutes (see fixes.go)
}
// New creates a finder for the given settings.
@@ -92,7 +78,7 @@ func New(cfg *core.Config, opts Options) *Artwork {
}
a := &Artwork{cfg: cfg, opts: opts, net: newNet(opts.Client, cfg.RequestGapMs), provs: buildProviders(), today: unixDay,
disk: map[string]*diskEntry{}, misses: map[string]time.Time{}, soft: map[string]bool{}, closest: map[string][]string{}, inflight: map[string]*lookupFlight{}, late: map[string]bool{},
- warned: map[string]bool{}, runtimes: map[string]int{}, aliases: mapByTitle(cfg.ArtworkAliases), overrides: mapByTitle(cfg.ArtworkOverrides)}
+ warned: map[string]bool{}, runtimes: map[string]int{}, fixes: newFixIndex(cfg.Fixes()), suggested: map[string]suggestEntry{}}
a.net.blocked = blockedHostFilter(cfg)
a.net.onLate = a.lateAnswer
a.res = newResolver(a)
@@ -670,8 +656,8 @@ func (a *Artwork) searchWith(media *core.Media, query string, contain []string)
func (a *Artwork) search(media *core.Media) *core.Art {
cfg := a.cfg
query := media.Title
- if v := a.aliases[normTitle(media.Title)]; v != "" {
- query = v
+ if fx := a.FixFor(media); fx != nil && fx.Search != "" {
+ query = fx.Search
}
var seen []string
spaced := core.Trim(reWS.ReplaceStr(reDashSpace.ReplaceStr(query, " "), " "))
@@ -767,7 +753,7 @@ func (a *Artwork) search(media *core.Media) *core.Art {
a.closest[normTitle(media.Title)] = uniq // for Explain
a.mu.Unlock()
}
- a.log("INFO", `No artwork match for "`+media.Title+`".`+extra+` You can pin one with "Search under another name" / "Pin a cover image" in the Advanced settings.`)
+ a.log("INFO", `No artwork match for "`+media.Title+`".`+extra+` You can fix it with "Wrong title or cover?" under the preview, or in Titles & art > Fix a match.`)
return nil
}
@@ -1173,6 +1159,7 @@ type lookupJob struct {
special *core.Media // the title read as a show's special (core.NamedSpecial), or nil
query string
overrideArt *core.Art
+ fix *core.MatchFix // the user's fix for this title or file (Fix a match), or nil
wantEp bool
fullKey string // the in-flight key: epKey when the episode title is wanted, else key
key string // poster/season info, per show+season
@@ -1182,23 +1169,21 @@ type lookupJob struct {
lbKey string
}
-// newLookupJob works out the keys, the alias query and the override of one title.
+// newLookupJob works out the keys, the query and the pinned cover of one title, from the user's fix if it has one.
func (a *Artwork) newLookupJob(media *core.Media) *lookupJob {
cfg := a.cfg
nt := normTitle(media.Title)
+ fx := a.FixFor(media)
query := media.Title
- if v := a.aliases[nt]; v != "" {
- query = v
+ if fx != nil && fx.Search != "" {
+ query = fx.Search
}
+ // a pinned cover without a pinned entry is the whole answer, as a pinned cover always was
var overrideArt *core.Art
- if ov := a.overrides[nt]; ov != "" {
- if (strings.HasPrefix(ov, "http://") || strings.HasPrefix(ov, "https://")) && u16len(ov) <= 256 {
- overrideArt = core.NewArt()
- overrideArt.Poster, overrideArt.Name, overrideArt.Source = ov, media.Title, "override"
- } else {
- a.warnOnce("ov:"+nt, `artworkOverrides entry for "`+media.Title+`" must be an http(s) image URL (max 256 chars).`)
- }
+ if fx != nil && fx.Cover != "" && fx.Entry == "" && a.coverOK(fx, media) {
+ overrideArt = core.NewArt()
+ overrideArt.Poster, overrideArt.Name, overrideArt.Source = fx.Cover, media.Title, "override"
}
// Poster/season info is cached per show+season; the episode's own title per episode.
@@ -1217,7 +1202,7 @@ func (a *Artwork) newLookupJob(media *core.Media) *lookupJob {
if !truthy2(media.Year) && !media.IsEpisode && media.DurationMin != 0 {
dur = "|d" + strconv.Itoa(int(jsRound(float64(media.DurationMin)/10)))
}
- key := keyVersion + kind + "|" + nt + "|" + yearS + "|" + normTitle(a.aliases[nt]) + "|" + seasonS + "|" + media.CodePrefix + dur
+ key := keyVersion + kind + "|" + nt + "|" + yearS + "|" + fixKey(fx) + "|" + seasonS + "|" + media.CodePrefix + dur
// A leading list number ("02. Show Name") is the episode number if the title turns out to be a series.
epNo := media.Index
if media.IsEpisode {
@@ -1240,7 +1225,7 @@ func (a *Artwork) newLookupJob(media *core.Media) *lookupJob {
if wantEp {
fullKey = epKey
}
- return &lookupJob{a: a, media: media, special: special, query: query, overrideArt: overrideArt, wantEp: wantEp,
+ return &lookupJob{a: a, media: media, special: special, query: query, overrideArt: overrideArt, fix: fx, wantEp: wantEp,
fullKey: fullKey, key: key, epKey: epKey, infoKey: "info|" + key, aniKey: "ani|" + key, lbKey: "lb|" + key}
}
@@ -1267,6 +1252,9 @@ func (j *lookupJob) merge(base *core.Art, ep *core.ArtEpisode) *core.Art {
if n := j.inEntry(base); n != core.NA {
out.EpInEntry = n
}
+ if fx := j.fix; base != nil && fx != nil && fx.Cover != "" && fx.Entry != "" && j.a.coverOK(fx, j.media) {
+ out.Poster = fx.Cover // the user's image over the pinned entry's cover
+ }
return out
}
@@ -1327,9 +1315,9 @@ func (a *Artwork) Lookup(media *core.Media) *core.Art {
if !cfg.ShowArtwork || media == nil || media.Title == "" {
return nil
}
- // A junk name (a camera clip, a bare number such as a Blu-ray's "00062") is not looked up, unless the user named
- // it in Fix a match: their alias or pinned cover says what it is.
- if media.Junk && !a.fixed(media.Title) {
+ // A junk name (a camera clip, a bare number such as a Blu-ray's "00062") is not looked up, unless the user fixed it
+ // in Fix a match: their fix says what it is.
+ if media.Junk && a.FixFor(media) == nil {
return nil
}
j := a.newLookupJob(media)
@@ -1455,7 +1443,13 @@ func (j *lookupJob) baseArt() *core.Art {
if base == nil && !missKey {
down := a.unavail.Load()
- base = a.search(j.media)
+ searchIt := true
+ if j.fix != nil && j.fix.Entry != "" {
+ base, searchIt = a.pinned(j.fix, j.media)
+ }
+ if base == nil && searchIt {
+ base = a.search(j.media)
+ }
a.mu.Lock()
if base != nil {
a.put(j.key, &diskEntry{art: base})
@@ -1597,7 +1591,11 @@ func (j *lookupJob) episode(base *core.Art) *core.ArtEpisode {
}
var ep *core.ArtEpisode
if epMedia != nil {
- ep = a.res.Find(epMedia, base, j.query, func(k, msg string) { failed = true; a.warnOnce(k, msg) })
+ q := j.query
+ if j.fix != nil && j.fix.Entry != "" && base != nil && base.Name != "" && base.Source != "override" {
+ q = base.Name // episodes are looked up as the pinned entry
+ }
+ ep = a.res.Find(epMedia, base, q, func(k, msg string) { failed = true; a.warnOnce(k, msg) })
}
a.mu.Lock()
if epMedia == nil && base != nil {
diff --git a/internal/artwork/cache_days_test.go b/internal/artwork/cache_days_test.go
index afa25ca..0027dac 100644
--- a/internal/artwork/cache_days_test.go
+++ b/internal/artwork/cache_days_test.go
@@ -8,7 +8,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// cacheTestFinder makes a finder on a temp file whose clock is the returned day.
diff --git a/internal/artwork/cands.go b/internal/artwork/cands.go
new file mode 100644
index 0000000..9afeeac
--- /dev/null
+++ b/internal/artwork/cands.go
@@ -0,0 +1,95 @@
+package artwork
+
+import "github.com/CptPakundo/MPRP/internal/core"
+
+// The catalogs' answers read as candidates: the same for a search (providers.go) and for a page a fix pins
+// (fixes.go).
+
+// tmdbCand reads one TMDB result; kind is "movie" or "tv".
+func tmdbCand(r any, kind string) *Cand {
+ c := &Cand{
+ Titles: nonEmptyTitles(get(r, "name"), get(r, "title"), get(r, "original_name"), get(r, "original_title")),
+ Year: yearOf(firstTruthy(get(r, "first_air_date"), get(r, "release_date"))),
+ URL: "https://www.themoviedb.org/" + kind + "/" + tmpl(get(r, "id")),
+ URLLabel: "TMDB", Ref: str(get(r, "id")), Kind: kind,
+ }
+ if truthy(get(r, "poster_path")) {
+ c.Poster = posterIf(str(get(r, "poster_path")))
+ }
+ return c
+}
+
+// cinemetaCand reads one Cinemeta meta.
+func cinemetaCand(m any) *Cand {
+ return &Cand{
+ Titles: nonEmptyTitles(get(m, "name")), Year: yearOf(get(m, "releaseInfo")), Poster: str(get(m, "poster")),
+ URL: imdbURL(str(firstTruthy(get(m, "imdb_id"), get(m, "id")))), URLLabel: "IMDb",
+ }
+}
+
+// imdbCand reads one IMDb suggestion.
+func imdbCand(d any) *Cand {
+ c := &Cand{Titles: nonEmptyTitles(get(d, "l")), Year: yearNum(get(d, "y")), URL: imdbURL(str(get(d, "id"))), URLLabel: "IMDb"}
+ if truthy(get(d, "i")) {
+ c.Poster = str(get(d, "i", "imageUrl"))
+ }
+ c.l0 = tmpl(get(d, "l"))
+ return c
+}
+
+// tvmazeCand reads one TVmaze show.
+func tvmazeCand(s any) *Cand {
+ c := &Cand{Titles: nonEmptyTitles(get(s, "name")), Year: yearOf(get(s, "premiered")), Ref: str(get(s, "id")), ID: str(get(s, "id"))}
+ if truthy(get(s, "image")) {
+ c.Poster = orStr(get(s, "image", "medium"), str(get(s, "image", "original")))
+ }
+ if u := imdbURL(str(get(s, "externals", "imdb"))); u != "" {
+ c.URL, c.URLLabel = u, "IMDb"
+ } else {
+ c.URL, c.URLLabel = str(get(s, "url")), "TVmaze"
+ }
+ return c
+}
+
+// anilistFields are the fields asked of each AniList entry.
+const anilistFields = "siteUrl format episodes duration genres averageScore startDate { year } title { romaji english native } synonyms coverImage { large } " +
+ "staff(perPage: 8, sort: RELEVANCE) { edges { role node { name { full } } } }"
+
+// anilistCand reads one AniList entry.
+func anilistCand(m any) *Cand {
+ titles := nonEmptyTitles(get(m, "title", "romaji"), get(m, "title", "english"), get(m, "title", "native"))
+ titles = append(titles, nonEmptyTitles(asArr(get(m, "synonyms"))...)...)
+ c := &Cand{Titles: titles, Year: yearNum(get(m, "startDate", "year")), URL: str(get(m, "siteUrl")), URLLabel: "AniList",
+ Runtime: optPositive(get(m, "duration")), Eps: optPositive(get(m, "episodes")),
+ Alt: &core.ArtAlt{English: orStr(get(m, "title", "english"), ""), Romaji: orStr(get(m, "title", "romaji"), "")},
+ AniInfo: aniInfoOf(m)}
+ if truthy(get(m, "coverImage")) {
+ c.Poster = str(get(m, "coverImage", "large"))
+ }
+ return c
+}
+
+// kitsuCand reads one Kitsu entry.
+func kitsuCand(d any) *Cand {
+ attrs := get(d, "attributes")
+ if !truthy(attrs) {
+ attrs = &OMap{M: map[string]any{}}
+ }
+ t := get(attrs, "titles")
+ titles := nonEmptyTitles(get(attrs, "canonicalTitle"), get(t, "en"), get(t, "en_jp"), get(t, "en_us"), get(t, "ja_jp"))
+ titles = append(titles, nonEmptyTitles(asArr(get(attrs, "abbreviatedTitles"))...)...)
+ score := num(get(attrs, "averageRating"))
+ c := &Cand{Titles: titles, Year: yearOf(get(attrs, "startDate")), Ref: str(get(d, "id")), ID: str(get(d, "id")),
+ URLLabel: "Kitsu", Runtime: optPositive(get(attrs, "episodeLength")), Eps: optPositive(get(attrs, "episodeCount")),
+ Alt: &core.ArtAlt{English: orStr(firstTruthy(get(t, "en"), get(t, "en_us")), ""), Romaji: orStr(firstTruthy(get(t, "en_jp"), get(attrs, "canonicalTitle")), "")}}
+ if truthy(get(attrs, "posterImage")) {
+ c.Poster = str(firstTruthy(get(attrs, "posterImage", "large"), get(attrs, "posterImage", "medium"), get(attrs, "posterImage", "original")))
+ }
+ if truthy(get(attrs, "slug")) {
+ c.URL = "https://kitsu.io/anime/" + str(get(attrs, "slug"))
+ }
+ if score > 0 {
+ c.AniInfo = &core.ArtInfo{Genres: []string{}, Rating: jsRound(score) / 10}
+ }
+ return c
+}
diff --git a/internal/artwork/disabled.go b/internal/artwork/disabled.go
index 68efb86..d6b2f24 100644
--- a/internal/artwork/disabled.go
+++ b/internal/artwork/disabled.go
@@ -3,7 +3,7 @@ package artwork
import (
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// blockedHostFilter returns a function that reports whether a host belongs to a service switched off in the
diff --git a/internal/artwork/disabled_test.go b/internal/artwork/disabled_test.go
index 451e51b..e34454d 100644
--- a/internal/artwork/disabled_test.go
+++ b/internal/artwork/disabled_test.go
@@ -10,7 +10,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func TestBaseHost(t *testing.T) {
diff --git a/internal/artwork/episodes.go b/internal/artwork/episodes.go
index cc4de62..68e4fd4 100644
--- a/internal/artwork/episodes.go
+++ b/internal/artwork/episodes.go
@@ -8,7 +8,7 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Looks up the real title of the episode being watched when the filename doesn't carry one
diff --git a/internal/artwork/fixes.go b/internal/artwork/fixes.go
new file mode 100644
index 0000000..64a6388
--- /dev/null
+++ b/internal/artwork/fixes.go
@@ -0,0 +1,487 @@
+package artwork
+
+import (
+ "errors"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// Fix a match: the user's fixes (core.MatchFix), the catalog page a fix pins, and the searches the window's Fix this
+// match dialog asks for (Suggest, Covers). Every request goes through a.net, so each host's request gap, the blocked
+// hosts and the Privacy switches apply.
+
+// fixIndex finds the fix for a playing title: a fix for the file's exact name first, then one for the read title.
+type fixIndex struct {
+ byFile map[string]*core.MatchFix // lower-cased file name
+ byTitle map[string]*core.MatchFix // normTitle
+}
+
+func newFixIndex(fixes []core.MatchFix) fixIndex {
+ ix := fixIndex{byFile: map[string]*core.MatchFix{}, byTitle: map[string]*core.MatchFix{}}
+ for i := range fixes {
+ fx := &fixes[i]
+ if strings.TrimSpace(fx.Match) == "" {
+ continue
+ }
+ if fx.File {
+ ix.byFile[strings.ToLower(strings.TrimSpace(fx.Match))] = fx
+ } else {
+ ix.byTitle[normTitle(fx.Match)] = fx
+ }
+ }
+ return ix
+}
+
+// FixFor is the user's fix for media (its file name, set by the engine, before its read title), or nil.
+func (a *Artwork) FixFor(media *core.Media) *core.MatchFix {
+ if a == nil || media == nil {
+ return nil
+ }
+ if media.File != "" {
+ if fx := a.fixes.byFile[strings.ToLower(media.File)]; fx != nil {
+ return fx
+ }
+ }
+ if media.Title == "" {
+ return nil
+ }
+ return a.fixes.byTitle[normTitle(media.Title)]
+}
+
+// Offset moves the season and episode read from the file by the offsets of the user's fix (core.ShiftMedia), so the
+// catalogs are asked, and the card shows, the catalog's numbers. shifted says it did; a number that would fall below 1
+// leaves media as it is, with a warning in the log.
+func (a *Artwork) Offset(media *core.Media) (out *core.Media, shifted bool) {
+ fx := a.FixFor(media)
+ if fx == nil || (fx.SeasonOffset == 0 && fx.EpisodeOffset == 0) || !media.IsEpisode {
+ return media, false
+ }
+ m, ok := core.ShiftMedia(media, fx.SeasonOffset, fx.EpisodeOffset)
+ if !ok {
+ a.warnOnce("offset:"+fx.Match, `The episode offset of the fix for "`+fx.Match+`" would give a number below 1; it is not used for this file.`)
+ return media, false
+ }
+ return m, m != media
+}
+
+// fixKey is the part of a cache key that a fix changes: the other name searched (as before matchFixes), or the pinned
+// entry. "" without either, so the keys of titles nobody fixed stay as they were.
+func fixKey(fx *core.MatchFix) string {
+ if fx == nil {
+ return normTitle("")
+ }
+ if fx.Entry != "" {
+ return "@" + fx.Entry
+ }
+ return normTitle(fx.Search)
+}
+
+// coverOK checks a fix's own image address (http or https, at most 256 characters), with a warning once otherwise.
+func (a *Artwork) coverOK(fx *core.MatchFix, media *core.Media) bool {
+ c := fx.Cover
+ if (strings.HasPrefix(c, "http://") || strings.HasPrefix(c, "https://")) && u16len(c) <= 256 {
+ return true
+ }
+ a.warnOnce("ov:"+normTitle(fx.Match), `The cover pinned for "`+media.Title+`" must be an http(s) image address (at most 256 characters).`)
+ return false
+}
+
+// pinned is the art of the catalog page a fix pins, with a show's season poster and name when the catalog has them.
+// search is true when the page could not be had (its catalog is off under Privacy, or the page is gone) and the read
+// title should be searched instead; false with nil art when the catalog did not answer (asked again later).
+func (a *Artwork) pinned(fx *core.MatchFix, media *core.Media) (art *core.Art, search bool) {
+ e, ok := core.EntryPage(fx.Entry)
+ if !ok {
+ return nil, true
+ }
+ p, typ, c, err := a.entryCand(e)
+ if err != nil && unavailable(err) {
+ a.unavail.Add(1)
+ a.warnOnce("pin:"+fx.Entry, `The entry pinned for "`+media.Title+`" could not be read (`+err.Error()+`); trying again later.`)
+ return nil, false
+ }
+ if c == nil {
+ a.warnOnce("pin:"+fx.Entry, `The entry pinned for "`+media.Title+`" was not found (its catalog may be off under Privacy, or the page is gone); searching the title instead.`)
+ return nil, true
+ }
+ hit := a.hitOf(p, typ, c)
+ if typ == "series" && media.IsEpisode && media.Season != core.NA && p.Season != nil {
+ if se, err := p.Season(a, c, media); err == nil && se != nil && (se.Poster != "" || !genericSeasonName(se.Name)) {
+ if se.Poster != "" {
+ hit.Poster = se.Poster
+ }
+ if !genericSeasonName(se.Name) {
+ hit.SeasonName = se.Name
+ }
+ hit.SeasonNo = se.Number
+ }
+ }
+ a.log("INFO", `Artwork for "`+media.Title+`": `+describe(hit)+` (pinned in Fix a match).`)
+ return hit, false
+}
+
+// entryCand reads a pinned catalog page: the provider that answered, the kind ("movie" or "series") and the
+// candidate, or a nil candidate when no catalog that is on has it. An IMDb page is read from IMDb, else Cinemeta, else
+// TVmaze (shows only).
+func (a *Artwork) entryCand(e core.Entry) (p *Provider, typ string, c *Cand, err error) {
+ cfg := a.cfg
+ on := func(id string) bool {
+ pr := a.provs[id]
+ return cfg.ShowArtwork && pr != nil && cfg.SourceOn(id) && (pr.Enabled == nil || pr.Enabled(cfg))
+ }
+ var firstErr error
+ keep := func(e error) {
+ if firstErr == nil || unavailable(e) {
+ firstErr = e
+ }
+ }
+ switch e.Catalog {
+ case "imdb":
+ if on("imdb") {
+ j, err := a.net.getJSON(cfg.ImdbSuggestBase+"/suggestion/t/"+e.ID+".json", reqInit{})
+ if err != nil {
+ keep(err)
+ }
+ for _, d := range asArr(get(j, "d")) {
+ if str(get(d, "id")) != e.ID {
+ continue
+ }
+ typ := "movie"
+ if q := str(get(d, "qid")); q == "tvSeries" || q == "tvMiniSeries" {
+ typ = "series"
+ }
+ return a.provs["imdb"], typ, imdbCand(d), nil
+ }
+ }
+ if on("cinemeta") {
+ for _, typ := range []string{"series", "movie"} {
+ j, err := a.net.getJSON(cfg.CinemetaBase+"/meta/"+typ+"/"+e.ID+".json", reqInit{})
+ if err != nil {
+ keep(err)
+ continue
+ }
+ if m := get(j, "meta"); truthy(get(m, "name")) {
+ return a.provs["cinemeta"], typ, cinemetaCand(m), nil
+ }
+ }
+ }
+ if on("tvmaze") {
+ j, err := a.net.getJSON(cfg.TvmazeBase+"/lookup/shows?imdb="+e.ID, reqInit{})
+ if err != nil {
+ keep(err)
+ } else if truthy(get(j, "name")) {
+ return a.provs["tvmaze"], "series", tvmazeCand(j), nil
+ }
+ }
+ case "tmdb":
+ if on("tmdb") {
+ kind := "movie"
+ if e.Kind == "series" {
+ kind = "tv"
+ }
+ j, err := a.tmdbGet("/"+kind+"/"+e.ID, nil)
+ if err != nil {
+ keep(err)
+ } else if truthy(get(j, "id")) {
+ return a.provs["tmdb"], e.Kind, tmdbCand(j, kind), nil
+ }
+ }
+ case "tvmaze":
+ if on("tvmaze") {
+ j, err := a.net.getJSON(cfg.TvmazeBase+"/shows/"+e.ID, reqInit{})
+ if err != nil {
+ keep(err)
+ } else if truthy(get(j, "name")) {
+ return a.provs["tvmaze"], "series", tvmazeCand(j), nil
+ }
+ }
+ case "anilist":
+ if on("anilist") {
+ id, _ := strconv.Atoi(e.ID)
+ body := jsonString(struct {
+ Query string `json:"query"`
+ Variables map[string]int `json:"variables"`
+ }{"query ($id: Int) { Media(id: $id, type: ANIME) { " + anilistFields + " } }", map[string]int{"id": id}})
+ j, err := a.net.getJSON(cfg.AnilistURL, reqInit{Method: "POST", Headers: map[string]string{"Content-Type": "application/json", "Accept": "application/json"}, Body: body})
+ if err != nil {
+ keep(err)
+ } else if m := get(j, "data", "Media"); truthy(get(m, "siteUrl")) {
+ typ := "series"
+ if get(m, "format") == "MOVIE" {
+ typ = "movie"
+ }
+ return a.provs["anilist"], typ, anilistCand(m), nil
+ }
+ }
+ case "kitsu":
+ if on("kitsu") {
+ j, err := a.net.getJSON(cfg.KitsuBase+"/anime?filter[slug]="+encURI(e.ID), reqInit{Headers: map[string]string{"Accept": "application/vnd.api+json"}, NoRetryOnTimeout: true})
+ if err != nil {
+ keep(err)
+ } else if d := asArr(get(j, "data")); len(d) > 0 {
+ typ := "series"
+ if get(d[0], "attributes", "subtype") == "movie" {
+ typ = "movie"
+ }
+ return a.provs["kitsu"], typ, kitsuCand(d[0]), nil
+ }
+ }
+ }
+ return nil, "", nil, firstErr
+}
+
+// ---- the Fix this match dialog -------------------------------------------------------
+
+// Suggestion is one row of the Fix this match dialog: a catalog entry the user can pin.
+type Suggestion struct {
+ Name string `json:"name"`
+ Year int `json:"year,omitempty"`
+ Kind string `json:"kind"` // "movie" or "series"
+ Catalog string `json:"catalog"` // the catalog's name, as the window shows it
+ Poster string `json:"poster,omitempty"`
+ Entry string `json:"entry"` // the catalog page a fix pins
+}
+
+// Cover is one of the other catalogs' covers of a pinned title.
+type Cover struct {
+ URL string `json:"url"`
+ Catalog string `json:"catalog"`
+}
+
+type suggestEntry struct {
+ at time.Time
+ list []Suggestion
+ covers []Cover
+}
+
+// suggestTTL is how long the dialog's answers are kept: typing the same letters again asks nothing.
+const suggestTTL = 5 * time.Minute
+
+// maxSuggestCatalogs is how many catalogs one search of the dialog asks.
+const maxSuggestCatalogs = 3
+
+// suggestOrder are the catalogs the dialog may search, in the order they are chosen (Wikipedia, Jikan and Bulbapedia
+// never: they are no place to pin an entry). Cinemeta lists IMDb's entries, so it stands in for IMDb when that is off.
+var suggestOrder = []string{"tmdb", "imdb", "cinemeta", "tvmaze", "anilist", "kitsu"}
+
+// SuggestCatalogs are the catalogs the dialog's searches ask (at most three, only those on under Privacy).
+func (a *Artwork) SuggestCatalogs() []*Provider {
+ cfg := a.cfg
+ if !cfg.ShowArtwork {
+ return nil
+ }
+ var out []*Provider
+ for _, id := range suggestOrder {
+ p := a.provs[id]
+ if p == nil || !cfg.SourceOn(id) || (p.Enabled != nil && !p.Enabled(cfg)) {
+ continue
+ }
+ if id == "cinemeta" && len(out) > 0 && out[len(out)-1].Label == "IMDb" {
+ continue
+ }
+ out = append(out, p)
+ if len(out) == maxSuggestCatalogs {
+ break
+ }
+ }
+ return out
+}
+
+func (a *Artwork) cached(key string) (suggestEntry, bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e, ok := a.suggested[key]
+ if ok && time.Since(e.at) < suggestTTL {
+ return e, true
+ }
+ return suggestEntry{}, false
+}
+
+func (a *Artwork) keep(key string, e suggestEntry) {
+ e.at = time.Now()
+ a.mu.Lock()
+ if len(a.suggested) >= 100 {
+ clear(a.suggested)
+ }
+ a.suggested[key] = e
+ a.mu.Unlock()
+}
+
+// Suggest searches the dialog's catalogs for query and gives the entries found, closest names first, each once. An
+// empty list with no error: nothing found, or every catalog is off.
+func (a *Artwork) Suggest(query string) ([]Suggestion, error) {
+ query = core.Trim(query)
+ if u16len(query) < 2 {
+ return nil, nil
+ }
+ key := "s|" + strings.ToLower(query)
+ if e, ok := a.cached(key); ok {
+ return e.list, nil
+ }
+ type job struct {
+ p *Provider
+ typ string
+ list []*Cand
+ err error
+ }
+ var jobs []*job
+ for _, p := range a.SuggestCatalogs() {
+ for _, typ := range []string{"series", "movie"} {
+ if p.handles(typ) {
+ jobs = append(jobs, &job{p: p, typ: typ})
+ }
+ }
+ }
+ media := &core.Media{Title: query, Year: core.NA, Season: core.NA, Episode: core.NA, Index: core.NA, CodeEpisode: core.NA, BadgeEpisode: core.NA}
+ var wg sync.WaitGroup
+ for _, j := range jobs {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer func() {
+ if r := recover(); r != nil {
+ j.err = errors.New("the answer could not be read")
+ }
+ }()
+ j.list, j.err = j.p.Search(a, j.typ, query, media)
+ }()
+ }
+ wg.Wait()
+ // round robin over the catalogs' lists, so each one's best answers come first; then exact names first
+ var out []Suggestion
+ seen := map[string]bool{}
+ var failed error
+ for i := 0; ; i++ {
+ more := false
+ for _, j := range jobs {
+ if j.err != nil {
+ if failed == nil {
+ failed = j.err
+ }
+ continue
+ }
+ if i >= len(j.list) {
+ continue
+ }
+ more = true
+ c := j.list[i]
+ e, ok := core.EntryPage(c.URL)
+ if !ok || len(c.Titles) == 0 || seen[c.URL] {
+ continue
+ }
+ seen[c.URL] = true
+ // the catalog whose page it is (TVmaze lists a show by its IMDb page when it knows it)
+ s := Suggestion{Name: c.Titles[0], Year: c.Year, Kind: j.typ, Catalog: entryLabels[e.Catalog], Entry: c.URL}
+ if len(c.Poster) <= 512 {
+ s.Poster = c.Poster
+ }
+ out = append(out, s)
+ }
+ if !more {
+ break
+ }
+ }
+ nq := normTitle(query)
+ rank := func(s Suggestion) int {
+ n := normTitle(s.Name)
+ switch {
+ case n == nq:
+ return 0
+ case strings.HasPrefix(n, nq):
+ return 1
+ }
+ return 2
+ }
+ sort.SliceStable(out, func(i, j int) bool { return rank(out[i]) < rank(out[j]) })
+ if len(out) > 12 {
+ out = out[:12]
+ }
+ if len(out) == 0 && failed != nil {
+ return nil, failed
+ }
+ a.keep(key, suggestEntry{list: out})
+ return out, nil
+}
+
+// Covers finds the covers of one title in the other catalogs that are on (not except, the catalog of the pinned
+// entry): one search each, at most five covers, each once.
+func (a *Artwork) Covers(name string, year int, kind, except string) []Cover {
+ name = core.Trim(name)
+ if name == "" || (kind != "movie" && kind != "series") || !a.cfg.ShowArtwork {
+ return nil
+ }
+ key := "c|" + strings.ToLower(name) + "|" + strconv.Itoa(year) + "|" + kind + "|" + except
+ if e, ok := a.cached(key); ok {
+ return e.covers
+ }
+ cfg := a.cfg
+ type job struct {
+ p *Provider
+ list []*Cand
+ }
+ var jobs []*job
+ for _, id := range suggestOrder {
+ p := a.provs[id]
+ if p == nil || p.Label == except || !p.handles(kind) || !cfg.SourceOn(id) || (p.Enabled != nil && !p.Enabled(cfg)) {
+ continue
+ }
+ jobs = append(jobs, &job{p: p})
+ }
+ y := core.NA
+ if year > 0 {
+ y = year
+ }
+ media := &core.Media{Title: name, Year: y, Season: core.NA, Episode: core.NA, Index: core.NA, CodeEpisode: core.NA, BadgeEpisode: core.NA}
+ var wg sync.WaitGroup
+ for _, j := range jobs {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer func() { _ = recover() }()
+ j.list, _ = j.p.Search(a, kind, name, media)
+ }()
+ }
+ wg.Wait()
+ var out []Cover
+ seen := map[string]bool{}
+ for _, j := range jobs {
+ var usable []*Cand
+ for _, c := range j.list {
+ if c.Poster != "" && u16len(c.Poster) <= 256 {
+ usable = append(usable, c)
+ }
+ }
+ c := pickMatch(usable, name, year, kind == "movie", PickOpts{Earliest: j.p.Earliest, ExactOnly: j.p.ExactOnly, TrustAlias: j.p.TrustAlias})
+ if c == nil || seen[c.Poster] {
+ continue
+ }
+ seen[c.Poster] = true
+ out = append(out, Cover{URL: c.Poster, Catalog: j.p.Label})
+ if len(out) == 5 {
+ break
+ }
+ }
+ a.keep(key, suggestEntry{covers: out})
+ return out
+}
+
+// isPinned reports whether found is the entry fx pins (and not what a search found after the pinned page failed).
+func isPinned(fx *core.MatchFix, found *core.Art) bool {
+ e, ok := core.EntryPage(fx.Entry)
+ if !ok || found == nil || found.Source == "override" {
+ return false
+ }
+ if strings.Contains(found.URL, e.ID) {
+ return true
+ }
+ ids := found.IDs
+ return ids != nil && (ids.Imdb == e.ID || ids.Tvmaze == e.ID || ids.Tmdb == e.ID || ids.Kitsu == e.ID)
+}
+
+// entryLabels name the catalogs of the pages a fix can pin, as the window shows them.
+var entryLabels = map[string]string{"imdb": "IMDb", "tmdb": "TMDB", "tvmaze": "TVmaze", "anilist": "AniList", "kitsu": "Kitsu"}
diff --git a/internal/artwork/fixmatch_test.go b/internal/artwork/fixmatch_test.go
index 5a8295d..022bef4 100644
--- a/internal/artwork/fixmatch_test.go
+++ b/internal/artwork/fixmatch_test.go
@@ -1,13 +1,18 @@
package artwork
import (
+ "io"
+ "net/http"
+ "regexp"
+ "strings"
+ "sync"
"testing"
+ "time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
-// A junk name (a bare number such as a Blu-ray's "00062") is never looked up, unless the user gave it a pinned
-// cover or an alias in Fix a match.
+// A junk name (a bare number such as a Blu-ray's "00062") is never looked up, unless the user fixed it in Fix a match.
func TestFixAMatchWinsOverJunk(t *testing.T) {
cfg := core.DefaultConfig()
cfg.ArtworkSources, cfg.EpisodeSources, cfg.RichInfo = []string{}, []string{}, false // no catalog is asked
@@ -20,15 +25,389 @@ func TestFixAMatchWinsOverJunk(t *testing.T) {
}
const poster = "https://images.example/sample-movie.jpg"
- cfg.ArtworkOverrides = map[string]string{"00062": poster}
+ cfg.MatchFixes = []core.MatchFix{{Match: "00062", Cover: poster}}
art := New(&cfg, Options{}).Lookup(media)
if art == nil || art.Poster != poster || art.Source != "override" {
t.Fatalf("the pinned cover of a junk name was not used: %+v", art)
}
- cfg.ArtworkOverrides = map[string]string{}
- cfg.ArtworkAliases = map[string]string{"00062": "Sample Movie"}
- if a := New(&cfg, Options{}); !a.fixed(media.Title) || a.fixed("00063") {
- t.Fatal("an alias should mark exactly its own title as fixed")
+ cfg.MatchFixes = []core.MatchFix{{Match: "00062", Search: "Sample Movie"}}
+ a := New(&cfg, Options{})
+ if a.FixFor(media) == nil || a.FixFor(core.ParseMedia("00063.m2ts", &cfg, nil)) != nil {
+ t.Fatal("a fix should mark exactly its own title as fixed")
+ }
+}
+
+// Old artworkAliases and artworkOverrides lines act as before while config.json has no matchFixes: the same search,
+// the same cache key, the same pinned cover.
+func TestLegacyLinesActAsBefore(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.ArtworkSources, cfg.EpisodeSources = []string{}, []string{}
+ cfg.ArtworkAliases = map[string]string{"sample movie": "Sample Film", "Sample Show": "Sample Series"}
+ cfg.ArtworkOverrides = map[string]string{"sample show": "https://img.example/show.jpg", "other": "not an address"}
+ if cfg.MatchFixes != nil {
+ t.Fatal("the default must be nil (no matchFixes key)")
+ }
+ a := New(&cfg, Options{})
+ movie := core.ParseMedia("Sample Movie (2020).mkv", &cfg, nil)
+ j := a.newLookupJob(movie)
+ if j.query != "Sample Film" || j.key != keyVersion+"m|"+normTitle("Sample Movie")+"|2020|"+normTitle("Sample Film")+"||" {
+ t.Errorf("alias: query %q, key %q", j.query, j.key)
+ }
+ plain := core.ParseMedia("Another Movie (2020).mkv", &cfg, nil)
+ if j := a.newLookupJob(plain); j.key != keyVersion+"m|"+normTitle("Another Movie")+"|2020|"+normTitle("")+"||" || j.fix != nil {
+ t.Errorf("a title nobody fixed must keep its key: %q", j.key)
+ }
+ show := core.ParseMedia("Sample Show S01E02.mkv", &cfg, nil)
+ if art := a.Lookup(show); art == nil || art.Source != "override" || art.Poster != "https://img.example/show.jpg" {
+ t.Errorf("a title in both maps keeps its pinned cover (it always won): %+v", art)
+ }
+ // a pinned cover that is no image address is not used, as before
+ var warned []string
+ a = New(&cfg, Options{Log: func(_, m string) { warned = append(warned, m) }})
+ if art := a.Lookup(core.ParseMedia("Other.mkv", &cfg, nil)); art != nil {
+ t.Errorf("a bad cover address was used: %+v", art)
+ }
+ if strings.Count(strings.Join(warned, " / "), "http(s) image address") != 1 {
+ t.Errorf("warnings: %q", warned)
+ }
+
+ // an empty matchFixes (saved by the window) means no fixes: the old lines are no longer read
+ cfg.MatchFixes = []core.MatchFix{}
+ if New(&cfg, Options{}).FixFor(movie) != nil {
+ t.Error("with matchFixes saved, the legacy lines must not be read")
+ }
+}
+
+// A fix for one file wins over a fix for its title, and only matches that file name (any case).
+func TestFileFixBeatsTitleFix(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.MatchFixes = []core.MatchFix{
+ {Match: "Sample Show", Search: "Sample Series"},
+ {Match: "sample.show.s01e02.mkv", File: true, Search: "Sample Special"},
+ }
+ a := New(&cfg, Options{})
+ m := core.ParseMedia("Sample.Show.S01E02.mkv", &cfg, nil)
+ if fx := a.FixFor(m); fx == nil || fx.Search != "Sample Series" {
+ t.Fatalf("without a file name the title fix applies: %+v", fx)
+ }
+ m.File = "Sample.Show.S01E02.mkv"
+ if fx := a.FixFor(m); fx == nil || fx.Search != "Sample Special" {
+ t.Errorf("the file fix should win: %+v", fx)
+ }
+ m2 := core.ParseMedia("Sample.Show.S01E03.mkv", &cfg, nil)
+ m2.File = "Sample.Show.S01E03.mkv"
+ if fx := a.FixFor(m2); fx == nil || fx.Search != "Sample Series" {
+ t.Errorf("another episode gets the title fix: %+v", fx)
+ }
+}
+
+// fakeCatalogs answers by path, counts requests per host and when they came.
+type fakeCatalogs struct {
+ mu sync.Mutex
+ routes []fakeRoute
+ hosts map[string][]time.Time
+ paths []string
+}
+
+type fakeRoute struct {
+ re *regexp.Regexp
+ body string
+}
+
+func newFakeCatalogs(routes ...string) *fakeCatalogs {
+ f := &fakeCatalogs{hosts: map[string][]time.Time{}}
+ for i := 0; i+1 < len(routes); i += 2 {
+ f.routes = append(f.routes, fakeRoute{regexp.MustCompile(routes[i]), routes[i+1]})
+ }
+ return f
+}
+
+func (f *fakeCatalogs) RoundTrip(req *http.Request) (*http.Response, error) {
+ where := req.URL.Host + req.URL.RequestURI()
+ if req.Body != nil {
+ b, _ := io.ReadAll(req.Body)
+ where += " " + string(b)
+ }
+ f.mu.Lock()
+ f.hosts[req.URL.Host] = append(f.hosts[req.URL.Host], time.Now())
+ f.paths = append(f.paths, where)
+ f.mu.Unlock()
+ body, status := "{}", 200
+ for _, r := range f.routes {
+ if r.re.MatchString(where) {
+ body = r.body
+ break
+ }
+ }
+ if body == "404" {
+ body, status = `{"status":404}`, 404
+ }
+ return &http.Response{StatusCode: status, Status: http.StatusText(status), Header: http.Header{"Content-Type": {"application/json"}},
+ Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+}
+
+func (f *fakeCatalogs) count(host string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.hosts[host])
+}
+
+func (f *fakeCatalogs) total() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.paths)
+}
+
+const (
+ imdbEntryJSON = `{"d":[{"id":"tt0000001","l":"The Sample Show","y":1998,"qid":"tvSeries","i":{"imageUrl":"https://img.example/ts.jpg"}}]}`
+ tvmazeShowJSON = `{"id":42,"name":"Sample Show","premiered":"2019-01-01","url":"https://www.tvmaze.com/shows/42/sample-show","image":{"medium":"https://img.example/ss.jpg"},"externals":{}}`
+ tvmazeSeasons = `[{"number":1,"name":"","image":{"medium":"https://img.example/ss-s1.jpg"}}]`
+)
+
+func pinConfig() core.Config {
+ cfg := core.DefaultConfig()
+ cfg.RequestGapMs = map[string]int{}
+ cfg.EpisodeTitles, cfg.RichInfo, cfg.LinkButton = false, false, false
+ cfg.AnimeTitles = "file"
+ return cfg
+}
+
+// A pinned page is read by its id, from the catalog it belongs to, and a show gets its season's poster.
+func TestPinnedEntry(t *testing.T) {
+ fake := newFakeCatalogs(
+ `^v3\.sg\.media-imdb\.com/suggestion/t/tt0000001\.json`, imdbEntryJSON,
+ `^api\.tvmaze\.com/shows/42/seasons`, tvmazeSeasons,
+ `^api\.tvmaze\.com/shows/42$`, tvmazeShowJSON,
+ `^graphql\.anilist\.co.*Media\(id`, `{"data":{"Media":{"siteUrl":"https://anilist.co/anime/7","format":"MOVIE","title":{"romaji":"Sample Eiga","english":"Sample Movie"},"startDate":{"year":2020},"coverImage":{"large":"https://img.example/sm.jpg"}}}}`,
+ `^kitsu\.io/api/edge/anime\?filter\[slug\]=sample-anime`, `{"data":[{"id":"9","attributes":{"subtype":"TV","canonicalTitle":"Sample Anime","slug":"sample-anime","startDate":"2018-04-01","posterImage":{"large":"https://img.example/sa.jpg"}}}]}`,
+ )
+ cases := []struct {
+ entry, file, name, source, typ, poster string
+ }{
+ {"https://www.imdb.com/title/tt0000001/", "Sample Show S01E02.mkv", "The Sample Show", "IMDb", "series", "https://img.example/ts.jpg"},
+ {"https://www.tvmaze.com/shows/42/sample-show", "Sample Show S01E02.mkv", "Sample Show", "TVmaze", "series", "https://img.example/ss-s1.jpg"},
+ {"https://anilist.co/anime/7/sample-eiga", "Sample Eiga.mkv", "Sample Eiga", "AniList", "movie", "https://img.example/sm.jpg"},
+ {"https://kitsu.io/anime/sample-anime", "Sample Anime - 03.mkv", "Sample Anime", "Kitsu", "series", "https://img.example/sa.jpg"},
+ }
+ for _, c := range cases {
+ cfg := pinConfig()
+ media := core.ParseMedia(c.file, &cfg, nil)
+ cfg.MatchFixes = []core.MatchFix{{Match: media.Title, Entry: c.entry}}
+ before := fake.total()
+ art := New(&cfg, Options{Client: &http.Client{Transport: fake}}).Lookup(media)
+ if art == nil || art.Name != c.name || art.Source != c.source || art.Type != c.typ || art.Poster != c.poster {
+ t.Errorf("%s: %+v", c.entry, art)
+ continue
+ }
+ if fake.total()-before > 2 {
+ t.Errorf("%s: %d requests, want one or two (no search)", c.entry, fake.total()-before)
+ }
+ if !isPinned(&cfg.MatchFixes[0], art) {
+ t.Errorf("%s: not recognised as the pinned entry: %+v", c.entry, art)
+ }
+ }
+
+ // a user's image over a pinned entry
+ cfg := pinConfig()
+ media := core.ParseMedia("Sample Show S01E02.mkv", &cfg, nil)
+ cfg.MatchFixes = []core.MatchFix{{Match: "sample show", Entry: "https://www.imdb.com/title/tt0000001/", Cover: "https://img.example/mine.jpg"}}
+ if art := New(&cfg, Options{Client: &http.Client{Transport: fake}}).Lookup(media); art == nil || art.Name != "The Sample Show" || art.Poster != "https://img.example/mine.jpg" {
+ t.Errorf("cover over a pinned entry: %+v", art)
+ }
+}
+
+// A pinned page that is gone, or whose catalog is off under Privacy, falls back to searching the read title, with a
+// warning; a switched-off catalog is never asked.
+func TestPinnedEntryFallsBack(t *testing.T) {
+ fake := newFakeCatalogs(
+ `^v3\.sg\.media-imdb\.com/suggestion/t/tt0000002\.json`, `{"d":[]}`,
+ `^v3\.sg\.media-imdb\.com/suggestion/s/sample%20show\.json`, `{"d":[{"id":"tt0000003","l":"Sample Show","y":2019,"qid":"tvSeries","i":{"imageUrl":"https://img.example/found.jpg"}}]}`,
+ `^v3-cinemeta\.strem\.io/meta/`, `{}`,
+ `^api\.tvmaze\.com/lookup/shows`, `404`,
+ )
+ for _, off := range [][]string{nil, {"imdb", "cinemeta", "tvmaze"}} {
+ cfg := pinConfig()
+ cfg.ArtworkSources = []string{"imdb"}
+ cfg.DisabledSources = off
+ if off != nil {
+ cfg.ArtworkSources = []string{"imdb", "anilist"}
+ cfg.DisabledSources = []string{"cinemeta", "tvmaze"} // the page's catalogs but IMDb are off
+ }
+ media := core.ParseMedia("Sample Show S01E02.mkv", &cfg, nil)
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", Entry: "https://www.imdb.com/title/tt0000002/"}}
+ var logs []string
+ var mu sync.Mutex
+ before := fake.count("api.tvmaze.com")
+ art := New(&cfg, Options{Client: &http.Client{Transport: fake}, Log: func(l, m string) { mu.Lock(); logs = append(logs, l+" "+m); mu.Unlock() }}).Lookup(media)
+ if art == nil || art.Name != "Sample Show" || art.Poster != "https://img.example/found.jpg" {
+ t.Errorf("off %v: no fallback: %+v", off, art)
+ }
+ mu.Lock()
+ if !strings.Contains(strings.Join(logs, "\n"), "WARN The entry pinned for \"Sample Show\" was not found") {
+ t.Errorf("off %v: no warning: %q", off, logs)
+ }
+ mu.Unlock()
+ if off != nil && fake.count("api.tvmaze.com") != before {
+ t.Errorf("TVmaze is off but was asked")
+ }
+ }
+}
+
+// The dialog's search asks at most three catalogs that are on, through the usual network path, and gives each entry
+// once, exact names first; the same search again asks nothing.
+func TestSuggest(t *testing.T) {
+ fake := newFakeCatalogs(
+ `^v3\.sg\.media-imdb\.com/suggestion/s/sample%20show\.json`, `{"d":[{"id":"tt0000004","l":"Sample Show Returns","y":2021,"qid":"tvSeries"},{"id":"tt0000003","l":"Sample Show","y":2019,"qid":"tvSeries","i":{"imageUrl":"https://img.example/a.jpg"}},{"id":"tt0000005","l":"Sample Show: The Movie","y":2022,"qid":"movie"}]}`,
+ `^api\.tvmaze\.com/search/shows`, `[{"show":{"id":42,"name":"Sample Show","premiered":"2019-01-01","url":"https://www.tvmaze.com/shows/42/sample-show","externals":{"imdb":"tt0000003"}}},{"show":{"id":43,"name":"Sample Show","premiered":"2024-01-01","url":"https://www.tvmaze.com/shows/43/sample-show"}}]`,
+ `^graphql\.anilist\.co`, `{"data":{"Page":{"media":[]}}}`,
+ )
+ cfg := pinConfig()
+ a := New(&cfg, Options{Client: &http.Client{Transport: fake}})
+ cats := a.SuggestCatalogs()
+ var names []string
+ for _, p := range cats {
+ names = append(names, p.Label)
+ }
+ if strings.Join(names, ",") != "IMDb,TVmaze,AniList" {
+ t.Errorf("catalogs %v, want IMDb, TVmaze and AniList (TMDB has no key, Cinemeta lists IMDb's entries)", names)
+ }
+ list, err := a.Suggest("Sample Show")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, s := range list {
+ got = append(got, s.Name+"|"+s.Catalog+"|"+s.Kind+"|"+s.Entry)
+ }
+ want := []string{
+ "Sample Show|IMDb|series|https://www.imdb.com/title/tt0000003/",
+ "Sample Show|TVmaze|series|https://www.tvmaze.com/shows/43/sample-show",
+ "Sample Show Returns|IMDb|series|https://www.imdb.com/title/tt0000004/",
+ "Sample Show: The Movie|IMDb|movie|https://www.imdb.com/title/tt0000005/",
+ }
+ if strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Errorf("suggestions:\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+ if fake.count("v3-cinemeta.strem.io") != 0 || fake.count("kitsu.io") != 0 || fake.count("en.wikipedia.org") != 0 {
+ t.Errorf("a catalog beyond the three was asked: %v", fake.paths)
+ }
+ n := fake.total()
+ if _, err := a.Suggest("sample show"); err != nil || fake.total() != n {
+ t.Errorf("the same search asked again (%d new requests)", fake.total()-n)
+ }
+ if l, _ := a.Suggest("S"); l != nil {
+ t.Errorf("one character is no search: %v", l)
+ }
+
+ // Privacy: a switched-off catalog is not asked; with every one off nothing is
+ cfg2 := pinConfig()
+ cfg2.DisabledSources = []string{"imdb", "tvmaze"}
+ a2 := New(&cfg2, Options{Client: &http.Client{Transport: fake}})
+ before := fake.count("v3.sg.media-imdb.com") + fake.count("api.tvmaze.com")
+ _, _ = a2.Suggest("Sample Show Two")
+ if fake.count("v3.sg.media-imdb.com")+fake.count("api.tvmaze.com") != before {
+ t.Error("a switched-off catalog was asked")
+ }
+ cfg3 := pinConfig()
+ cfg3.ShowArtwork = false
+ if c := New(&cfg3, Options{}).SuggestCatalogs(); len(c) != 0 {
+ t.Errorf("with lookups off no catalog may be asked: %v", c)
+ }
+
+ // each host's request gap applies
+ cfg4 := pinConfig()
+ cfg4.RequestGapMs = map[string]int{"api.tvmaze.com": 150}
+ a4 := New(&cfg4, Options{Client: &http.Client{Transport: fake}})
+ start := fake.count("api.tvmaze.com")
+ _, _ = a4.Suggest("Sample Gap One")
+ _, _ = a4.Suggest("Sample Gap Two")
+ fake.mu.Lock()
+ ts := fake.hosts["api.tvmaze.com"][start:]
+ fake.mu.Unlock()
+ if len(ts) != 2 || ts[1].Sub(ts[0]) < 120*time.Millisecond {
+ t.Errorf("TVmaze's request gap was not kept: %v", ts)
+ }
+}
+
+// The cover step asks the other catalogs once each, picks their match of the title, and gives at most five covers.
+func TestCovers(t *testing.T) {
+ fake := newFakeCatalogs(
+ `^v3-cinemeta\.strem\.io/catalog/series/top/search=Sample%20Show`, `{"metas":[{"name":"Sample Show","releaseInfo":"2019","poster":"https://img.example/cm.jpg","imdb_id":"tt0000003"}]}`,
+ `^api\.tvmaze\.com/search/shows`, `[{"show":{"id":42,"name":"Sample Show","premiered":"2019-01-01","url":"https://www.tvmaze.com/shows/42","image":{"medium":"https://img.example/tv.jpg"}}}]`,
+ `^v3\.sg\.media-imdb\.com`, `{"d":[{"id":"tt0000003","l":"Sample Show","y":2019,"qid":"tvSeries","i":{"imageUrl":"https://img.example/imdb.jpg"}}]}`,
+ `^kitsu\.io`, `{"data":[{"id":"1","attributes":{"subtype":"TV","canonicalTitle":"Sample Show","startDate":"2019-01-01","posterImage":{"large":"https://img.example/tv.jpg"}}}]}`,
+ )
+ cfg := pinConfig()
+ a := New(&cfg, Options{Client: &http.Client{Transport: fake}})
+ covers := a.Covers("Sample Show", 2019, "series", "IMDb")
+ var got []string
+ for _, c := range covers {
+ got = append(got, c.Catalog+" "+c.URL)
+ }
+ if strings.Join(got, ", ") != "Cinemeta https://img.example/cm.jpg, TVmaze https://img.example/tv.jpg" {
+ t.Errorf("covers: %v", got)
+ }
+ if fake.count("v3.sg.media-imdb.com") != 0 {
+ t.Error("the pinned entry's own catalog was asked")
+ }
+ n := fake.total()
+ a.Covers("Sample Show", 2019, "series", "IMDb")
+ if fake.total() != n {
+ t.Error("the same covers were asked again")
+ }
+}
+
+// Offsets move the numbers read from the file (after the folder's count), and 0 and 0 change nothing.
+func TestOffsets(t *testing.T) {
+ cfg := core.DefaultConfig()
+ m := core.ParseMedia("Sample Show S02E02.mkv", &cfg, nil)
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", EpisodeOffset: 12}}
+ a := New(&cfg, Options{})
+ got, shifted := a.Offset(m)
+ if !shifted || got.Season != 2 || got.Episode != 14 || got.Label != "S02E14" || m.Episode != 2 {
+ t.Errorf("offset: %+v (shifted %v); the original must stay %d", got, shifted, m.Episode)
+ }
+
+ withFolder := *m
+ withFolder.BadgeEpisode = 5 // folderEpisodeNumbers counted this file as the fifth
+ if got, _ := a.Offset(&withFolder); got.BadgeEpisode != 17 || got.Episode != 14 {
+ t.Errorf("with the folder's count: %+v", got)
+ }
+
+ var warned []string
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", SeasonOffset: -5}}
+ a = New(&cfg, Options{Log: func(_, msg string) { warned = append(warned, msg) }})
+ if got, shifted := a.Offset(m); shifted || got != m || len(warned) != 1 {
+ t.Errorf("below 1: %+v %v %q", got, shifted, warned)
+ }
+
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", Search: "Sample Series"}}
+ if got, shifted := New(&cfg, Options{}).Offset(m); shifted || got != m {
+ t.Error("0 and 0 must be today's path")
+ }
+ film := core.ParseMedia("Sample Show (2020).mkv", &cfg, nil)
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", EpisodeOffset: 3}}
+ if got, shifted := New(&cfg, Options{}).Offset(film); shifted || got != film {
+ t.Error("a film has no episode to move")
+ }
+}
+
+// "Why this title?" says a title was fixed, and how.
+func TestExplainAFix(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Show", Entry: "https://www.tvmaze.com/shows/42/sample-show"}}
+ a := New(&cfg, Options{})
+ show := core.ParseMedia("Sample Show - S01E02.mkv", &cfg, nil)
+ hit := core.NewArt()
+ hit.Type, hit.Name, hit.Source, hit.URL = "series", "Sample Show", "TVmaze", "https://www.imdb.com/title/tt0000003/"
+ hit.IDs = &core.ArtIDs{Tvmaze: "42"}
+ got := strings.Join(a.Explain(show, hit), "\n")
+ if !strings.Contains(got, `Fixed by you in Fix a match (every file read as "Sample Show").`) || !strings.Contains(got, `Matched as you chose: TVmaze "Sample Show" (a show).`) {
+ t.Errorf("pinned:\n%s", got)
+ }
+ hit.IDs = nil
+ if got := strings.Join(a.Explain(show, hit), "\n"); !strings.Contains(got, `Matched by TVmaze: "Sample Show"`) {
+ t.Errorf("a search after the pinned page failed is no pinned match:\n%s", got)
}
}
diff --git a/internal/artwork/fuzz_test.go b/internal/artwork/fuzz_test.go
index 1acb12c..79c1b74 100644
--- a/internal/artwork/fuzz_test.go
+++ b/internal/artwork/fuzz_test.go
@@ -6,7 +6,7 @@ import (
"os"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func TestFuzzAgainstJS(t *testing.T) {
diff --git a/internal/artwork/jx.go b/internal/artwork/jx.go
index 9384230..370a2b4 100644
--- a/internal/artwork/jx.go
+++ b/internal/artwork/jx.go
@@ -5,7 +5,7 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
)
// OMap is an order-preserving JSON object (see jsonx).
diff --git a/internal/artwork/letterboxd.go b/internal/artwork/letterboxd.go
index 567da23..12a22ec 100644
--- a/internal/artwork/letterboxd.go
+++ b/internal/artwork/letterboxd.go
@@ -7,7 +7,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Letterboxd (letterboxdLink): letterboxd.com/imdb// and, for films, /tmdb// redirect to the title's page
diff --git a/internal/artwork/letterboxd_test.go b/internal/artwork/letterboxd_test.go
index 70ed0ac..7323349 100644
--- a/internal/artwork/letterboxd_test.go
+++ b/internal/artwork/letterboxd_test.go
@@ -9,7 +9,7 @@ import (
"sync"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakeLetterboxd is Cinemeta with one film (tt0000001) and Letterboxd answering with lb (the status for that id:
diff --git a/internal/artwork/live_test.go b/internal/artwork/live_test.go
index 1adf253..2e184ce 100644
--- a/internal/artwork/live_test.go
+++ b/internal/artwork/live_test.go
@@ -7,13 +7,13 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The weekly canary (.github/workflows/canary.yml) asks every keyless catalog about one long-known title, through the
// same search and episode code the program uses, and fails when a service stops answering or changes the shape of
// its answer: no match, a wrong year, no link, no cover, no episode names. It contacts the real services, so it is
-// opt-in (MPCRPC_LIVE_CATALOGS=1). TMDB needs a key and the public Jikan closed, so neither is asked.
+// opt-in (MPRP_LIVE_CATALOGS=1). TMDB needs a key and the public Jikan closed, so neither is asked.
//
// A catalog check needs real titles: these are chosen because they are old, listed by every catalog, and unlikely to
// be renamed.
@@ -29,8 +29,8 @@ var (
)
func TestLiveCatalogs(t *testing.T) {
- if os.Getenv("MPCRPC_LIVE_CATALOGS") != "1" {
- t.Skip("set MPCRPC_LIVE_CATALOGS=1 to ask the real catalog services")
+ if os.Getenv("MPRP_LIVE_CATALOGS") != "1" {
+ t.Skip("set MPRP_LIVE_CATALOGS=1 to ask the real catalog services")
}
cfg := core.DefaultConfig()
// ask retries a service that is down or slow twice, half a minute apart, each time with a fresh finder (a failing
diff --git a/internal/artwork/match.go b/internal/artwork/match.go
index aad4f09..1b9b438 100644
--- a/internal/artwork/match.go
+++ b/internal/artwork/match.go
@@ -8,8 +8,8 @@ import (
"strings"
"unicode/utf16"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
func re(p, flags string) *jsre.Regexp { return jsre.MustCompile(p, flags) }
diff --git a/internal/artwork/names_test.go b/internal/artwork/names_test.go
index c24fcc1..f6396e5 100644
--- a/internal/artwork/names_test.go
+++ b/internal/artwork/names_test.go
@@ -9,7 +9,7 @@ import (
"sync"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// A film named ": A Mystery" loses its colon in a file name; the catalogs list "".
diff --git a/internal/artwork/net.go b/internal/artwork/net.go
index 17b6de7..dc5b8ba 100644
--- a/internal/artwork/net.go
+++ b/internal/artwork/net.go
@@ -24,8 +24,21 @@ import (
// text (fetchText), which has none of that (no cache, spacing, retry or breaker); the Resolver keeps the page for
// six hours itself.
-// userAgent is what every request says it is (Wikipedia answers 403 to Go's default client string).
-const userAgent = "MPCvibedRPC (Discord Rich Presence for video players; https://github.com/CptPakundo/MPCvibedRPC)"
+// userAgent is what every request says it is (Wikipedia answers 403 to Go's default client string). It names the
+// program's version as Wikimedia's User-Agent policy shows (name/version, then a link); SetVersion fills it in.
+var userAgent = agentFor("")
+
+// agentFor is the User-Agent of version v ("": none known, as in the tests).
+func agentFor(v string) string {
+ name := "MPRP"
+ if v != "" {
+ name += "/" + v
+ }
+ return name + " (Discord Rich Presence for media players; https://github.com/CptPakundo/MPRP)"
+}
+
+// SetVersion puts the program's version in the User-Agent. Call it once at the start, before any request.
+func SetVersion(v string) { userAgent = agentFor(v) }
const (
respTTL = 10 * time.Minute
diff --git a/internal/artwork/providers.go b/internal/artwork/providers.go
index 2eb1d28..66de225 100644
--- a/internal/artwork/providers.go
+++ b/internal/artwork/providers.go
@@ -6,8 +6,8 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
var (
@@ -151,16 +151,7 @@ func buildProviders() map[string]*Provider {
}
var out []*Cand
for _, r := range asArr(get(j, "results")) {
- c := &Cand{
- Titles: nonEmptyTitles(get(r, "name"), get(r, "title"), get(r, "original_name"), get(r, "original_title")),
- Year: yearOf(firstTruthy(get(r, "first_air_date"), get(r, "release_date"))),
- URL: "https://www.themoviedb.org/" + kind + "/" + tmpl(get(r, "id")),
- URLLabel: "TMDB", Ref: str(get(r, "id")), Kind: kind,
- }
- if truthy(get(r, "poster_path")) {
- c.Poster = posterIf(str(get(r, "poster_path")))
- }
- out = append(out, c)
+ out = append(out, tmdbCand(r, kind))
}
return out, nil
},
@@ -190,10 +181,7 @@ func buildProviders() map[string]*Provider {
}
var out []*Cand
for _, m := range asArr(get(j, "metas")) {
- out = append(out, &Cand{
- Titles: nonEmptyTitles(get(m, "name")), Year: yearOf(get(m, "releaseInfo")), Poster: str(get(m, "poster")),
- URL: imdbURL(str(firstTruthy(get(m, "imdb_id"), get(m, "id")))), URLLabel: "IMDb",
- })
+ out = append(out, cinemetaCand(m))
}
return out, nil
},
@@ -222,12 +210,7 @@ func buildProviders() map[string]*Provider {
if !slices.Contains(want, qid) {
continue
}
- c := &Cand{Titles: nonEmptyTitles(get(d, "l")), Year: yearNum(get(d, "y")), URL: imdbURL(str(get(d, "id"))), URLLabel: "IMDb"}
- if truthy(get(d, "i")) {
- c.Poster = str(get(d, "i", "imageUrl"))
- }
- c.l0 = tmpl(get(d, "l"))
- list = append(list, c)
+ list = append(list, imdbCand(d))
}
if len(list) > 0 {
qw := map[string]bool{}
@@ -262,16 +245,7 @@ func buildProviders() map[string]*Provider {
if !truthy(s) {
continue
}
- c := &Cand{Titles: nonEmptyTitles(get(s, "name")), Year: yearOf(get(s, "premiered")), Ref: str(get(s, "id")), ID: str(get(s, "id"))}
- if truthy(get(s, "image")) {
- c.Poster = orStr(get(s, "image", "medium"), str(get(s, "image", "original")))
- }
- if u := imdbURL(str(get(s, "externals", "imdb"))); u != "" {
- c.URL, c.URLLabel = u, "IMDb"
- } else {
- c.URL, c.URLLabel = str(get(s, "url")), "TVmaze"
- }
- out = append(out, c)
+ out = append(out, tvmazeCand(s))
}
return out, nil
},
@@ -312,9 +286,7 @@ func buildProviders() map[string]*Provider {
P["anilist"] = &Provider{
Label: "AniList", Types: []string{"movie", "series"}, Earliest: true,
Search: func(a *Artwork, typ, query string, media *core.Media) ([]*Cand, error) {
- gql := "query ($s: String!) { Page(perPage: 25) { media(search: $s, type: ANIME, sort: SEARCH_MATCH) { " +
- "siteUrl format episodes duration genres averageScore startDate { year } title { romaji english native } synonyms coverImage { large } " +
- "staff(perPage: 8, sort: RELEVANCE) { edges { role node { name { full } } } } } } }"
+ gql := "query ($s: String!) { Page(perPage: 25) { media(search: $s, type: ANIME, sort: SEARCH_MATCH) { " + anilistFields + " } } }"
body := jsonString(struct {
Query string `json:"query"`
Variables map[string]string `json:"variables"`
@@ -328,16 +300,7 @@ func buildProviders() map[string]*Provider {
if wrongKind(typ, get(m, "format") == "MOVIE") {
continue
}
- titles := nonEmptyTitles(get(m, "title", "romaji"), get(m, "title", "english"), get(m, "title", "native"))
- titles = append(titles, nonEmptyTitles(asArr(get(m, "synonyms"))...)...)
- c := &Cand{Titles: titles, Year: yearNum(get(m, "startDate", "year")), URL: str(get(m, "siteUrl")), URLLabel: "AniList",
- Runtime: optPositive(get(m, "duration")), Eps: optPositive(get(m, "episodes")),
- Alt: &core.ArtAlt{English: orStr(get(m, "title", "english"), ""), Romaji: orStr(get(m, "title", "romaji"), "")},
- AniInfo: aniInfoOf(m)}
- if truthy(get(m, "coverImage")) {
- c.Poster = str(get(m, "coverImage", "large"))
- }
- out = append(out, c)
+ out = append(out, anilistCand(m))
}
return out, nil
},
@@ -354,30 +317,10 @@ func buildProviders() map[string]*Provider {
}
var out []*Cand
for _, d := range asArr(get(j, "data")) {
- attrs := get(d, "attributes")
- if !truthy(attrs) {
- attrs = &OMap{M: map[string]any{}}
- }
- if wrongKind(typ, get(attrs, "subtype") == "movie") {
+ if wrongKind(typ, get(d, "attributes", "subtype") == "movie") {
continue
}
- t := get(attrs, "titles")
- titles := nonEmptyTitles(get(attrs, "canonicalTitle"), get(t, "en"), get(t, "en_jp"), get(t, "en_us"), get(t, "ja_jp"))
- titles = append(titles, nonEmptyTitles(asArr(get(attrs, "abbreviatedTitles"))...)...)
- score := num(get(attrs, "averageRating"))
- c := &Cand{Titles: titles, Year: yearOf(get(attrs, "startDate")), Ref: str(get(d, "id")), ID: str(get(d, "id")),
- URLLabel: "Kitsu", Runtime: optPositive(get(attrs, "episodeLength")), Eps: optPositive(get(attrs, "episodeCount")),
- Alt: &core.ArtAlt{English: orStr(firstTruthy(get(t, "en"), get(t, "en_us")), ""), Romaji: orStr(firstTruthy(get(t, "en_jp"), get(attrs, "canonicalTitle")), "")}}
- if truthy(get(attrs, "posterImage")) {
- c.Poster = str(firstTruthy(get(attrs, "posterImage", "large"), get(attrs, "posterImage", "medium"), get(attrs, "posterImage", "original")))
- }
- if truthy(get(attrs, "slug")) {
- c.URL = "https://kitsu.io/anime/" + str(get(attrs, "slug"))
- }
- if score > 0 {
- c.AniInfo = &core.ArtInfo{Genres: []string{}, Rating: jsRound(score) / 10}
- }
- out = append(out, c)
+ out = append(out, kitsuCand(d))
}
return out, nil
},
diff --git a/internal/artwork/pure_test.go b/internal/artwork/pure_test.go
index 8917886..7acff49 100644
--- a/internal/artwork/pure_test.go
+++ b/internal/artwork/pure_test.go
@@ -5,7 +5,7 @@ import (
"reflect"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// recCand is a candidate as the recorded data writes it.
diff --git a/internal/artwork/replay_test.go b/internal/artwork/replay_test.go
index 611ffb0..d3829f7 100644
--- a/internal/artwork/replay_test.go
+++ b/internal/artwork/replay_test.go
@@ -15,7 +15,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
type recResp struct {
diff --git a/internal/artwork/seasons.go b/internal/artwork/seasons.go
index 43ed813..60e60ae 100644
--- a/internal/artwork/seasons.go
+++ b/internal/artwork/seasons.go
@@ -7,8 +7,8 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// ---- seasons that are really separate titles -----------------------------------------
diff --git a/internal/artwork/specials_test.go b/internal/artwork/specials_test.go
index d598e6a..310237a 100644
--- a/internal/artwork/specials_test.go
+++ b/internal/artwork/specials_test.go
@@ -9,7 +9,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakeSpecials answers like Cinemeta for "Sample Show" (tt0000555): two specials as season 0, then a season of six.
diff --git a/internal/artwork/why.go b/internal/artwork/why.go
index 2a48525..d46cb3a 100644
--- a/internal/artwork/why.go
+++ b/internal/artwork/why.go
@@ -4,7 +4,7 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Explain says in a few lines how the catalogs answered for media, for "Why this title?" in Copy diagnostics: which
@@ -20,8 +20,16 @@ func (a *Artwork) Explain(media *core.Media, found *core.Art) []string {
var out []string
add := func(s string) { out = append(out, s) }
nt := normTitle(media.Title)
- if alias := a.aliases[nt]; alias != "" {
- add(`Searched as "` + alias + `" (Fix a match > Search under another name).`)
+ fx := a.FixFor(media)
+ if fx != nil {
+ scope := `every file read as "` + fx.Match + `"`
+ if fx.File {
+ scope = "only this file"
+ }
+ add("Fixed by you in Fix a match (" + scope + ").")
+ if fx.Search != "" && fx.Entry == "" {
+ add(`Searched as "` + fx.Search + `".`)
+ }
}
if found == nil {
j := a.newLookupJob(media)
@@ -42,9 +50,12 @@ func (a *Artwork) Explain(media *core.Media, found *core.Art) []string {
return out
}
if found.Source == "override" {
- add("Cover pinned by you (Fix a match > Pin a cover image).")
+ add("Cover pinned by you (Fix a match).")
} else {
m := "Matched by " + found.Source + `: "` + found.Name + `"`
+ if fx != nil && isPinned(fx, found) {
+ m = "Matched as you chose: " + found.Source + ` "` + found.Name + `"`
+ }
var bits []string
if found.Year != core.NA && found.Year != 0 {
bits = append(bits, strconv.Itoa(found.Year))
diff --git a/internal/artwork/why_test.go b/internal/artwork/why_test.go
index 322bda8..efeb724 100644
--- a/internal/artwork/why_test.go
+++ b/internal/artwork/why_test.go
@@ -5,12 +5,12 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func TestExplain(t *testing.T) {
cfg := core.DefaultConfig()
- cfg.ArtworkAliases = map[string]string{"Sample Movie": "Sample Film"}
+ cfg.MatchFixes = []core.MatchFix{{Match: "Sample Movie", Search: "Sample Film"}}
a := New(&cfg, Options{})
movie := core.ParseMedia("Sample Movie (2020).mkv", &cfg, nil)
show := core.ParseMedia("Sample Show - S01E02.mkv", &cfg, nil)
diff --git a/internal/assets/assets_test.go b/internal/assets/assets_test.go
index c14ae72..f14a6a1 100644
--- a/internal/assets/assets_test.go
+++ b/internal/assets/assets_test.go
@@ -1,12 +1,15 @@
package assets
import (
+ "encoding/json"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
+
+ "github.com/CptPakundo/MPRP/internal/store"
)
// The page's script must parse: no Go test runs it, and one stray apostrophe would leave the window blank.
@@ -24,6 +27,55 @@ func TestPageScriptParses(t *testing.T) {
}
}
+// The page's script behaves: testdata/page_test.js runs ui.js in a small fake DOM built from ui.html, with a stubbed
+// fetch playing the program's API, and checks the saver, the status sync, Text lines and Fix a match. The state it
+// starts from carries the real settings layout and a store's values. Like TestPageScriptParses it needs Node.js (CI
+// runners have it).
+func TestPageBehaviour(t *testing.T) {
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("node is not installed; the page's script cannot be run here")
+ }
+ st, err := store.New(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixes := []map[string]any{
+ {"match": "Sample Show", "entry": "https://www.imdb.com/title/tt0000003/", "label": "Sample Show (2019) · Show · IMDb", "episodeOffset": 12},
+ {"match": "sample.movie.2020.720p.mkv", "file": true, "cover": "https://img.example/sample-movie.jpg"},
+ }
+ if err := st.SetSettings(map[string]any{"matchFixes": fixes}); err != nil {
+ t.Fatal(err)
+ }
+ app := st.App()
+ app.SeenVersion, app.WelcomeSeen = "0.0.0", true
+ state := map[string]any{
+ "version": "0.0.0", "schema": store.SectionsFor("windows"), "os": "windows", "values": st.Values(), "app": app,
+ "status": map[string]any{"running": true, "discord": "connected", "playerAnswers": true, "player": "MPC-HC", "nowPlaying": "Sample Show",
+ "paused": false, "preview": nil, "hideTitle": false, "streamTitle": "auto"},
+ "autoStart": false, "dataDir": "", "update": nil, "changelog": []any{}, "stats": nil, "tray": false,
+ }
+ b, err := json.Marshal(state)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ write := func(name, text string) string {
+ p := filepath.Join(dir, name)
+ if err := os.WriteFile(p, []byte(text), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ cmd := exec.Command(node, filepath.Join("testdata", "page_test.js"), write("ui.html", UI), write("ui.js", JS), write("state.json", string(b)),
+ filepath.Join("..", "core", "testdata", "lines.json"))
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("the page's behaviour tests failed: %v\n%s", err, out)
+ }
+ t.Logf("%s", out)
+}
+
// The page policy (script-src 'self', style-src 'self') allows no inline script or style: the markup must hold none,
// and must load the two files the server serves. The script reads the token from the meta tag.
func TestPageHasNoInlineCode(t *testing.T) {
diff --git a/internal/assets/changelog.json b/internal/assets/changelog.json
index 67dcee7..892a48d 100644
--- a/internal/assets/changelog.json
+++ b/internal/assets/changelog.json
@@ -1,4 +1,16 @@
[
+ {"version": "0.9.60", "date": "2026-11-25", "items": [
+ "✨ MPCvibedRPC is now MPRP, Media Player Rich Presence, with a new logo. Your settings and start-up entry move over by themselves.",
+ "🎮 The status comes from the project's own Discord app: it reads \"Watching MPRP\" when the title is not the name.",
+ "🎯 Fix a match is new: search the catalogs as you type, then pick the title, cover and episode offset, for one file or all.",
+ "✏️ Text lines on the Look tab: Standard, Short, Detailed, or lines of your own for the status.",
+ "⚡ Saving a setting no longer reconnects to Discord, so the status stays put.",
+ "🔐 On Windows, saved sign-ins are encrypted. Going back to an older version means signing in again.",
+ "🔔 Linux and macOS show the same update notices as Windows; macOS asks once whether MPRP may notify.",
+ "🍎 macOS: the app has a new identity, so it may ask again for Local Network access.",
+ "🪟 The settings window's taskbar button has MPRP's own sharp icon. A pin made under the old name stays separate.",
+ "🐛 Fixed: the window's X quits again after a close to the tray did not go through."
+ ]},
{"version": "0.9.58", "date": "2026-11-25", "items": [
"💿 Blu-ray and DVD movies get their real title and cover, from the disc's folder, its own title or its label.",
"🛠️ Fixed: Fix a match now also works for files named only by a number.",
diff --git a/internal/assets/icon-update.ico b/internal/assets/icon-update.ico
index 886bfa6..9122ac0 100644
Binary files a/internal/assets/icon-update.ico and b/internal/assets/icon-update.ico differ
diff --git a/internal/assets/icon.ico b/internal/assets/icon.ico
index 0d12bb7..9febf91 100644
Binary files a/internal/assets/icon.ico and b/internal/assets/icon.ico differ
diff --git a/internal/assets/icons_test.go b/internal/assets/icons_test.go
new file mode 100644
index 0000000..be96df1
--- /dev/null
+++ b/internal/assets/icons_test.go
@@ -0,0 +1,46 @@
+package assets
+
+import (
+ "encoding/binary"
+ "fmt"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// The page names both icons with the version in their addresses (a browser profile keeps a page's icon and would go
+// on showing an older logo), and every size it claims for the .ico is in the file.
+func TestPageIconLinks(t *testing.T) {
+ for _, link := range []string{
+ ``,
+ `href="/icon.ico?v=__VERSION__">`,
+ } {
+ if !strings.Contains(UI, link) {
+ t.Errorf("ui.html has no %s", link)
+ }
+ }
+ m := regexp.MustCompile(`
+// ui.js runs in a small fake DOM built from ui.html, with a stubbed fetch that plays the program's local API. It
+// prints one line per check and exits 1 when one fails.
+const fs = require('fs');
+const vm = require('vm');
+
+const [htmlPath, jsPath, statePath, linesPath] = process.argv.slice(2);
+
+// ---- a small DOM: enough of it for ui.js ------------------------------------------------------------------------
+const camel = (s) => s.replace(/-([a-z])/g, (m, c) => c.toUpperCase());
+class TextNode {
+ constructor(t) { this.nodeType = 3; this.data = String(t); this.parentNode = null; }
+ get textContent() { return this.data; }
+ set textContent(v) { this.data = String(v); }
+ remove() { if (this.parentNode) this.parentNode.removeChild(this); }
+}
+class ClassList {
+ constructor(el) { this.el = el; }
+ get list() { return this.el.className.split(/\s+/).filter(Boolean); }
+ contains(c) { return this.list.includes(c); }
+ add(...cs) { const l = this.list; cs.forEach((c) => { if (!l.includes(c)) l.push(c); }); this.el.className = l.join(' '); }
+ remove(...cs) { this.el.className = this.list.filter((c) => !cs.includes(c)).join(' '); }
+ toggle(c, on) { const has = this.contains(c); const want = on === undefined ? !has : !!on; if (want && !has) this.add(c); if (!want && has) this.remove(c); return want; }
+}
+let doc = null;
+class Element {
+ constructor(tag) {
+ this.nodeType = 1; this.tagName = tag.toUpperCase(); this.childNodes = []; this.parentNode = null;
+ this.attrs = {}; this.dataset = {}; this.listeners = {}; this.style = {}; this.className = ''; this.id = '';
+ this.classList = new ClassList(this); this.disabled = false; this.checked = false; this.selectionStart = null; this.selectionEnd = null;
+ this._value = '';
+ }
+ get children() { return this.childNodes.filter((n) => n.nodeType === 1); }
+ get firstChild() { return this.childNodes[0] || null; }
+ get lastChild() { return this.childNodes[this.childNodes.length - 1] || null; }
+ get textContent() { return this.childNodes.map((n) => n.textContent).join(''); }
+ set textContent(v) { this.childNodes.forEach((n) => { n.parentNode = null; }); this.childNodes = []; if (v !== '' && v != null) this.append(String(v)); }
+ set innerHTML(v) { this.textContent = ''; this._html = v; }
+ get innerHTML() { return this._html || ''; }
+ get value() {
+ if (this.tagName === 'SELECT') { const o = this.options.find((x) => x.selected) || this.options[0]; return o ? o.value : ''; }
+ return this._value;
+ }
+ set value(v) {
+ if (this.tagName === 'SELECT') { this.options.forEach((o) => { o.selected = o.value === String(v); }); return; }
+ this._value = v == null ? '' : String(v);
+ }
+ get options() { return this.children.filter((c) => c.tagName === 'OPTION'); }
+ get isConnected() { let n = this; while (n.parentNode) n = n.parentNode; return n === doc.documentElement; }
+ append(...nodes) { nodes.forEach((n) => this.appendChild(typeof n === 'string' ? new TextNode(n) : n)); }
+ prepend(...nodes) { nodes.reverse().forEach((n) => { const x = typeof n === 'string' ? new TextNode(n) : n; if (x.parentNode) x.parentNode.removeChild(x); x.parentNode = this; this.childNodes.unshift(x); }); }
+ appendChild(n) { if (n.parentNode) n.parentNode.removeChild(n); n.parentNode = this; this.childNodes.push(n); return n; }
+ removeChild(n) { const i = this.childNodes.indexOf(n); if (i >= 0) this.childNodes.splice(i, 1); n.parentNode = null; return n; }
+ remove() { if (this.parentNode) this.parentNode.removeChild(this); }
+ before(n) { const p = this.parentNode; if (n.parentNode) n.parentNode.removeChild(n); p.childNodes.splice(p.childNodes.indexOf(this), 0, n); n.parentNode = p; }
+ replaceWith(n) { const p = this.parentNode; if (!p) return; p.childNodes[p.childNodes.indexOf(this)] = n; n.parentNode = p; this.parentNode = null; }
+ replaceChildren(...nodes) { this.textContent = ''; this.append(...nodes); }
+ setAttribute(k, v) { this.attrs[k] = String(v); if (k === 'id') this.id = String(v); if (k === 'class') this.className = String(v); }
+ getAttribute(k) { if (k === 'id') return this.id || null; if (k === 'class') return this.className; return k in this.attrs ? this.attrs[k] : null; }
+ hasAttribute(k) { return this.getAttribute(k) !== null; }
+ removeAttribute(k) { delete this.attrs[k]; }
+ addEventListener(t, f) { (this.listeners[t] = this.listeners[t] || []).push(f); }
+ removeEventListener(t, f) { this.listeners[t] = (this.listeners[t] || []).filter((x) => x !== f); }
+ dispatch(type, extra) {
+ const ev = Object.assign({ type, target: this, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, stopPropagation() {} }, extra || {});
+ (this.listeners[type] || []).slice().forEach((f) => f.call(this, ev));
+ if (typeof this['on' + type] === 'function') this['on' + type](ev);
+ return ev;
+ }
+ click() { if (this.disabled) return; this.dispatch('mousedown'); this.dispatch('click'); }
+ focus() { doc.activeElement = this; this.dispatch('focus'); }
+ blur() { if (doc.activeElement === this) doc.activeElement = doc.body; this.dispatch('blur'); }
+ select() {}
+ scrollIntoView() {}
+ getClientRects() { return [{}]; }
+ closest(sel) { let n = this; while (n && n.nodeType === 1) { if (matches(n, sel)) return n; n = n.parentNode; } return null; }
+ matches(sel) { return matches(this, sel); }
+ querySelectorAll(sel) { const out = []; walk(this, (n) => { if (n !== this && matches(n, sel, this)) out.push(n); }); return out; }
+ querySelector(sel) { return this.querySelectorAll(sel)[0] || null; }
+}
+function walk(n, f) { n.childNodes.forEach((c) => { if (c.nodeType === 1) { f(c); walk(c, f); } }); }
+// selectors: groups of compounds (tag, #id, .class, [attr] or [attr="v"]) joined by spaces (descendant)
+function parseCompound(s) {
+ const c = { tag: null, id: null, cls: [], attrs: [] };
+ const re = /([a-zA-Z][\w-]*)|#([\w-]+)|\.([\w-]+)|\[([\w-]+)(?:="([^"]*)")?\]/y;
+ for (let i = 0; i < s.length;) {
+ re.lastIndex = i;
+ const m = re.exec(s);
+ if (!m) throw new Error('selector not understood: ' + s);
+ if (m[1]) c.tag = m[1].toUpperCase(); else if (m[2]) c.id = m[2]; else if (m[3]) c.cls.push(m[3]); else c.attrs.push([m[4], m[5]]);
+ i = re.lastIndex;
+ }
+ return c;
+}
+function attrOf(n, k) {
+ if (k.startsWith('data-')) return n.dataset[camel(k.slice(5))];
+ if (k === 'tabindex') return n.tabIndex == null ? undefined : String(n.tabIndex);
+ if (k in n.attrs) return n.attrs[k];
+ const p = n[k];
+ return p == null || p === '' ? undefined : String(p);
+}
+function one(n, c) {
+ if (c.tag && n.tagName !== c.tag) return false;
+ if (c.id && n.id !== c.id) return false;
+ if (!c.cls.every((x) => n.classList.contains(x))) return false;
+ return c.attrs.every(([k, v]) => { const a = attrOf(n, k); return v === undefined ? a !== undefined : a === v; });
+}
+function matches(n, sel, scope) {
+ return sel.split(',').some((group) => {
+ const parts = group.trim().split(/\s+/).map(parseCompound);
+ if (!one(n, parts[parts.length - 1])) return false;
+ let cur = n.parentNode;
+ for (let i = parts.length - 2; i >= 0; i--) {
+ while (cur && cur.nodeType === 1 && !one(cur, parts[i])) { if (cur === scope) return false; cur = cur.parentNode; }
+ if (!cur || cur.nodeType !== 1) return false;
+ cur = cur.parentNode;
+ }
+ return true;
+ });
+}
+
+// ui.html as a tree (the page's markup is simple: no unquoted attributes, no inline script)
+function build(html) {
+ const root = new Element('html');
+ const stack = [root];
+ const voids = new Set(['meta', 'link', 'img', 'input', 'br', 'hr']);
+ const re = /|]*>|<(\/?)([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:="[^"]*")?)*)\s*\/?>|([^<]+)/gi;
+ let m;
+ while ((m = re.exec(html))) {
+ if (m[4] !== undefined) { if (m[4].trim()) stack[stack.length - 1].append(m[4]); continue; }
+ if (!m[2]) continue;
+ const tag = m[2].toLowerCase();
+ if (m[1]) { if (tag !== 'html') stack.pop(); continue; }
+ if (tag === 'html') { continue; }
+ const e = new Element(tag);
+ const ar = /([\w:-]+)(?:="([^"]*)")?/g;
+ let a;
+ while ((a = ar.exec(m[3]))) {
+ const k = a[1], v = a[2] === undefined ? '' : a[2];
+ if (k === 'class') e.className = v;
+ else if (k === 'id') e.id = v;
+ else if (k.startsWith('data-')) e.dataset[camel(k.slice(5))] = v;
+ else if (k === 'type' || k === 'content' || k === 'name' || k === 'src' || k === 'href') { e[k] = v; e.attrs[k] = v; }
+ else if (k === 'checked' || k === 'disabled' || k === 'readonly') e[k] = true;
+ else e.attrs[k] = v;
+ }
+ stack[stack.length - 1].appendChild(e);
+ if (!voids.has(tag)) stack.push(e);
+ }
+ return root;
+}
+
+const html = fs.readFileSync(htmlPath, 'utf8').replace('__TOKEN__', 'test-token');
+const root = build(html);
+const docListeners = {};
+doc = {
+ documentElement: root,
+ activeElement: null,
+ hidden: false,
+ get body() { return root.querySelector('body'); },
+ getElementById(id) { let f = null; walk(root, (n) => { if (!f && n.id === id) f = n; }); return f; },
+ querySelector: (s) => root.querySelector(s),
+ querySelectorAll: (s) => root.querySelectorAll(s),
+ createElement: (t) => new Element(t),
+ createTextNode: (t) => new TextNode(t),
+ addEventListener(t, f) { (docListeners[t] = docListeners[t] || []).push(f); },
+ removeEventListener(t, f) { docListeners[t] = (docListeners[t] || []).filter((x) => x !== f); },
+ execCommand: () => true,
+};
+doc.activeElement = doc.body;
+const key = (k, extra) => { const ev = Object.assign({ key: k, preventDefault() {}, shiftKey: false }, extra || {}); (docListeners.keydown || []).slice().forEach((f) => f(ev)); };
+
+// ---- the program's API, stubbed ----------------------------------------------------------------------------------
+const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
+const calls = [];
+let refuseNextSave = null; // the error the next save answers with
+let staleSearch = false; // the next search answers with an older request number
+const opened = [], copied = [];
+const SEARCH = [
+ { name: 'Sample Show', year: 2019, kind: 'series', catalog: 'IMDb', entry: 'https://www.imdb.com/title/tt0000003/', poster: 'https://img.example/a.jpg' },
+ { name: 'The Sample Show', year: 1998, kind: 'series', catalog: 'IMDb', entry: 'https://www.imdb.com/title/tt0000001/' },
+ { name: 'Sample Show', year: 2024, kind: 'series', catalog: 'TVmaze', entry: 'https://www.tvmaze.com/shows/43/sample-show' },
+];
+function answer(status, body) {
+ return { ok: status < 400, status, json: async () => JSON.parse(JSON.stringify(body)), body: { getReader: () => ({ read: () => new Promise(() => {}) }) } };
+}
+async function fakeFetch(url, init) {
+ const name = url.replace(/^\/api\//, '');
+ const body = init && init.body ? JSON.parse(init.body) : undefined;
+ if (name === 'alive') return answer(200, {}); // held open while the program runs: never ends here
+ calls.push({ name, body });
+ switch (name) {
+ case 'state': return answer(200, state);
+ case 'status': return answer(200, state.status);
+ case 'save': {
+ if (refuseNextSave) { const e = refuseNextSave; refuseNextSave = null; return answer(400, { error: e }); }
+ Object.assign(state.values, (body && body.settings) || {});
+ Object.assign(state.app, (body && body.app) || {});
+ return answer(200, state);
+ }
+ case 'match-search': return answer(200, { n: staleSearch ? body.n - 1 : body.n, results: (body.q || '').length >= 2 ? SEARCH : [], catalogs: ['IMDb', 'TVmaze', 'AniList'] });
+ case 'match-covers': return answer(200, { n: body.n, covers: [{ url: 'https://img.example/other.jpg', catalog: 'TVmaze' }] });
+ case 'match-report': return answer(200, { text: 'File name: ' + body.file + '\nThe fix: ' + (body.fix.label || body.fix.search) });
+ case 'log': return answer(200, { lines: [] });
+ case 'connections': return answer(200, { hosts: [] });
+ default: return answer(200, {});
+ }
+}
+
+// ---- run ui.js -----------------------------------------------------------------------------------------------------
+const ctx = {
+ document: doc, console, fetch: fakeFetch, setTimeout, clearTimeout, setInterval, clearInterval,
+ history: { replaceState() {} }, location: { pathname: '/' },
+ sessionStorage: { getItem: () => null, setItem() {} }, localStorage: { getItem: () => null, setItem() {} },
+ navigator: { clipboard: { writeText: async (t) => { copied.push(t); } } },
+ Option: function Option(text, value, defSel, sel) { const o = new Element('option'); o.textContent = text; o.value = value; o.selected = !!sel; return o; },
+};
+ctx.window = ctx;
+ctx.window.open = (u) => { opened.push(u); };
+ctx.window.close = () => {};
+vm.createContext(ctx);
+vm.runInContext(fs.readFileSync(jsPath, 'utf8'), ctx, { filename: 'ui.js' });
+
+// ---- the checks ----------------------------------------------------------------------------------------------------
+let failed = 0;
+const check = (ok, what, detail) => { console.log((ok ? 'ok ' : 'FAIL ') + what + (ok || detail === undefined ? '' : ': ' + JSON.stringify(detail))); if (!ok) failed++; };
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+async function until(cond, ms = 2000) { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return true; await sleep(20); } return cond(); }
+const $ = (id) => doc.getElementById(id);
+const field = (sel) => doc.querySelector(sel);
+const saves = () => calls.filter((c) => c.name === 'save');
+const lastSave = () => saves()[saves().length - 1];
+const change = (el, v) => { if (el.type === 'checkbox') el.checked = v; else el.value = v; el.dispatch('change'); };
+
+(async () => {
+ // 1. the shared table of text lines
+ const tab = JSON.parse(fs.readFileSync(linesPath, 'utf8'));
+ const L = vm.runInContext('MPRP_LINES', ctx);
+ let bad = tab.cases.filter((c) => L.expand(c.tpl, tab.values[c.values]) !== c.want);
+ check(tab.cases.length >= 10 && !bad.length, 'the page fills text lines as the program does (' + tab.cases.length + ' cases)', bad.map((c) => [c.tpl, L.expand(c.tpl, tab.values[c.values]), c.want]));
+
+ // 2. the page draws itself from the state
+ check(await until(() => $('p-look') && $('p-titles')), 'the page draws the settings tabs');
+
+ // 3. the saver: one setting at a time; a refused value goes back, with the error in the bar
+ const rich = field('input[data-key="richInfo"]');
+ change(rich, false);
+ check(await until(() => saves().length === 1), 'a switch saves at once');
+ check(JSON.stringify(lastSave().body) === '{"settings":{"richInfo":false}}', 'only that setting is sent', lastSave().body);
+ check(await until(() => $('msg').textContent === 'Saved'), 'the bar says Saved', $('msg').textContent);
+ refuseNextSave = 'Check every (ms): enter a number from 1000 to 60000';
+ const poll = field('input[data-key="pollInterval"]');
+ const before = poll.value;
+ change(poll, '5');
+ check(await until(() => $('msg').classList.contains('err')), 'a refused value shows its error', $('msg').textContent);
+ check(poll.value === String(before) && $('msg').textContent.startsWith('Check every'), 'and goes back to what was saved', poll.value);
+
+ // 4. the status sync: a switch made from the tray shows in the window without a save
+ const n = saves().length;
+ state.status.hideTitle = true;
+ check(await until(() => field('input[data-key="hideTitle"]').checked, 2500), 'Hide what I\'m watching follows the status');
+ check(saves().length === n, 'without saving anything');
+ state.status.hideTitle = false;
+ await until(() => !field('input[data-key="hideTitle"]').checked, 2500);
+
+ // 5. Text lines: Custom shows its lines, filled from the choice before, with a sample; a line saves after a pause
+ const choice = field('select[data-key="textLines"]'), custom = field('.tl-custom');
+ const epRow = field('input[data-key="episodeInDetails"]').closest('.field');
+ check(custom.classList.contains('hidden') && !epRow.classList.contains('hidden'), 'Standard: no custom lines, S01E02 switch shown');
+ change(choice, 'custom');
+ check(await until(() => saves().some((s) => s.body.settings && s.body.settings.customLines)), 'Custom saves the lines it starts with');
+ const cl = saves().find((s) => s.body.settings && s.body.settings.customLines).body.settings.customLines;
+ check(cl.episodeDetails === '{episodeTitle}' && cl.movieState === '{rating} · {director}' && cl.movieCover === '{title}[ ({year})]', 'filled with Standard\'s lines', cl);
+ check(!custom.classList.contains('hidden') && epRow.classList.contains('hidden'), 'Custom shows the lines and hides the S01E02 switch');
+ const ep = field('input[data-line="episodeDetails"]');
+ check(custom.querySelector('.tl-l1').textContent === 'Sample Episode', 'the sample shows the first line', custom.querySelector('.tl-l1').textContent);
+ ep.value = '{code} · {titel}';
+ ep.dispatch('input');
+ check(custom.querySelector('.tl-l1').textContent === 'S01E02 · {titel}' && custom.querySelector('.tl-bad').textContent === 'Unknown: {titel}', 'the sample follows the typing and names an unknown placeholder', custom.querySelector('.tl-bad').textContent);
+ const chip = [...custom.querySelectorAll('button.chip')].find((b) => b.textContent === '{rating}');
+ ep.focus();
+ chip.click();
+ check(ep.value === '{code} · {titel} · {rating}', 'a placeholder goes in with a separator', ep.value);
+ const k = saves().length;
+ check(!(await until(() => saves().length > k, 500)), 'no save on each key');
+ check(await until(() => saves().length > k, 1500) && lastSave().body.settings.customLines.episodeDetails === '{code} · {titel} · {rating}', 'the line saves after a pause', lastSave().body);
+ change(choice, 'short');
+ check(await until(() => custom.classList.contains('hidden')), 'another choice hides the custom lines');
+
+ // 6. Fix a match: the list, Remove and Undo
+ const rows = () => [...$('fixes').querySelectorAll('.fix-row')];
+ check(rows().length === 2, 'the list shows the fixes', rows().length);
+ check(rows()[0].querySelector('.help').textContent === 'Sample Show (2019) · Show · IMDb · episodes +12' && rows()[1].querySelector('.help').textContent === 'Only this file · Your image',
+ 'each says what it does', rows().map((r) => r.querySelector('.help').textContent));
+ rows()[1].querySelectorAll('button')[1].click();
+ check(await until(() => rows().length === 1), 'Remove takes the row away');
+ check(lastSave().body.settings.matchFixes.length === 1, 'and saves the list without it');
+ const undo = $('msg').querySelector('button');
+ check(!!undo && $('msg').textContent.startsWith('Fix removed.'), 'the bar offers Undo', $('msg').textContent);
+ undo.click();
+ check(await until(() => rows().length === 2) && lastSave().body.settings.matchFixes.length === 2, 'Undo brings it back');
+
+ // 7. Fix this match from the preview: what plays, the search as you type, the pick, the cover step
+ state.status.match = { file: 'sample.show.s01e02.1080p.mkv', title: 'Sample Show', season: 1, episode: 2, now: 'The Sample Show (1998)', nowEntry: 'https://www.imdb.com/title/tt0000001/' };
+ await sleep(1300); // the next status poll
+ $('fixMatch').click();
+ const sheet = () => doc.querySelector('.sheet');
+ check(await until(() => sheet()), 'Wrong title or cover? opens Fix this match');
+ const from = sheet().querySelector('.from').textContent;
+ check(from === 'From sample.show.s01e02.1080p.mkv, read as Sample Show, season 1, episode 2. Now matched to The Sample Show (1998).', 'it says what was read', from);
+ const searches = () => calls.filter((c) => c.name === 'match-search');
+ check(await until(() => searches().length === 1 && sheet().querySelectorAll('.res li[role="option"]').length === 4), 'it searches the read title at once', searches().map((c) => c.body));
+ check(searches()[0].body.q === 'Sample Show', 'with the read title', searches()[0].body);
+ const opts = () => [...sheet().querySelectorAll('.res li[role="option"]')];
+ check(opts()[1].textContent.endsWith('Now') && opts()[3].textContent === 'Search as "Sample Show" instead (no entry pinned)', 'the current match says Now; the last row searches under the typed name', opts().map((o) => o.textContent));
+ check(sheet().querySelector('.help').textContent.startsWith('Searches IMDb, TVmaze and AniList'), 'it names the catalogs it asks', sheet().querySelector('.help').textContent);
+ const use = [...sheet().querySelectorAll('button')].find((b) => b.textContent === 'Use this');
+ opts()[1].click();
+ check(use.disabled, 'the current match cannot be used again');
+ const q = sheet().querySelector('input[type="text"]');
+ q.value = 'Sa'; q.dispatch('input');
+ q.value = 'Sample'; q.dispatch('input');
+ await sleep(150);
+ check(searches().length === 1, 'no search before the pause');
+ check(await until(() => searches().length === 2, 1000) && searches()[1].body.q === 'Sample' && searches()[1].body.n === 2, 'one search after the pause', searches().map((c) => c.body));
+ await until(() => opts().length === 4);
+ staleSearch = true;
+ q.value = 'Sample Sh'; q.dispatch('input');
+ await until(() => searches().length === 3, 1000);
+ await sleep(100);
+ check(opts().length === 0 || sheet().querySelector('.res li.wait'), 'an answer to an older keystroke is dropped', opts().length);
+ staleSearch = false;
+ q.value = 'Sample Show'; q.dispatch('input');
+ check(await until(() => opts().length === 4, 1500), 'the next answer is drawn');
+ opts()[2].click();
+ check(!use.disabled, 'a pick can be used');
+ const scope = sheet().querySelectorAll('.scope input');
+ check(scope.length === 2 && scope[0].checked, 'the fix is for every file read as the title by default');
+ use.click();
+ check(await until(() => sheet() && sheet().querySelector('h2').textContent === 'Fixed'), 'Use this saves and shows Fixed');
+ const saved = lastSave().body.settings.matchFixes;
+ const fx = saved.find((x) => x.match === 'Sample Show');
+ check(!!fx && fx.entry === 'https://www.tvmaze.com/shows/43/sample-show' && fx.label === 'Sample Show (2024) · Show · TVmaze' && fx.episodeOffset === 12 && saved.length === 2,
+ 'the fix pins the pick and keeps its offset', saved);
+ check(await until(() => calls.some((c) => c.name === 'match-covers') && sheet().querySelectorAll('.covers img').length === 1), 'the cover step asks for the other catalogs\' covers');
+
+ // 8. Tell the project: the report is shown, copied, and GitHub's form opens at its plain address
+ [...sheet().querySelectorAll('button')].find((b) => b.textContent === 'Tell the project about this').click();
+ check(await until(() => doc.querySelector('textarea.report')), 'Tell the project shows the report');
+ const rep = calls.find((c) => c.name === 'match-report').body;
+ check(rep.file === 'sample.show.s01e02.1080p.mkv' && rep.before === 'The Sample Show (1998)' && rep.fix.entry === fx.entry, 'built from what plays and the fix', rep);
+ const reportText = doc.querySelector('textarea.report').value;
+ [...doc.querySelectorAll('.dlg button')].find((b) => b.textContent === 'Copy and open GitHub').click();
+ check(await until(() => opened.length === 1), 'Copy and open GitHub opens the issue form');
+ check(opened[0] === 'https://github.com/CptPakundo/MPRP/issues/new/choose' && copied[0] === reportText && reportText.startsWith('File name: sample.show'), 'at its plain address, with the text copied', [opened, copied]);
+ await until(() => !doc.querySelector('textarea.report') || !doc.querySelector('textarea.report').isConnected);
+
+ // 9. Done without a change saves nothing; Escape closes the dialog
+ const s9 = saves().length;
+ [...sheet().querySelectorAll('button')].find((b) => b.textContent === 'Done').click();
+ check(await until(() => !sheet()) && saves().length === s9, 'Done without a change closes without saving');
+ $('fixMatch').click();
+ await until(() => sheet());
+ key('Escape');
+ check(await until(() => !sheet()), 'Escape closes Fix this match');
+
+ // 10. About (Help tab): the version the program reports, and links to the project's own pages only
+ check($('aboutVer').textContent === 'Version ' + state.version, 'About shows the version', $('aboutVer').textContent);
+ const aboutLinks = $('p-help').querySelectorAll('.about a').map((a) => a.attrs.href);
+ check(aboutLinks.length >= 4 && aboutLinks.every((u) => u.startsWith('https://github.com/')) && aboutLinks.includes('https://github.com/CptPakundo/MPRP'),
+ 'About links to the project page, the licence and the credit', aboutLinks);
+
+ console.log(failed ? failed + ' failed' : 'all passed');
+ process.exit(failed ? 1 : 0);
+})().catch((e) => { console.log('FAIL the test itself: ' + (e && e.stack || e)); process.exit(1); });
diff --git a/internal/assets/ui.css b/internal/assets/ui.css
index 11093b2..be90be1 100644
--- a/internal/assets/ui.css
+++ b/internal/assets/ui.css
@@ -127,6 +127,13 @@
.checks .ok .mark { color: var(--good); } .checks .problem .mark { color: var(--bad); }
.checks .what { min-width: 0; overflow-wrap: anywhere; }
#diagText { min-height: 120px; margin-top: 8px; }
+ .about .ab-head { display: flex; align-items: center; gap: 12px; }
+ .about .ab-logo { flex: none; display: block; }
+ .about .ab-name { font-size: 20px; line-height: 28px; font-weight: 600; }
+ .about .ab-what { margin: 12px 0 8px; }
+ .about .ab-links { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-bottom: 8px; }
+ .about .ab-links button.link { margin-left: 0; font-size: 14px; line-height: 20px; }
+ .about .ab-links a { text-decoration: none; } .about .ab-links a:hover { text-decoration: underline; }
.credits { font-size: 12px; line-height: 16px; }
.credits .cr { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 8px 0 4px; }
.credits img { display: block; }
@@ -180,4 +187,69 @@
.chg h3:first-child { margin-top: 0; }
.chg ul { list-style: none; margin: 4px 0 12px; padding: 0; }
.chg li { margin: 8px 0; }
+ .msg button.link { margin-left: 4px; }
+
+ /* Text lines (Look): Custom's lines, placeholders and samples */
+ .tl-grp { margin-top: 4px; }
+ .tl-grp + .tl-grp { margin-top: 16px; }
+ .tl-h { font-weight: 600; margin-bottom: 4px; }
+ .tl-line { display: flex; gap: 8px; align-items: center; margin: 4px 0; }
+ .tl-line label { width: 88px; flex: none; font-size: 12px; color: var(--text-2); }
+ .tl-line input { flex: 1; min-width: 0; font: 12px/18px ui-monospace, Consolas, monospace; }
+ .tl-chips, .tl-bad, .tl-sample, .tl-covertext { margin-left: 96px; }
+ .tl-chips { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
+ button.chip { font: 12px/16px ui-monospace, Consolas, monospace; min-height: 0; padding: 2px 6px; color: var(--text-2); }
+ .tl-bad { color: var(--warn); }
+ .tl-bad:empty { display: none; }
+ .tl-sample { display: flex; gap: 12px; margin-top: 8px; padding: 8px 12px; background: var(--surface-2); border-radius: var(--r-control); }
+ .tl-cover { width: 48px; height: 48px; flex: none; border-radius: var(--r-control); background: var(--stroke-control); }
+ .tl-sample .pv-text > div { min-height: 16px; }
+ .tl-custom > .help:last-child { margin: 12px 0 0 96px; }
+ @media (max-width: 560px) { .tl-line { flex-wrap: wrap; } .tl-line label { width: auto; } .tl-chips, .tl-bad, .tl-sample, .tl-covertext, .tl-custom > .help:last-child { margin-left: 0; } }
+
+ /* Fix a match: the list (Titles & art) and the Fix this match dialog */
+ .fix-row { display: flex; gap: 12px; align-items: center; padding: 8px 0; border-top: 1px solid var(--stroke); }
+ .fix-row:first-child { border-top: 0; padding-top: 0; }
+ .fix-row .t, .res .t { flex: 1; min-width: 0; }
+ .fix-row .n, .res .n, .done-head .n { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .fix-row .help { margin-top: 0; overflow-wrap: anywhere; }
+ .fix-row img, .fix-row .sq, .res img, .res .sq { width: 32px; height: 48px; flex: none; border-radius: 2px; object-fit: cover; display: block; }
+ .sq { border: 1px dashed var(--stroke-control); background: var(--surface-2); display: block; }
+ .fixes + .actions { margin-top: 12px; }
+ .sheet { max-height: calc(100vh - 32px); display: flex; flex-direction: column; }
+ .sheet > div { display: flex; flex-direction: column; min-height: 0; }
+ .sheet .from { font-size: 12px; line-height: 16px; margin: 0 0 12px; overflow-wrap: anywhere; }
+ .sheet .from b { color: var(--text); font-weight: 600; }
+ .sheet .from label { display: block; margin-bottom: 4px; }
+ .res { list-style: none; margin: 8px 0 0; padding: 0; overflow-y: auto; flex: 1 1 auto; min-height: 120px; max-height: 44vh; border-top: 1px solid var(--stroke); }
+ .res li { display: flex; gap: 12px; align-items: center; padding: 6px 8px; border-bottom: 1px solid var(--stroke); cursor: pointer; border-radius: var(--r-control); }
+ .res li:hover { background: var(--control-hover); }
+ .res li[aria-selected="true"] { background: var(--accent-soft); }
+ .res .m { font-size: 12px; line-height: 16px; color: var(--text-2); }
+ .res .now { font-size: 12px; color: var(--text-2); flex: none; }
+ .res li.as { color: var(--text-2); }
+ .res li.wait { cursor: default; color: var(--text-2); font-size: 12px; }
+ .res li.wait:hover { background: none; }
+ .sheet .foot { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; }
+ .sheet .foot .grow { flex: 1; }
+ .sheet .foot button.link { margin-left: 0; }
+ .scope { flex: 1 1 260px; display: flex; flex-direction: column; gap: 2px; font-size: 12px; line-height: 16px; color: var(--text-2); }
+ .scope label { display: flex; gap: 6px; align-items: center; overflow-wrap: anywhere; }
+ .scope b { color: var(--text); font-weight: 600; }
+ .scope input, .opt input[type=radio] { accent-color: var(--accent); margin: 0; }
+ .done-head { display: flex; gap: 12px; align-items: flex-start; margin: 4px 0 12px; }
+ .done-head > div { min-width: 0; }
+ .done-head .big { width: 48px; height: 72px; flex: none; border-radius: var(--r-control); object-fit: cover; }
+ .opt { display: flex; gap: 8px; align-items: center; padding: 8px 0; border-top: 1px solid var(--stroke); }
+ .opt label { flex: none; }
+ .opt input[type=text] { flex: 1; min-width: 0; }
+ .covers { display: flex; flex-wrap: wrap; gap: 8px; margin: 4px 0 8px 24px; }
+ .covers:empty { display: none; }
+ .covers img { width: 40px; height: 60px; border-radius: 2px; cursor: pointer; outline-offset: 2px; object-fit: cover; }
+ .covers img.sel { outline: 2px solid var(--accent-text); }
+ .sheet .fold { border-top: 1px solid var(--stroke); }
+ .offs { display: flex; gap: 8px; align-items: center; font-size: 12px; color: var(--text-2); flex-wrap: wrap; }
+ .offs input { width: 72px; }
+ textarea.report { min-height: 140px; margin-bottom: 4px; }
+ .dlg .help + .row { margin-top: 16px; }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
diff --git a/internal/assets/ui.html b/internal/assets/ui.html
index 9b5e599..45560fd 100644
--- a/internal/assets/ui.html
+++ b/internal/assets/ui.html
@@ -5,8 +5,10 @@
-MPCvibedRPC
-
+MPRP
+
+
+
@@ -49,8 +51,8 @@
-
-
No player is answering. Open your player and play something. MPC-HC, MPC-BE, VLC and mpv need setting up first: the button does it. PotPlayer needs nothing; Kodi needs its web server and password (Players tab).
+
+
No player is answering. Open your player and play something. MPC-HC, MPC-BE, VLC and mpv need setting up first: the button does it. PotPlayer needs nothing; Kodi needs its web server and password (Players tab).
@@ -93,12 +95,23 @@
Your stats
Counted on this computer only: numbers, never titles. Nothing is sent anywhere.
+
About
+
+
+
+
+
MPRP
Media Player Rich Presence · Version
+
+
Shows what your video player is playing as your Discord status: the title, the episode, the cover and a progress bar.
Free and open source under the MIT license. The idea comes from angeloanan/MPC-DiscordRPC. Written by an AI (Claude) from the maintainer's prompts and testing: how.
+
Credits
This product uses the TMDB API but is not endorsed or certified by TMDB.
-
TV data from TVmaze, under CC BY-SA 4.0. Titles, covers and episode names also come from IMDb, Cinemeta, AniList, Kitsu, Wikipedia and Bulbapedia. Third-party notices
+
TV data from TVmaze, under CC BY-SA 4.0. Titles, covers and episode names also come from IMDb, Cinemeta, AniList, Kitsu, Wikipedia and Bulbapedia. Third-party notices
diff --git a/internal/assets/ui.js b/internal/assets/ui.js
index cf0f38c..7582266 100644
--- a/internal/assets/ui.js
+++ b/internal/assets/ui.js
@@ -1,3 +1,48 @@
+// Text lines (Look tab): the presets, the placeholders and how a line is filled, for the page's sample. The program
+// fills the card's lines with the same rules (internal/core/lines.go); internal/core/testdata/lines.json holds the
+// cases both must agree on (the page's test runs them through MPRP_LINES.expand).
+const MPRP_LINES = (() => {
+ const SEP = ' · ';
+ const COVER = '{title}[ ({year})]';
+ const KEYS = ['episodeDetails', 'episodeState', 'movieDetails', 'movieState', 'movieCover'];
+ // episode first and second line, film first and second line, film cover text (Standard is the program's own lines;
+ // these are what Custom starts from)
+ const PRESETS = {
+ standard: ['{episodeTitle}', '{seasonName}' + SEP + '{genres}' + SEP + '{rating}', '{year}' + SEP + '{genres}', '{rating}' + SEP + '{director}', COVER],
+ short: ['{code}' + SEP + '{episodeTitle}', '', '{year}', '{director}', COVER],
+ detailed: ['{code}' + SEP + '{episodeTitle}', '{genres}' + SEP + '{rating}' + SEP + '[on {player}]', '{year}' + SEP + '{genres}' + SEP + '{length}', '{rating}' + SEP + '{director}' + SEP + '[on {player}]', COVER],
+ };
+ const SAMPLE = {
+ episode: { title: 'Sample Show', year: '', genres: 'Drama, Comedy', rating: '★ 8.3', director: '', player: 'VLC media player', length: '45:00', code: 'S01E02', season: '1', episode: '2', episodeTitle: 'Sample Episode', seasonName: '' },
+ movie: { title: 'Sample Movie', year: '2020', genres: 'Drama, Comedy', rating: '★ 7.1', director: 'Dir. Sample Name', player: 'VLC media player', length: '1:52:10' },
+ };
+ const CHIPS = {
+ episode: ['title', 'code', 'season', 'episode', 'episodeTitle', 'seasonName', 'genres', 'rating', 'player', 'length'],
+ movie: ['title', 'year', 'genres', 'rating', 'director', 'player', 'length'],
+ };
+ const has = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
+ // each known {name} becomes its value (an unknown one stays as typed); a part in [ ] drops out when a placeholder in
+ // it is empty; parts between " · " that end up empty go with their separator; trimmed and cut to 128 characters
+ function expand(tpl, v) {
+ const fill = (s) => s.replace(/\{(\w+)\}/g, (m, k) => (has(v, k) ? v[k] : m));
+ let s = String(tpl || '').replace(/\[([^[\]]*)\]/g, (m, inner) => {
+ let empty = false;
+ inner.replace(/\{(\w+)\}/g, (x, k) => { if (has(v, k) && v[k] === '') empty = true; return x; });
+ return empty ? '' : inner;
+ });
+ s = fill(s).split(SEP).map((p) => p.trim()).filter(Boolean).join(SEP).trim();
+ if (s.length > 128) s = s.slice(0, 125) + '...';
+ return s;
+ }
+ // the placeholders in tpls that v does not know ("" when there are none)
+ function unknown(tpls, v) {
+ const out = [];
+ tpls.forEach((t) => String(t || '').replace(/\{(\w+)\}/g, (m, k) => { if (!has(v, k) && !out.includes(m)) out.push(m); return m; }));
+ return out.length ? 'Unknown: ' + out.join(', ') : '';
+ }
+ return { SEP, COVER, KEYS, PRESETS, SAMPLE, CHIPS, expand, unknown };
+})();
+
(() => {
// The page gets its token when it is opened with a one-time code. It keeps the token for this window (a reload
// comes without one) and takes the code, or a token, out of its address.
@@ -125,7 +170,7 @@
function applyOsText() {
const t = osText();
if (!t) return;
- $('mpcHelpText').innerHTML = t.help;
+ $('playerHelpText').innerHTML = t.help;
$('autoStartLabel').textContent = t.autoStart;
if (model.tray) { // the macOS app has a menu bar icon
$('autoStartHelp').textContent = 'Starts in the menu bar, without a window.';
@@ -139,7 +184,11 @@
// Every control saves on its own, one at a time and only its own setting: a toggle or a choice as soon as it changes,
// a text box when it loses focus (or on Enter). A value that is refused goes back to what was saved.
// "get" reads the control's value and "set" writes a value back into it (used when a value is refused).
- const same = (a, b) => (Array.isArray(a) || Array.isArray(b) ? JSON.stringify([...(a || [])].sort()) === JSON.stringify([...(b || [])].sort()) : String(a) === String(b == null ? '' : b));
+ // an object setting (the custom text lines) is the same when its non-empty values are
+ const flat = (o) => JSON.stringify(Object.keys(o || {}).sort().filter((k) => o[k] !== '' && o[k] != null).map((k) => [k, o[k]]));
+ const isObj = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
+ const same = (a, b) => (Array.isArray(a) || Array.isArray(b) ? JSON.stringify([...(a || [])].sort()) === JSON.stringify([...(b || [])].sort())
+ : isObj(a) || isObj(b) ? flat(a) === flat(b) : String(a) === String(b == null ? '' : b));
function saver(scope, key, get, set) {
return async () => {
const value = get();
@@ -196,6 +245,8 @@
ta.addEventListener('change', () => saveLater(run));
return wrap;
}
+ if (f.type === 'textlines') return customLinesBox(f, v);
+ if (f.type === 'fixes') return fixesBox(f);
let input;
if (f.type === 'bool') {
input = el('input', { type: 'checkbox', checked: !!v });
@@ -248,6 +299,7 @@
}
group.append(fieldFor(f, m.values[f.key]));
}
+ if (sec.id === 'look') textLinesFollow(d);
if (sec.id === 'privacy') { group.append(coverCacheBox()); dimServices(d); newFold('What else leaves ' + (osText() ? osText().here : 'this PC')); group.append(leavesBox()); newFold('Recent connections'); group.append(connsBox()); }
d.setAttribute('role', 'tabpanel');
$('p-help').before(d);
@@ -269,6 +321,394 @@
main.addEventListener('change', () => later(apply));
}
+ // ---- Text lines (Look tab) ----------------------------------------------------------------------------------------
+ // Custom's five lines in two groups, each with its placeholders to insert and a sample drawn like the preview. A
+ // line saves when it loses focus or after a second's pause in typing, not at each key: each save sends the status.
+ let customFields = null; // the custom lines' controls while the Look tab is drawn
+ function customLinesBox(f, v) {
+ const L = MPRP_LINES, vals = v || {}, inputs = {}, draws = [];
+ const wrap = el('div', { className: 'field tl-custom' });
+ let timer = null;
+ const draw = () => draws.forEach((d) => d());
+ const read = () => { const o = {}; L.KEYS.forEach((k) => { const s = inputs[k].value.trim(); if (s) o[k] = s; }); return o; };
+ const show = (o) => { L.KEYS.forEach((k) => { inputs[k].value = (o && o[k]) || ''; }); draw(); };
+ const run = saver('settings', f.key, read, show);
+ const save = () => { clearTimeout(timer); saveLater(run); };
+ const soon = () => { draw(); clearTimeout(timer); timer = setTimeout(save, 1000); };
+ const groups = [
+ ['episode', 'Episodes', [['episodeDetails', 'First line'], ['episodeState', 'Second line']]],
+ ['movie', 'Films', [['movieDetails', 'First line'], ['movieState', 'Second line'], ['movieCover', 'Cover text']]],
+ ];
+ for (const [kind, title, lines] of groups) {
+ const box = el('div', { className: 'tl-grp' }, el('div', { className: 'tl-h', textContent: title }));
+ let target = null; // the field a placeholder goes into: the last one used in this group
+ for (const [key, label] of lines) {
+ const i = el('input', { type: 'text', value: vals[key] || '', spellcheck: false, autocomplete: 'off' });
+ i.id = 'f-' + f.key + '-' + key;
+ i.dataset.line = key;
+ if (key === 'movieCover') i.placeholder = L.COVER;
+ inputs[key] = i;
+ if (!target) target = i;
+ i.addEventListener('input', soon);
+ i.addEventListener('change', save);
+ i.addEventListener('keydown', (e) => { if (e.key === 'Enter') i.blur(); });
+ i.addEventListener('focus', () => { target = i; });
+ box.append(el('div', { className: 'tl-line' }, el('label', { htmlFor: i.id, textContent: label }), i));
+ }
+ const chips = el('div', { className: 'tl-chips' });
+ chips.setAttribute('role', 'group'); chips.setAttribute('aria-label', title + ': placeholders');
+ L.CHIPS[kind].forEach((k) => {
+ const b = el('button', { type: 'button', className: 'chip', textContent: '{' + k + '}' });
+ b.addEventListener('mousedown', (e) => e.preventDefault()); // the field keeps the focus and the cursor
+ b.onclick = () => {
+ const t = target, pos = t.selectionStart == null ? t.value.length : t.selectionStart;
+ const before = t.value.slice(0, pos), after = t.value.slice(pos);
+ const ins = (before.trim() && !before.endsWith(L.SEP) ? L.SEP : '') + '{' + k + '}';
+ t.value = before + ins + after;
+ t.focus();
+ t.selectionStart = t.selectionEnd = (before + ins).length;
+ soon();
+ };
+ chips.append(b);
+ });
+ const bad = el('div', { className: 'help tl-bad' });
+ const l1 = el('div', { className: 'tl-l1' }), l2 = el('div', { className: 'tl-l2' });
+ const sample = el('div', { className: 'tl-sample' }, el('div', { className: 'tl-cover' + (kind === 'movie' ? ' film' : '') }),
+ el('div', { className: 'pv-text' }, el('div', { className: 'pv-name', textContent: 'Watching ' + L.SAMPLE[kind].title }), l1, l2));
+ const coverNote = kind === 'movie' ? el('div', { className: 'help tl-covertext' }) : null;
+ box.append(chips, bad, sample, ...(coverNote ? [coverNote] : []));
+ draws.push(() => {
+ const sv = L.SAMPLE[kind], keys = lines.map(([k]) => k);
+ l1.textContent = L.expand(inputs[keys[0]].value, sv);
+ l2.textContent = L.expand(inputs[keys[1]].value, sv);
+ bad.textContent = L.unknown(keys.map((k) => inputs[k].value), sv);
+ if (coverNote) coverNote.textContent = 'Shown when you point at the cover: ' + L.expand(inputs.movieCover.value.trim() || L.COVER, sv);
+ });
+ wrap.append(box);
+ }
+ wrap.append(help('Parts in [ ] drop out when a value is missing. Discord shows up to 128 characters a line.'));
+ customFields = { read, show, save };
+ draw();
+ return wrap;
+ }
+ // The Text lines choice: Custom shows its five lines (filled with the lines of the choice that was on before, while
+ // they are empty), and "Also show S01E02 in the title line" belongs to Standard only.
+ function textLinesFollow(panel) {
+ const sel = panel.querySelector('select[data-key="textLines"]'), custom = panel.querySelector('.tl-custom');
+ if (!sel || !custom) return;
+ const ep = panel.querySelector('input[data-key="episodeInDetails"]'), epField = ep && ep.closest('.field');
+ let prev = sel.value === 'custom' ? 'standard' : sel.value;
+ const apply = () => {
+ custom.classList.toggle('hidden', sel.value !== 'custom');
+ if (epField) epField.classList.toggle('hidden', sel.value !== 'standard');
+ };
+ apply();
+ sel.addEventListener('change', () => {
+ if (sel.value === 'custom' && customFields && !Object.keys(customFields.read()).length) {
+ const p = MPRP_LINES.PRESETS[prev] || MPRP_LINES.PRESETS.standard, o = {};
+ MPRP_LINES.KEYS.forEach((k, i) => { if (p[i]) o[k] = p[i]; });
+ customFields.show(o);
+ customFields.save();
+ }
+ if (sel.value !== 'custom') prev = sel.value;
+ apply();
+ later(apply); // after the save: a refused choice is put back
+ });
+ }
+
+ // ---- Fix a match (Titles & art, and the preview's "Wrong title or cover?") ----------------------------------------
+ let fixList = null, lastMatch = null; // the list while Titles & art is drawn; what plays, as the status says (Status.match)
+ const fixesNow = () => (model && Array.isArray(model.values.matchFixes) ? model.values.matchFixes : []);
+ const kindName = (k) => (k === 'movie' ? 'Movie' : 'Show');
+ const entryLine = (r) => [r.year, kindName(r.kind), r.catalog].filter(Boolean).join(' · ');
+ const entryLabel = (r) => r.name + (r.year ? ' (' + r.year + ')' : '') + ' · ' + kindName(r.kind) + ' · ' + r.catalog;
+ const signed = (n) => (n > 0 ? '+' + n : String(n));
+ const sameFix = (a, b) => !!a.file === !!b.file && a.match.trim().toLowerCase() === b.match.trim().toLowerCase();
+ // the list with fx in place of the fix for the same title or file (or added at the end)
+ const withFix = (list, fx) => { const i = list.findIndex((x) => sameFix(x, fx)); const out = list.filter((x) => !sameFix(x, fx)); out.splice(i < 0 ? out.length : i, 0, fx); return out; };
+ const fixFor = (m) => fixesNow().find((x) => (x.file ? m.file && x.match.toLowerCase() === m.file.toLowerCase() : false))
+ || fixesNow().find((x) => !x.file && x.match.trim().toLowerCase() === (m.title || '').trim().toLowerCase());
+ // what a fix does, in the list: "Only this file · Your image · Sample Show (2019) · Show · IMDb · episodes +12"
+ function fixMeta(fx) {
+ const parts = [];
+ if (fx.file) parts.push('Only this file');
+ if (fx.cover) parts.push('Your image');
+ if (fx.entry) parts.push(fx.label || fx.entry);
+ else if (fx.search) parts.push('Searched as "' + fx.search + '"');
+ if (fx.seasonOffset) parts.push('seasons ' + signed(fx.seasonOffset));
+ if (fx.episodeOffset) parts.push('episodes ' + signed(fx.episodeOffset));
+ return parts.join(' · ');
+ }
+ const thumb = (src, cls) => {
+ if (!src) return el('span', { className: 'sq' + (cls ? ' ' + cls : '') });
+ const i = el('img', { alt: '', src, className: cls || '' });
+ i.onerror = () => { i.replaceWith(el('span', { className: 'sq' + (cls ? ' ' + cls : '') })); };
+ return i;
+ };
+ function fixesBox() {
+ fixList = el('div', { className: 'fixes', id: 'fixes' });
+ drawFixes();
+ const add = el('button', { textContent: 'Add a fix' });
+ add.onclick = () => openFix({ add: true });
+ return el('div', { className: 'field' }, fixList, el('div', { className: 'row actions' }, add, el('span', { className: 'help', textContent: 'A fix applies to every file read as that title, or to one file.' })));
+ }
+ function drawFixes() {
+ if (!fixList) return;
+ fixList.textContent = '';
+ const list = fixesNow();
+ if (!list.length) {
+ fixList.append(el('div', { className: 'help fix-empty' }, document.createTextNode('No fixes yet. When the card shows the wrong title or cover, choose '), el('b', { textContent: 'Wrong title or cover?' }), document.createTextNode(' under it.')));
+ return;
+ }
+ list.forEach((fx) => {
+ const edit = el('button', { className: 'quiet', textContent: 'Edit' }), rm = el('button', { className: 'quiet', textContent: 'Remove' });
+ edit.setAttribute('aria-label', 'Edit the fix for ' + fx.match); rm.setAttribute('aria-label', 'Remove the fix for ' + fx.match);
+ edit.onclick = () => openFix({ fix: fx });
+ rm.onclick = async () => {
+ const before = fixesNow();
+ if (await saveFixes(before.filter((x) => !sameFix(x, fx)))) noteUndo('Fix removed.', () => saveFixes(before));
+ };
+ fixList.append(el('div', { className: 'fix-row' }, thumb(fx.cover || fx.poster),
+ el('div', { className: 't' }, el('div', { className: 'n', textContent: fx.match }), el('div', { className: 'help', textContent: fixMeta(fx) })), edit, rm));
+ });
+ }
+ // saves Fix a match's list, in turn like every change, and draws it again; resolves to whether it was saved
+ const saveFixes = (next) => new Promise((resolve) => later(async () => {
+ note('Saving…');
+ saving++;
+ try { model = await api('save', { settings: { matchFixes: next } }); note('Saved'); resolve(true); } catch (e) { note(e.message, true); resolve(false); } finally { saving--; drawFixes(); }
+ }));
+ // a line in the bottom bar with an Undo button, for a few seconds
+ function noteUndo(text, undo) {
+ clearTimeout(clearTimer);
+ const m = $('msg'), b = el('button', { className: 'link', textContent: 'Undo' });
+ m.className = 'msg'; m.textContent = '';
+ b.onclick = () => { m.textContent = ''; undo(); };
+ m.append(document.createTextNode(text + ' '), b);
+ clearTimer = setTimeout(() => { m.textContent = ''; }, 8000);
+ }
+ // a dialog with content of its own (modal() is for a question with buttons). Escape and a click outside close it;
+ // Tab stays inside it.
+ function sheet(title) {
+ const prev = document.activeElement, uid = 'dlg' + (++modalCount);
+ const h = el('h2', { textContent: title, id: uid + '-title' }), body = el('div');
+ const box = el('div', { className: 'dlg wide sheet' }, h, body);
+ box.setAttribute('role', 'dialog'); box.setAttribute('aria-modal', 'true'); box.setAttribute('aria-labelledby', h.id);
+ const back = el('div', { className: 'dlg-back' }, box);
+ const top = () => [...document.querySelectorAll('.dlg-back')].pop() === back;
+ const close = () => { document.removeEventListener('keydown', key, true); back.remove(); if (prev && prev.focus) prev.focus(); };
+ const key = (e) => {
+ if (!top()) return;
+ if (e.key === 'Escape') { e.preventDefault(); close(); return; }
+ if (e.key !== 'Tab') return;
+ const all = [...box.querySelectorAll('button, input, select, textarea, summary, li[tabindex]')].filter((x) => !x.disabled && x.getClientRects().length);
+ if (!all.length) return;
+ const i = all.indexOf(document.activeElement);
+ if (e.shiftKey ? i <= 0 : i === all.length - 1) { e.preventDefault(); all[e.shiftKey ? all.length - 1 : 0].focus(); }
+ };
+ document.addEventListener('keydown', key, true);
+ back.onmousedown = (e) => { if (e.target === back) close(); };
+ document.body.append(back);
+ return { box, h, body, close };
+ }
+ // Fix this match. ctx.match: what plays (Status.match); ctx.fix: a fix to edit; ctx.add: a fix for a title that is not
+ // playing. Step 1 searches the catalogs and saves the pick; step 2 (fixed) offers the cover and the offsets.
+ function openFix(ctx) {
+ const playing = ctx.match || null;
+ const fix = ctx.fix || (playing ? fixFor(playing) : null) || null;
+ const s = sheet('Fix this match');
+ let cats = [], sel = null, n = 0, timer = null, scopeFile = !!(fix && fix.file);
+ const from = el('p', { className: 'from' });
+ const b = (t) => el('b', { textContent: t }), tx = (t) => document.createTextNode(t);
+ let readIn = null;
+ if (playing) {
+ const nums = (playing.season ? ', season ' + playing.season : '') + (playing.episode ? ', episode ' + playing.episode : '');
+ from.append(tx('From '), b(playing.file || 'this video'), tx(', read as '), b(playing.title), tx(nums + '. '), tx(playing.now ? 'Now matched to ' + playing.now + '.' : 'Nothing matched it yet.'));
+ } else if (fix) {
+ from.append(...(fix.file ? [tx('For the file '), b(fix.match), tx('.')] : [tx('For every file read as '), b(fix.match), tx('.')]));
+ } else {
+ readIn = el('input', { type: 'text', spellcheck: false, autocomplete: 'off', placeholder: 'Sample Show' });
+ readIn.id = 'fixRead';
+ from.append(el('label', { htmlFor: readIn.id, textContent: 'The title as it is read from the file name (the preview shows it while it plays):' }), readIn);
+ }
+ const q = el('input', { type: 'text', spellcheck: false, autocomplete: 'off', value: (fix && fix.search) || (playing ? playing.title : fix ? (fix.label ? fix.label.split(' · ')[0].replace(/ \(\d{4}\)$/, '') : fix.match) : '') });
+ q.setAttribute('aria-label', 'Search the catalogs');
+ const qHelp = help('');
+ const res = el('ul', { className: 'res' });
+ res.setAttribute('role', 'listbox'); res.setAttribute('aria-label', 'Results');
+ const use = el('button', { className: 'primary', textContent: 'Use this', disabled: true });
+ const cancel = el('button', { className: 'quiet', textContent: 'Cancel' });
+ cancel.onclick = s.close;
+ let scope = el('span', { className: 'grow' });
+ if (playing && playing.file) {
+ const name = 'scope' + modalCount;
+ const r1 = el('input', { type: 'radio', name, checked: !scopeFile }), r2 = el('input', { type: 'radio', name, checked: scopeFile });
+ r1.onchange = () => { scopeFile = false; }; r2.onchange = () => { scopeFile = true; };
+ scope = el('div', { className: 'scope' }, el('label', {}, r1, el('span', {}, tx('Every file read as '), b(playing.title))), el('label', {}, r2, el('span', {}, tx('Only this file ('), b(playing.file), tx(')'))));
+ scope.setAttribute('role', 'radiogroup'); scope.setAttribute('aria-label', 'Apply the fix to');
+ }
+ s.body.append(from, q, qHelp, res, el('div', { className: 'foot' }, scope, cancel, use));
+ const nowEntry = playing && playing.nowEntry ? playing.nowEntry : fix && fix.entry ? fix.entry : '';
+ const rows = () => [...res.querySelectorAll('li[role="option"]')];
+ const choose = (li, r) => {
+ rows().forEach((x) => x.setAttribute('aria-selected', 'false'));
+ li.setAttribute('aria-selected', 'true');
+ sel = r; use.disabled = !!r.now;
+ };
+ const row = (li, r) => {
+ li.setAttribute('role', 'option'); li.setAttribute('aria-selected', 'false'); li.tabIndex = -1;
+ li.onclick = () => choose(li, r);
+ li.ondblclick = () => { choose(li, r); if (!use.disabled) use.click(); };
+ res.append(li);
+ };
+ function render(list, err) {
+ res.textContent = ''; sel = null; use.disabled = true;
+ qHelp.textContent = (cats.length ? 'Searches ' + cats.join(', ').replace(/, ([^,]*)$/, ' and $1') + ' (the catalogs on under Privacy).' : 'All catalogs are off (Privacy).') + (err ? ' ' + err : '');
+ const term = q.value.trim();
+ if (cats.length && term.length >= 2 && !list.length) res.append(el('li', { className: 'wait', textContent: err ? 'No answer.' : 'Nothing found. Try another spelling.' }));
+ list.forEach((r) => {
+ const now = !!nowEntry && r.entry === nowEntry;
+ row(el('li', {}, thumb(r.poster), el('div', { className: 't' }, el('div', { className: 'n', textContent: r.name }), el('div', { className: 'm', textContent: entryLine(r) })),
+ ...(now ? [el('span', { className: 'now', textContent: 'Now' })] : [])), Object.assign({}, r, { now }));
+ });
+ if (term) row(el('li', { className: 'as' }, el('span', { className: 'sq' }), el('div', { className: 't', textContent: 'Search as "' + term + '" instead (no entry pinned)' })), { search: term });
+ }
+ async function search(first) {
+ clearTimeout(timer);
+ const term = q.value.trim(), my = ++n;
+ if (!first && term.length < 2) { render([], ''); return; }
+ res.textContent = '';
+ res.append(el('li', { className: 'wait', textContent: 'Searching…' }));
+ try {
+ const r = await api('match-search', { q: term, n: my });
+ if (r.n !== my || !s.box.isConnected) return; // an answer to an older keystroke
+ cats = r.catalogs || [];
+ render(r.results || [], r.error || '');
+ } catch (e) { if (my === n) render([], e.message); }
+ }
+ q.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => search(false), 350); });
+ q.addEventListener('keydown', (e) => {
+ const all = rows(), i = all.findIndex((x) => x.getAttribute('aria-selected') === 'true');
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ const to = all[Math.max(0, Math.min(all.length - 1, i + (e.key === 'ArrowDown' ? 1 : -1)))];
+ if (to) { to.click(); to.scrollIntoView({ block: 'nearest' }); }
+ } else if (e.key === 'Enter' && !use.disabled) use.click();
+ });
+ use.onclick = async () => {
+ if (!sel || sel.now) return;
+ let match, file = false;
+ if (readIn) match = readIn.value.trim();
+ else if (playing && playing.file && scopeFile) { match = playing.file; file = true; }
+ else if (playing) match = playing.title;
+ else { match = fix.match; file = !!fix.file; }
+ if (!match) { qHelp.textContent = 'Type the title as it is read from the file name first.'; readIn.focus(); return; }
+ const fx = { match };
+ if (file) fx.file = true;
+ if (sel.entry) { fx.entry = sel.entry; fx.label = entryLabel(sel); if (sel.poster) fx.poster = sel.poster; } else fx.search = sel.search;
+ if (fix && sameFix(fix, fx)) ['cover', 'seasonOffset', 'episodeOffset'].forEach((k) => { if (fix[k]) fx[k] = fix[k]; });
+ const before = fixesNow();
+ let next = fix && !sameFix(fix, fx) && !playing ? before.filter((x) => !sameFix(x, fix)) : before;
+ next = withFix(next, fx);
+ use.disabled = true;
+ if (await saveFixes(next)) fixed(fx, before, sel); else use.disabled = false;
+ };
+ // step 2: the fix is saved; its cover and its offsets
+ function fixed(fx, before, picked) {
+ s.h.textContent = 'Fixed';
+ s.body.textContent = '';
+ const name = picked.entry ? picked.name : 'Searched as "' + fx.search + '"';
+ const head = el('div', { className: 'done-head' }, thumb(fx.cover || fx.poster, 'big'), el('div', {}, el('div', { className: 'n', textContent: name }),
+ help(picked.entry ? entryLine(picked) : 'No entry pinned'), help(picked.entry ? 'The card shows it in a moment. Episode titles come from this entry.' : 'The card shows it in a moment.')));
+ const group = 'cov' + modalCount;
+ const rCat = el('input', { type: 'radio', name: group, checked: !fx.cover, id: group + '-cat' });
+ const rOwn = el('input', { type: 'radio', name: group, id: group + '-own' });
+ const own = el('input', { type: 'text', value: fx.cover || '', placeholder: 'https://example.com/poster.jpg', spellcheck: false, autocomplete: 'off' });
+ own.setAttribute('aria-label', 'Image address');
+ const covers = el('div', { className: 'covers' }), capt = help('Covers of this title from the other catalogs on under Privacy:');
+ capt.classList.add('hidden');
+ let picks = [];
+ const pick = (url) => { picks.forEach((x) => x.classList.toggle('sel', x.dataset.url === url)); };
+ rCat.onchange = () => pick(''); rOwn.onchange = () => pick('');
+ own.addEventListener('focus', () => { rOwn.checked = true; pick(''); });
+ if (fx.cover) rOwn.checked = true;
+ const bad = el('div', { className: 'help bad hidden' });
+ const sOff = el('input', { type: 'number', value: fx.seasonOffset || 0, min: -500, max: 500 }), eOff = el('input', { type: 'number', value: fx.episodeOffset || 0, min: -500, max: 500 });
+ sOff.setAttribute('aria-label', 'Season offset'); eOff.setAttribute('aria-label', 'Episode offset');
+ const fold = el('details', { className: 'fold', open: !!(fx.seasonOffset || fx.episodeOffset) }, el('summary', { textContent: "Episodes don't line up?" }),
+ el('div', { className: 'offs' }, tx('Season '), sOff, tx(' episode '), eOff),
+ help('Added to the numbers read from the file before the catalogs are asked (0 and 0: no change). Example: a file numbered S01E02 with +12 episodes is looked up as S01E14.'));
+ const undo = el('button', { className: 'link', textContent: 'Undo' }), tell = el('button', { className: 'link', textContent: 'Tell the project about this' });
+ const done = el('button', { className: 'primary', textContent: 'Done' });
+ s.body.append(head,
+ el('div', { className: 'opt' }, rCat, el('label', { htmlFor: rCat.id, textContent: picked.entry ? "This entry's cover" : 'The cover the search finds' })),
+ capt, covers,
+ el('div', { className: 'opt' }, rOwn, el('label', { htmlFor: rOwn.id, textContent: 'An image address' }), own),
+ bad, fold, el('div', { className: 'foot' }, undo, el('span', { className: 'help', textContent: '·' }), tell, el('span', { className: 'grow' }), done));
+ if (picked.entry) {
+ api('match-covers', { name: picked.name, year: picked.year || 0, kind: picked.kind, catalog: picked.catalog, n: 1 }).then((r) => {
+ (r.covers || []).forEach((c) => {
+ const i = el('img', { alt: 'Cover from ' + c.catalog, src: c.url, title: c.catalog, tabIndex: 0 });
+ i.dataset.url = c.url;
+ const choose = () => { rCat.checked = false; rOwn.checked = false; pick(c.url); };
+ i.onclick = choose;
+ i.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); choose(); } };
+ i.onerror = () => i.remove();
+ picks.push(i); covers.append(i);
+ });
+ capt.classList.toggle('hidden', !picks.length);
+ if (fx.cover) pick(fx.cover);
+ }).catch(() => {});
+ }
+ const current = () => {
+ const chosen = picks.find((x) => x.classList.contains('sel'));
+ const cover = rCat.checked ? '' : rOwn.checked ? own.value.trim() : chosen ? chosen.dataset.url : '';
+ const out = Object.assign({}, fx);
+ ['cover', 'seasonOffset', 'episodeOffset'].forEach((k) => { delete out[k]; });
+ if (cover) out.cover = cover;
+ const so = Math.trunc(Number(sOff.value) || 0), eo = Math.trunc(Number(eOff.value) || 0);
+ if (so) out.seasonOffset = so;
+ if (eo) out.episodeOffset = eo;
+ return out;
+ };
+ undo.onclick = async () => { if (await saveFixes(before)) { s.close(); note('Fix undone.'); } };
+ tell.onclick = () => tellProject(current(), playing);
+ done.onclick = async () => {
+ const out = current();
+ if (out.cover && !/^https?:\/\/\S+$/.test(out.cover)) { bad.textContent = 'Enter a web address of an image (starting with https).'; bad.classList.remove('hidden'); own.focus(); return; }
+ if (JSON.stringify(out) === JSON.stringify(fx)) { s.close(); return; }
+ done.disabled = true;
+ if (await saveFixes(withFix(fixesNow(), out))) s.close(); else done.disabled = false;
+ };
+ done.focus();
+ }
+ search(true);
+ (readIn || q).focus();
+ }
+ // "Tell the project about this": the report is shown to be looked over, copied, and posted by the user on GitHub's
+ // issue form (opened at its plain address: no file name goes into a web address). The program sends nothing.
+ async function tellProject(fx, playing) {
+ let text = '';
+ try {
+ text = (await api('match-report', { fix: fx, file: (playing && playing.file) || '', title: (playing && playing.title) || '', season: (playing && playing.season) || 0, episode: (playing && playing.episode) || 0, before: (playing && playing.now) || '' })).text;
+ } catch (e) { note(e.message, true); return; }
+ const ta = el('textarea', { value: text, spellcheck: false, className: 'report' });
+ ta.setAttribute('aria-label', 'Report text');
+ const body = el('div', {}, el('p', { textContent: 'If the program should have found this by itself, a report helps it learn the pattern. The program sends nothing: you copy the text, look it over, and post it on GitHub yourself.' }),
+ ta, help("Folders, players' addresses and sign-ins are left out. You can edit the text before posting."));
+ await modal('Tell the project about this', body, [['Cancel'], ['Copy and open GitHub', 'primary']], true, {
+ focus: 1,
+ hold: async (i) => {
+ if (i !== 1) return true;
+ let ok = false;
+ try { await navigator.clipboard.writeText(ta.value); ok = true; } catch (_) { ta.focus(); ta.select(); try { ok = document.execCommand('copy'); } catch (_) {} }
+ window.open('https://github.com/CptPakundo/MPRP/issues/new/choose', '_blank', 'noopener');
+ note(ok ? 'Copied. Paste it into the new issue and look it over before you post it.' : 'Select the text and copy it, then paste it into the new issue.');
+ return true;
+ },
+ });
+ }
+
// "Set up the player connection" at the top of the Players tab: the same call and confirmation as the card that
// shows when no player is answering
function playerSetupBox() {
@@ -303,7 +743,7 @@
}
function leavesBox() {
const all = el('li', {}, document.createTextNode('Every address the program reaches is listed in '),
- el('a', { href: 'https://github.com/CptPakundo/MPCvibedRPC/blob/master/SECURITY.md#where-it-connects', target: '_blank', rel: 'noopener', textContent: 'SECURITY.md' }),
+ el('a', { href: 'https://github.com/CptPakundo/MPRP/blob/master/SECURITY.md#where-it-connects', target: '_blank', rel: 'noopener', textContent: 'SECURITY.md' }),
document.createTextNode('.'));
// MPC-HC is Windows-only; its web interface answers every web page (no password, any origin)
const mpc = osText() ? [] : ["MPC-HC's web interface has no password, and web pages you open can read it and control the player while it is on. Switch it off in MPC-HC when you stop using this program."];
@@ -534,6 +974,7 @@
model = m;
$('ver').textContent = 'Version ' + m.version;
$('ver').setAttribute('aria-label', 'Changelog (version ' + m.version + ')');
+ $('aboutVer').textContent = 'Version ' + m.version;
if (!$('updText').textContent) $('updText').textContent = 'Version ' + m.version; // until a check says more
$('autoStart').checked = !!m.autoStart; $('startPresence').checked = !!m.app.startPresence; $('openWindow').checked = !!m.app.openWindow; $('minimizeToTray').checked = !!m.app.minimizeToTray;
$('minimizeRow').classList.toggle('hidden', m.os !== 'windows'); // only Windows can tell a minimised window and has a tray for it
@@ -578,6 +1019,7 @@
function paint(s) {
paintPreview(s.preview);
+ lastMatch = s.match || null;
if (typeof s.hideTitle === 'boolean' && model && !saving && model.values.hideTitle !== s.hideTitle) {
model.values.hideTitle = s.hideTitle; // switched from the tray or the menu bar
const box = document.querySelector('input[data-key="hideTitle"]');
@@ -597,9 +1039,9 @@
d.textContent = s.discord === 'connected' ? 'Discord connected' : s.discord === 'waiting' ? 'Waiting for Discord' : s.discord === 'standby' ? 'Discord on standby' : 'Discord idle';
d.title = s.discord === 'standby' ? 'Discord is contacted as soon as something plays.' : s.discord === 'waiting' ? 'Discord was not found yet. Is the desktop app running?' : '';
d.className = s.discord === 'waiting' ? 'warn' : '';
- p.textContent = s.mpc ? (s.player || 'Player') + ' detected' : 'No player found';
- p.className = s.mpc ? '' : 'warn';
- $('stDot').className = 'dot ' + (s.discord === 'waiting' || !s.mpc ? 'warn' : s.discord === 'connected' ? 'good' : '');
+ p.textContent = s.playerAnswers ? (s.player || 'Player') + ' detected' : 'No player found';
+ p.className = s.playerAnswers ? '' : 'warn';
+ $('stDot').className = 'dot ' + (s.discord === 'waiting' || !s.playerAnswers ? 'warn' : s.discord === 'connected' ? 'good' : '');
const now = $('now');
let line = '';
if (!s.running) { /* the first line says it */ }
@@ -609,7 +1051,7 @@
// while the Discord preview is showing, the title is already there: keep only a note that adds something
line = s.preview ? (s.paused ? sub : '') : sub + ': ' + s.nowPlaying;
}
- else if (s.mpc) line = 'Nothing playing. Play something in ' + players() + '.';
+ else if (s.playerAnswers) line = 'Nothing playing. Play something in ' + players() + '.';
now.textContent = line;
now.classList.toggle('hidden', !line);
const t = $('toggle'); t.textContent = s.running ? 'Stop showing' : 'Show on Discord'; t.className = s.running ? '' : 'primary';
@@ -617,7 +1059,7 @@
const live = s.running ? d.textContent + '. ' + p.textContent + '.' : 'Not showing on Discord.';
if ($('liveStatus').textContent !== live) $('liveStatus').textContent = live;
const dp = $('discordProblem'); dp.textContent = s.discordProblem || ''; dp.classList.toggle('hidden', !s.discordProblem);
- $('mpcHelp').classList.toggle('hidden', !(s.running && !s.mpc));
+ $('playerHelp').classList.toggle('hidden', !(s.running && !s.playerAnswers));
const hint = $('playerHint'); hint.textContent = s.hint || ''; hint.classList.toggle('hidden', !s.hint);
if (s.update && s.update.newer && s.update.latest !== updShown && $('installUpd').disabled === false) showUpdate(s.update, false);
paintUpdBanner(s.update);
@@ -628,7 +1070,7 @@
const on = !!(u && u.newer);
updInfo = on ? u : null;
$('updBanner').classList.toggle('hidden', !on);
- if (on) $('updBannerText').textContent = 'MPCvibedRPC ' + u.latest + ' is available.';
+ if (on) $('updBannerText').textContent = 'MPRP ' + u.latest + ' is available.';
}
$('updBannerBtn').onclick = async () => { if (!await askUpdate(updInfo, true)) { showTab('general'); $('updates').scrollIntoView({ block: 'start' }); } };
@@ -636,7 +1078,7 @@
// port that another program, or the next start, may listen on by then).
function closeWindow() {
gone = true; timers.forEach(clearInterval);
- document.body.innerHTML = '
MPCvibedRPC has quit. You can close this window.
';
+ document.body.innerHTML = '
MPRP has quit. You can close this window.
';
try { window.close(); } catch (_) {}
}
let polling = false;
@@ -702,7 +1144,7 @@
$('toggle').onclick = async () => { $('toggle').disabled = true; try { paint(await api(model && running ? 'stop' : 'start', {})); } catch (e) { await ask('Could not change this', e.message, 'OK', false, null); } $('toggle').disabled = false; };
async function restoreDefaults() {
- if (!await ask('Restore defaults?', 'Every setting goes back to its default. This also turns off ' + autoStartName() + ', signs you out of Plex, Stremio, Jellyfin and Emby, and clears the TMDB key, name aliases, pinned covers and your Never show list.', 'Restore', true)) return;
+ if (!await ask('Restore defaults?', 'Every setting goes back to its default. This also turns off ' + autoStartName() + ', signs you out of Plex, Stremio, Jellyfin and Emby, and clears the TMDB key, your fixes (Fix a match) and your Never show list.', 'Restore', true)) return;
later(async () => {
try { fill(await api('reset', {})); note('Defaults restored.'); } catch (e) { note(e.message, true); }
});
@@ -713,8 +1155,8 @@
btn.disabled = true;
msgEl.textContent = 'Working…';
try {
- let r = await api('mpc-web', { closeMpc: false });
- if (r.needsClose) { if (!await ask('Close the player for a moment?', (r.message || 'The player is open and has to be closed for a moment (it will reopen).') + ' Continue?', 'Continue')) { msgEl.textContent = ''; btn.disabled = false; return; } r = await api('mpc-web', { closeMpc: true }); }
+ let r = await api('player-setup', { closePlayers: false });
+ if (r.needsClose) { if (!await ask('Close the player for a moment?', (r.message || 'The player is open and has to be closed for a moment (it will reopen).') + ' Continue?', 'Continue')) { msgEl.textContent = ''; btn.disabled = false; return; } r = await api('player-setup', { closePlayers: true }); }
msgEl.textContent = r.message || (r.ok ? 'Done.' : 'Could not change it.');
if (r.settingsChanged) { // the mpv name or VLC's password may have been taken over; the window is drawn again, so say it here too
// in the queue, like every other change of the window's values: an answer that left before a save still
@@ -793,7 +1235,7 @@
const self = install && model && model.os !== 'darwin' && model.app.checkUpdates && model.app.autoUpdate;
const hint = el('p', { textContent: 'Not now: it installs by itself later, once nothing is playing and the app runs without this window.' });
if (self) body.append(hint);
- await modal('MPCvibedRPC ' + u.latest + ' is available', body, [['Not now'], [install ? 'Update now' : 'Open the download page', 'primary']], true, {
+ await modal('MPRP ' + u.latest + ' is available', body, [['Not now'], [install ? 'Update now' : 'Open the download page', 'primary']], true, {
focus: 1,
hold: async (i) => {
if (i !== 1) return true;
@@ -808,7 +1250,7 @@
}
// Install: download, check, swap, restart. say gets the progress, and the reason when it fails.
async function installUpdate(say) {
- $('installUpd').disabled = true; say('Downloading… MPCvibedRPC restarts by itself.');
+ $('installUpd').disabled = true; say('Downloading… MPRP restarts by itself.');
try { await api('update-install', {}); return true; } catch (e) { say('Could not update: ' + e.message); $('installUpd').disabled = false; return false; }
}
$('checkUpd').onclick = async () => {
@@ -841,10 +1283,12 @@
msg.textContent = ok ? 'Copied. Look it over before you post it: it names what you played (folder paths, sign-ins and keys are left out).' : 'Select the text below and copy it (' + (osText() ? osText().copyKey : 'Ctrl+C') + ').';
} catch (e) { msg.textContent = 'Could not build it: ' + e.message; }
};
- $('reportBtn').onclick = () => window.open('https://github.com/CptPakundo/MPCvibedRPC/issues/new/choose', '_blank', 'noopener');
+ $('reportBtn').onclick = () => window.open('https://github.com/CptPakundo/MPRP/issues/new/choose', '_blank', 'noopener');
$('ver').onclick = () => showChangelog(true);
- // the preview's "Wrong title or cover?": the place where a match is fixed (another name to search under, a pinned cover)
+ $('aboutNews').onclick = () => showChangelog(true);
+ // the preview's "Wrong title or cover?": the Fix this match dialog for what plays, else the list of fixes
$('fixMatch').onclick = () => {
+ if (lastMatch) { openFix({ match: lastMatch }); return; }
showTab('titles');
const h = [...document.querySelectorAll('#p-titles h3.grp')].find((x) => x.textContent === 'Fix a match');
if (h) h.scrollIntoView({ block: 'start' });
@@ -853,9 +1297,9 @@
if (!await ask('Reset your stats?', 'The counts start again from today.', 'Reset', true)) return;
try { paintStats(await api('stats-reset', {})); } catch (e) { note(e.message, true); }
};
- $('quit').onclick = async () => { if (await ask('Quit MPCvibedRPC?', 'Discord stops showing what you watch.', 'Quit', true)) { try { await api('quit', {}); } catch (_) {} closeWindow(); } };
+ $('quit').onclick = async () => { if (await ask('Quit MPRP?', 'Discord stops showing what you watch.', 'Quit', true)) { try { await api('quit', {}); } catch (_) {} closeWindow(); } };
- if (!TOKEN) { document.body.replaceChildren(el('main', {}, el('p', { textContent: 'Open MPCvibedRPC from its tray icon or by launching the program again.' }))); return; }
+ if (!TOKEN) { document.body.replaceChildren(el('main', {}, el('p', { textContent: 'Open MPRP from its tray icon or by launching the program again.' }))); return; }
watchAlive();
api('state').then((m) => {
fill(m); paint(m.status);
diff --git a/internal/conns/conns.go b/internal/conns/conns.go
index ffa81a0..a7a7934 100644
--- a/internal/conns/conns.go
+++ b/internal/conns/conns.go
@@ -11,7 +11,7 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Entry is one host.
diff --git a/internal/conns/conns_test.go b/internal/conns/conns_test.go
index f4a3ae1..d193e52 100644
--- a/internal/conns/conns_test.go
+++ b/internal/conns/conns_test.go
@@ -8,7 +8,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// reset empties the list between tests.
diff --git a/internal/core/activity.go b/internal/core/activity.go
index 580c199..85ebd6e 100644
--- a/internal/core/activity.go
+++ b/internal/core/activity.go
@@ -8,7 +8,7 @@ import (
"strings"
"unicode/utf16"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// ---- Discord wire format -------------------------------------------------------------
@@ -247,6 +247,17 @@ func BuildActivity(info *Info, cfg *Config, now int64, media *Media, art *Art) *
} else {
details = media.Display
}
+ // Text lines other than Standard: the two lines (and a film's cover text) come from their layout. Not in the
+ // stream form, which keeps its own layout, nor without the title in the name.
+ var lines *lineSet
+ var vals map[string]string
+ if titleInName && !stream {
+ if lines = linesFor(cfg, media.IsEpisode); lines != nil {
+ vals = lineValues(info, media, cfg, art, title, effSeason)
+ details = Expand(lines.details, vals)
+ seasonLine, infoLine = Expand(lines.state, vals), ""
+ }
+ }
if details != "" {
a.Details = clip(details)
}
@@ -256,6 +267,11 @@ func BuildActivity(info *Info, cfg *Config, now int64, media *Media, art *Art) *
}
a.State, a.Timestamps = stateAndTimes(info, cfg, now, watching, titleInName, seasonLine, infoLine)
a.Assets = buildAssets(media, cfg, art, title, watching, effSeason, specialLabel)
+ if lines != nil && lines.cover != "" && a.Assets != nil && !media.IsEpisode && cfg.ShowArtwork && art != nil && a.Assets.LargeImage == art.Poster && art.Poster != "" {
+ if t := Expand(lines.cover, vals); t != "" {
+ a.Assets.LargeText = clip(t)
+ }
+ }
if u, site := TitleLink(cfg, art); u != "" && buttonURL(u) {
a.Buttons = []Button{{Label: viewOn(site), URL: u}}
@@ -338,11 +354,22 @@ func animeTitle(title string, cfg *Config, art *Art) string {
// infoParts reads the catalog's extra facts (RichInfo): the genres (at most two), which a film shows in its first
// line, and the info line after the season line: genres and rating for an episode, rating and director for a film.
func infoParts(media *Media, cfg *Config, art *Art) (genres, infoLine string) {
+ genres, rating, director := richParts(media, cfg, art)
+ if media.IsEpisode {
+ infoLine = joinNonEmpty(" · ", genres, rating)
+ } else {
+ infoLine = joinNonEmpty(" · ", rating, director)
+ }
+ return genres, infoLine
+}
+
+// richParts are the catalog's extra facts with their marks: the genres (at most two), "★ 7.1" and, for a film,
+// "Dir. Sample Name"; all empty with RichInfo off.
+func richParts(media *Media, cfg *Config, art *Art) (genres, rating, director string) {
var inf *ArtInfo
if cfg.RichInfo && art != nil && art.Info != nil {
inf = art.Info
}
- rating, director := "", ""
if inf != nil {
if len(inf.Genres) > 0 {
g := inf.Genres
@@ -358,12 +385,7 @@ func infoParts(media *Media, cfg *Config, art *Art) (genres, infoLine string) {
director = "Dir. " + inf.Director
}
}
- if media.IsEpisode {
- infoLine = joinNonEmpty(" · ", genres, rating)
- } else {
- infoLine = joinNonEmpty(" · ", rating, director)
- }
- return genres, infoLine
+ return genres, rating, director
}
// effectiveSeason is the season an episode is shown with: the file's own, else the catalog's, else 1 for a show the
@@ -386,6 +408,31 @@ func effectiveSeason(media *Media, art *Art) int {
// episodeDetails is the first text line of an episode (label and episode title), the season line that goes in front
// of the info line, and eraName, which replaces the status name when a Pokémon season or era is recognised ("" if not).
func episodeDetails(media *Media, cfg *Config, art *Art, title string, effSeason int, specialLabel string, watching bool) (details, seasonLine, eraName string) {
+ p := episodeParts(media, art, title, effSeason)
+ sn, label, epTitle := p.seasonName, p.label, p.epTitle
+ badge := watching && media.Episode != NA && effSeason != NA
+ seasonLine = sn
+ if badge && !cfg.EpisodeInDetails {
+ details = joinNonEmpty(" · ", epTitle)
+ } else {
+ details = joinNonEmpty(" · ", label, epTitle)
+ }
+ if details == "" && sn != "" {
+ details = sn
+ seasonLine = ""
+ }
+ if details == "" {
+ details = specialLabel // a special whose name no catalog has
+ }
+ return details, seasonLine, p.eraName
+}
+
+// epParts are the pieces of an episode's lines: its label ("S01E02", or a special's own words), its title, the name
+// of a named season not already in the title, and the era name that replaces the status name ("" if none).
+type epParts struct{ label, epTitle, seasonName, eraName string }
+
+func episodeParts(media *Media, art *Art, title string, effSeason int) epParts {
+ eraName := ""
var em *jsre.Match
if art != nil && art.SeasonName != "" && rePokemon.Test(title) {
em = reGenre.Exec(art.SeasonName)
@@ -447,33 +494,38 @@ func episodeDetails(media *Media, cfg *Config, art *Art, title string, effSeason
case ep != nil:
epTitle = ep.Title
}
- badge := watching && media.Episode != NA && effSeason != NA
- seasonLine = sn
- if badge && !cfg.EpisodeInDetails {
- details = joinNonEmpty(" · ", epTitle)
- } else {
- details = joinNonEmpty(" · ", label, epTitle)
- }
- if details == "" && sn != "" {
- details = sn
- seasonLine = ""
- }
- if details == "" {
- details = specialLabel // a special whose name no catalog has
- }
- return details, seasonLine, eraName
+ return epParts{label: label, epTitle: epTitle, seasonName: sn, eraName: eraName}
}
// movieDetails is the first text line of a film: its year (the file's, else the catalog's) and the genres.
func movieDetails(media *Media, art *Art, genres string) string {
- year := ""
+ return joinNonEmpty(" · ", filmYear(media, art), genres)
+}
+
+// filmYear is a film's year: the file's, else the catalog's ("" when neither has one).
+func filmYear(media *Media, art *Art) string {
switch {
case truthy(media.Year):
- year = itoa(media.Year)
+ return itoa(media.Year)
case art != nil && art.Type == "movie" && truthy(art.Year):
- year = itoa(art.Year)
+ return itoa(art.Year)
}
- return joinNonEmpty(" · ", year, genres)
+ return ""
+}
+
+// badgeEpisode is the episode number Discord's badge shows: the folder's count, else the number inside a split
+// catalog entry, else the file's (NA without one).
+func badgeEpisode(media *Media, art *Art) int {
+ if media.Episode == NA {
+ return NA
+ }
+ switch {
+ case truthy(media.BadgeEpisode):
+ return media.BadgeEpisode
+ case art != nil && art.Split && truthy(art.EpInEntry):
+ return art.EpInEntry
+ }
+ return media.Episode
}
// StreamProgress is where the video is, for the stream form while it plays: a text progress bar, the length and a
@@ -551,14 +603,7 @@ func buildAssets(media *Media, cfg *Config, art *Art, title string, watching boo
return nil
}
if watching && effSeason != NA && media.Episode != NA {
- ep := media.Episode
- switch {
- case truthy(media.BadgeEpisode):
- ep = media.BadgeEpisode
- case art != nil && art.Split && truthy(art.EpInEntry):
- ep = art.EpInEntry
- }
- assets.LargeText = "Season " + itoa(effSeason) + ", Episode " + itoa(ep)
+ assets.LargeText = "Season " + itoa(effSeason) + ", Episode " + itoa(badgeEpisode(media, art))
if specialLabel != "" {
assets.LargeText = specialLabel
}
diff --git a/internal/core/config.go b/internal/core/config.go
index 73cc28a..38aa40e 100644
--- a/internal/core/config.go
+++ b/internal/core/config.go
@@ -8,167 +8,238 @@ import (
// Config is every setting, with the defaults the program ships with. A user's config.json only needs the keys it
// wants to change; anything missing keeps its default (see LoadConfig).
+//
+// The settings come in four groups, embedded so that each is still cfg. and config.json stays one flat object:
+// - Settings: what the user chooses, in the window or by hand in config.json;
+// - Accounts: what a sign-in writes about the account and the server it follows (private, not secret);
+// - Secrets: the sign-ins' tokens and keys (written only by the sign-ins);
+// - Hooks: where the catalog services are (tests point them at fakes; a server of the user's own is the only other use).
+//
+// Every field's `reach` tag says what the running engine redoes when the setting changes (engine.ApplySettings):
+//
+// check nothing: the next check reads it (the status is sent again with it)
+// lookups the cover and title finder is made again (every setting internal/artwork reads)
+// players the players are looked for again: their event watches and the Plex, Stremio, Jellyfin and Emby watchers
+// discord the connection to Discord is made again
+// none the engine does not use it (names for the window, the sign-in's own values)
type Config struct {
+ Settings
+ Accounts
+ Secrets
+ Hooks
+}
+
+// Settings are what the user chooses.
+type Settings struct {
// Discord / the player
- ClientID string `json:"clientId"`
- Port int `json:"port"` // web interface of MPC-HC, MPC-BE and MPC-QT
- PollInterval int `json:"pollInterval"`
- MpvPipe string `json:"mpvPipe"` // mpv's input-ipc-server name; empty = don't look for mpv
- VlcPort int `json:"vlcPort"` // VLC's web interface (http-port)
- VlcPassword string `json:"vlcPassword"` // its password (http-password); empty = don't look for VLC
- KodiAddress string `json:"kodiAddress"` // Kodi's web server (host:port)
- KodiUser string `json:"kodiUser"` // its user name
- KodiPassword string `json:"kodiPassword"` // its password; empty = don't look for Kodi
- IinaPipe string `json:"iinaPipe"` // macOS: the input-ipc-server path in IINA's mpv options; empty = don't look for IINA
- Mpris bool `json:"mpris"` // Linux: read video players through MPRIS (D-Bus)
-
- // Plex: the sign-in made with "Sign in to Plex" (not typed in the window; empty plexToken = Plex is not followed)
- PlexToken string `json:"plexToken"` // the account's token
- PlexAccount int64 `json:"plexAccount"` // the account's id (on a server the user owns, only their own playback counts)
- PlexUser string `json:"plexUser"` // the account's name, for the window
- PlexServer string `json:"plexServer"` // the chosen server's machine identifier ("" = the account's only or first own server)
- PlexServerName string `json:"plexServerName"` // its name, for the window
- PlexClient string `json:"plexClient"` // this install's Plex client identifier (made at the first sign-in)
- PlexAddress string `json:"plexAddress"` // a fixed address for the server ("" = the addresses plex.tv lists)
- PlexJWT bool `json:"plexJwt"` // sign in with Plex's newer 7-day tokens and this install's own key (off: the long-lived token)
- PlexKey string `json:"plexKey"` // this install's signing key for those tokens (written by the sign-in; a secret)
-
- // Stremio: the sign-in made with "Sign in to Stremio" (not typed in the window; empty = Stremio is not followed)
- StremioKey string `json:"stremioKey"` // the account's key
-
- // Jellyfin or Emby: the sign-in made on the Players tab (not typed in the window; empty jellyfinToken = not followed)
- JellyfinAddress string `json:"jellyfinAddress"` // the server's address (ending in /emby for an Emby server that needs it)
- JellyfinToken string `json:"jellyfinToken"` // this install's sign-in on the server
- JellyfinUser string `json:"jellyfinUser"` // the user's id (only their own playback counts)
- JellyfinUserName string `json:"jellyfinUserName"` // the user's name, for the window
- JellyfinServerName string `json:"jellyfinServerName"` // the server's name, for the window
- JellyfinProduct string `json:"jellyfinProduct"` // Jellyfin or Emby
- JellyfinDevice string `json:"jellyfinDevice"` // this install's device id towards the server (made at the first sign-in)
+ ClientID string `json:"clientId" reach:"discord"`
+ Port int `json:"port" reach:"players"` // web interface of MPC-HC, MPC-BE and MPC-QT
+ PollInterval int `json:"pollInterval" reach:"check"`
+ MpvPipe string `json:"mpvPipe" reach:"players"` // mpv's input-ipc-server name; empty = don't look for mpv
+ VlcPort int `json:"vlcPort" reach:"players"` // VLC's web interface (http-port)
+ VlcPassword string `json:"vlcPassword" reach:"players"` // its password (http-password); empty = don't look for VLC
+ KodiAddress string `json:"kodiAddress" reach:"players"` // Kodi's web server (host:port)
+ KodiUser string `json:"kodiUser" reach:"players"` // its user name
+ KodiPassword string `json:"kodiPassword" reach:"players"` // its password; empty = don't look for Kodi
+ IinaPipe string `json:"iinaPipe" reach:"players"` // macOS: the input-ipc-server path in IINA's mpv options; empty = don't look for IINA
+ Mpris bool `json:"mpris" reach:"players"` // Linux: read video players through MPRIS (D-Bus)
+
+ PlexAddress string `json:"plexAddress" reach:"players"` // a fixed address for the Plex server ("" = the addresses plex.tv lists)
+ PlexJWT bool `json:"plexJwt" reach:"none"` // sign in with Plex's newer 7-day tokens and this install's own key (off: the long-lived token)
// Presentation
- ActivityType string `json:"activityType"` // "watching" (progress bar) or "playing"
- TitleAsName bool `json:"titleAsName"`
+ ActivityType string `json:"activityType" reach:"check"` // "watching" (progress bar) or "playing"
+ TitleAsName bool `json:"titleAsName" reach:"check"`
// StreamTitle says when the status is sent as "Playing ", the only kind Discord names a stream after: "off",
// "auto" (while Discord shares the screen; the engine finds that out and builds with "always" or "off") or "always".
- StreamTitle string `json:"streamTitle"`
- TextProgressBar bool `json:"textProgressBar"`
- ProgressWidth int `json:"progressWidth"`
- ShowRemainingTime bool `json:"showRemainingTime"`
+ // The engine's screen-share watch runs while it is "auto".
+ StreamTitle string `json:"streamTitle" reach:"check"`
+ TextProgressBar bool `json:"textProgressBar" reach:"check"`
+ ProgressWidth int `json:"progressWidth" reach:"check"`
+ ShowRemainingTime bool `json:"showRemainingTime" reach:"check"`
+ // TextLines is the layout of the two text lines (and a film's cover text): "standard" (the built-in lines),
+ // "short", "detailed" or "custom" (CustomLines). See lines.go.
+ TextLines string `json:"textLines" reach:"check"`
+ CustomLines map[string]string `json:"customLines" reach:"check"` // episodeDetails, episodeState, movieDetails, movieState, movieCover
- // HideTitle shows only "Watching a video" (no title, cover or details) and looks nothing up online.
- HideTitle bool `json:"hideTitle"`
+ // HideTitle shows only "Watching a video" (no title, cover or details) and looks nothing up online. A change ends
+ // the lookups under way (they go quietly: no title in the log).
+ HideTitle bool `json:"hideTitle" reach:"lookups"`
// HideFiles lists files that are never shown (see MatchesHideList); they are not looked up either.
- HideFiles []string `json:"hideFiles"`
+ HideFiles []string `json:"hideFiles" reach:"lookups"`
// PauseClearMinutes clears the status after the video has been paused this long (0 = never; the default is 30). It comes back on resume.
- PauseClearMinutes int `json:"pauseClearMinutes"`
+ PauseClearMinutes int `json:"pauseClearMinutes" reach:"check"`
// Filename cleanup
- SmartFormat bool `json:"smartFormat"`
- IgnoreBrackets bool `json:"ignoreBrackets"`
- IgnoreFiletype bool `json:"ignoreFiletype"` // only CleanName uses it (the recorded parse tests); titles never carry the extension
- ReplaceUnderscore bool `json:"replaceUnderscore"`
- ReplaceDots bool `json:"replaceDots"`
+ SmartFormat bool `json:"smartFormat" reach:"check"`
+ IgnoreBrackets bool `json:"ignoreBrackets" reach:"check"`
+ IgnoreFiletype bool `json:"ignoreFiletype" reach:"check"` // only CleanName uses it (the recorded parse tests); titles never carry the extension
+ ReplaceUnderscore bool `json:"replaceUnderscore" reach:"check"`
+ ReplaceDots bool `json:"replaceDots" reach:"check"`
// Artwork
- ShowArtwork bool `json:"showArtwork"`
- ArtworkSources []string `json:"artworkSources"`
+ ShowArtwork bool `json:"showArtwork" reach:"lookups"`
+ ArtworkSources []string `json:"artworkSources" reach:"lookups"`
// DisabledSources lists services (see Sources) that must never be contacted, whatever the lists below say.
- DisabledSources []string `json:"disabledSources"`
- TmdbAPIKey string `json:"tmdbApiKey"`
- ArtworkAliases map[string]string `json:"artworkAliases"`
- ArtworkOverrides map[string]string `json:"artworkOverrides"`
- ArtworkWaitMs int `json:"artworkWaitMs"`
- CinemetaBase string `json:"cinemetaBase"`
- ImdbSuggestBase string `json:"imdbSuggestBase"`
- TvmazeBase string `json:"tvmazeBase"`
- AnilistURL string `json:"anilistUrl"`
- KitsuBase string `json:"kitsuBase"`
- BulbapediaBase string `json:"bulbapediaBase"`
- JikanBase string `json:"jikanBase"`
- AnimeSources []string `json:"animeSources"`
- RequestGapMs map[string]int `json:"requestGapMs"`
- WikipediaBase string `json:"wikipediaBase"`
- LetterboxdBase string `json:"letterboxdBase"`
-
- EpisodeInDetails bool `json:"episodeInDetails"`
- FolderEpisodeNumbers bool `json:"folderEpisodeNumbers"`
- AnimeTitles string `json:"animeTitles"` // auto | english | romaji | file
- CatalogTitle bool `json:"catalogTitle"`
- RichInfo bool `json:"richInfo"`
- LinkButton bool `json:"linkButton"`
- LetterboxdLink bool `json:"letterboxdLink"` // the link opens the title's Letterboxd page when it has one
- UseFolderName bool `json:"useFolderName"`
- EpisodeTitles bool `json:"episodeTitles"`
- EpisodeSources []string `json:"episodeSources"`
+ DisabledSources []string `json:"disabledSources" reach:"lookups"`
+ TmdbAPIKey string `json:"tmdbApiKey" reach:"lookups"`
+ // MatchFixes is Fix a match: what the user said a title (or one file) is. nil when config.json has no
+ // matchFixes key: the legacy maps below are then read as fixes (see Fixes), and the store writes them as
+ // matchFixes once (store.MigrateMatchFixes).
+ MatchFixes []MatchFix `json:"matchFixes" reach:"lookups"`
+ // ArtworkAliases and ArtworkOverrides are the legacy form of Fix a match ("search under another name", "pin a
+ // cover image"), read once into MatchFixes and kept in the file for a downgrade.
+ ArtworkAliases map[string]string `json:"artworkAliases" reach:"lookups"`
+ ArtworkOverrides map[string]string `json:"artworkOverrides" reach:"lookups"`
+ ArtworkWaitMs int `json:"artworkWaitMs" reach:"lookups"`
+ AnimeSources []string `json:"animeSources" reach:"lookups"`
+ RequestGapMs map[string]int `json:"requestGapMs" reach:"lookups"`
+
+ EpisodeInDetails bool `json:"episodeInDetails" reach:"check"`
+ FolderEpisodeNumbers bool `json:"folderEpisodeNumbers" reach:"check"`
+ AnimeTitles string `json:"animeTitles" reach:"lookups"` // auto | english | romaji | file
+ CatalogTitle bool `json:"catalogTitle" reach:"lookups"`
+ RichInfo bool `json:"richInfo" reach:"lookups"`
+ LinkButton bool `json:"linkButton" reach:"lookups"`
+ LetterboxdLink bool `json:"letterboxdLink" reach:"lookups"` // the link opens the title's Letterboxd page when it has one
+ UseFolderName bool `json:"useFolderName" reach:"check"`
+ EpisodeTitles bool `json:"episodeTitles" reach:"lookups"`
+ EpisodeSources []string `json:"episodeSources" reach:"lookups"`
// Discord art assets
- LargeImageKey string `json:"largeImageKey"`
- SmallImageKey string `json:"smallImageKey"`
- AppName string `json:"appName"`
+ LargeImageKey string `json:"largeImageKey" reach:"check"`
+ SmallImageKey string `json:"smallImageKey" reach:"check"`
+ AppName string `json:"appName" reach:"check"`
+}
+
+// Accounts are what the sign-ins write about the account and the server followed (not typed in the window).
+type Accounts struct {
+ // Plex: the sign-in made with "Sign in to Plex"
+ PlexAccount int64 `json:"plexAccount" reach:"players"` // the account's id (on a server the user owns, only their own playback counts)
+ PlexUser string `json:"plexUser" reach:"none"` // the account's name, for the window
+ PlexServer string `json:"plexServer" reach:"players"` // the chosen server's machine identifier ("" = the account's only or first own server)
+ PlexServerName string `json:"plexServerName" reach:"none"` // its name, for the window
+ PlexClient string `json:"plexClient" reach:"players"` // this install's Plex client identifier (made at the first sign-in)
+
+ // Jellyfin or Emby: the sign-in made on the Players tab
+ JellyfinAddress string `json:"jellyfinAddress" reach:"players"` // the server's address (ending in /emby for an Emby server that needs it)
+ JellyfinUser string `json:"jellyfinUser" reach:"players"` // the user's id (only their own playback counts)
+ JellyfinUserName string `json:"jellyfinUserName" reach:"none"` // the user's name, for the window
+ JellyfinServerName string `json:"jellyfinServerName" reach:"none"` // the server's name, for the window
+ JellyfinProduct string `json:"jellyfinProduct" reach:"players"` // Jellyfin or Emby
+ JellyfinDevice string `json:"jellyfinDevice" reach:"players"` // this install's device id towards the server (made at the first sign-in)
+}
+
+// Secrets are the sign-ins' tokens and keys (not typed in the window). An empty one means that service is not followed.
+type Secrets struct {
+ PlexToken string `json:"plexToken" reach:"players"` // the Plex account's token
+ PlexKey string `json:"plexKey" reach:"none"` // this install's signing key for Plex's 7-day tokens (plexJwt)
+ StremioKey string `json:"stremioKey" reach:"players"` // the Stremio account's key
+ JellyfinToken string `json:"jellyfinToken" reach:"players"` // this install's sign-in on the Jellyfin or Emby server
}
+// Hooks are where the catalog services are asked. Tests point them at fakes; a Jikan of the user's own is the only
+// other use.
+type Hooks struct {
+ CinemetaBase string `json:"cinemetaBase" reach:"lookups"`
+ ImdbSuggestBase string `json:"imdbSuggestBase" reach:"lookups"`
+ TvmazeBase string `json:"tvmazeBase" reach:"lookups"`
+ AnilistURL string `json:"anilistUrl" reach:"lookups"`
+ KitsuBase string `json:"kitsuBase" reach:"lookups"`
+ BulbapediaBase string `json:"bulbapediaBase" reach:"lookups"`
+ JikanBase string `json:"jikanBase" reach:"lookups"`
+ WikipediaBase string `json:"wikipediaBase" reach:"lookups"`
+ LetterboxdBase string `json:"letterboxdBase" reach:"lookups"`
+}
+
+// DefaultClientID is the project's own Discord application (named MPRP, with the program's logo): the default
+// clientId. Every install depends on it.
+const DefaultClientID = "1575219115981934734"
+
+// FormerClientID is the Discord application every install used before ("Media Player Classic", registered by the
+// upstream project). A saved clientId of this value reads as DefaultClientID (store.settingsObj).
+const FormerClientID = "427863248734388224"
+
// DefaultConfig returns a fresh copy of the defaults.
func DefaultConfig() Config {
return Config{
- ClientID: "427863248734388224",
- Port: 13579,
- PollInterval: 5000,
- MpvPipe: "mpvsocket",
- VlcPort: 8080,
- KodiAddress: "127.0.0.1:8080",
- KodiUser: "kodi",
- IinaPipe: "iina-mpvsocket",
- Mpris: true,
-
- PauseClearMinutes: 30,
-
- ActivityType: "watching",
- TitleAsName: true,
- StreamTitle: "auto",
- TextProgressBar: true,
- ProgressWidth: 12,
- ShowRemainingTime: false,
-
- SmartFormat: true,
- IgnoreBrackets: true,
- IgnoreFiletype: true,
- ReplaceUnderscore: true,
- ReplaceDots: true,
-
- ShowArtwork: true,
- ArtworkSources: []string{"tmdb", "imdb", "cinemeta", "tvmaze", "anilist", "kitsu", "wikipedia"},
- DisabledSources: []string{},
- HideFiles: []string{},
- ArtworkAliases: map[string]string{},
- ArtworkOverrides: map[string]string{},
- ArtworkWaitMs: 1500,
- CinemetaBase: "https://v3-cinemeta.strem.io",
- ImdbSuggestBase: "https://v3.sg.media-imdb.com",
- TvmazeBase: "https://api.tvmaze.com",
- AnilistURL: "https://graphql.anilist.co",
- KitsuBase: "https://kitsu.io/api/edge",
- BulbapediaBase: "https://bulbapedia.bulbagarden.net",
- JikanBase: "https://api.jikan.moe/v4", // the public Jikan API closed on 2026-10-01: Jikan is in no source list by default
- AnimeSources: []string{"anilist", "kitsu"},
- RequestGapMs: map[string]int{"graphql.anilist.co": 250, "api.jikan.moe": 400},
- WikipediaBase: "https://{lang}.wikipedia.org",
- LetterboxdBase: "https://letterboxd.com",
-
- EpisodeInDetails: false,
- FolderEpisodeNumbers: false,
- AnimeTitles: "auto",
- CatalogTitle: true,
- RichInfo: true,
- LinkButton: true,
- UseFolderName: true,
- EpisodeTitles: true,
- EpisodeSources: []string{"bulbapedia", "tmdb", "tvmaze", "cinemeta", "kitsu"}, // "jikan" (a self-hosted Jikan in jikanBase) would go first for anime
-
- LargeImageKey: "mpc-hc",
- SmallImageKey: "mpc-hc",
- AppName: "Media Player Classic",
+ Settings: Settings{
+ ClientID: DefaultClientID,
+ Port: 13579,
+ PollInterval: 5000,
+ MpvPipe: "mpvsocket",
+ VlcPort: 8080,
+ KodiAddress: "127.0.0.1:8080",
+ KodiUser: "kodi",
+ IinaPipe: "iina-mpvsocket",
+ Mpris: true,
+
+ PauseClearMinutes: 30,
+
+ ActivityType: "watching",
+ TitleAsName: true,
+ StreamTitle: "auto",
+ TextProgressBar: true,
+ ProgressWidth: 12,
+ ShowRemainingTime: false,
+ TextLines: "standard",
+ CustomLines: map[string]string{},
+
+ SmartFormat: true,
+ IgnoreBrackets: true,
+ IgnoreFiletype: true,
+ ReplaceUnderscore: true,
+ ReplaceDots: true,
+
+ ShowArtwork: true,
+ ArtworkSources: []string{"tmdb", "imdb", "cinemeta", "tvmaze", "anilist", "kitsu", "wikipedia"},
+ DisabledSources: []string{},
+ HideFiles: []string{},
+ ArtworkAliases: map[string]string{},
+ ArtworkOverrides: map[string]string{},
+ ArtworkWaitMs: 1500,
+ AnimeSources: []string{"anilist", "kitsu"},
+ RequestGapMs: map[string]int{"graphql.anilist.co": 250, "api.jikan.moe": 400},
+
+ EpisodeInDetails: false,
+ FolderEpisodeNumbers: false,
+ AnimeTitles: "auto",
+ CatalogTitle: true,
+ RichInfo: true,
+ LinkButton: true,
+ UseFolderName: true,
+ EpisodeTitles: true,
+ EpisodeSources: []string{"bulbapedia", "tmdb", "tvmaze", "cinemeta", "kitsu"}, // "jikan" (a self-hosted Jikan in jikanBase) would go first for anime
+
+ LargeImageKey: "mpc-hc",
+ SmallImageKey: "mpc-hc",
+ AppName: "Media Player Classic",
+ },
+ Hooks: Hooks{
+ CinemetaBase: "https://v3-cinemeta.strem.io",
+ ImdbSuggestBase: "https://v3.sg.media-imdb.com",
+ TvmazeBase: "https://api.tvmaze.com",
+ AnilistURL: "https://graphql.anilist.co",
+ KitsuBase: "https://kitsu.io/api/edge",
+ BulbapediaBase: "https://bulbapedia.bulbagarden.net",
+ JikanBase: "https://api.jikan.moe/v4", // the public Jikan API closed on 2026-10-01: Jikan is in no source list by default
+ WikipediaBase: "https://{lang}.wikipedia.org",
+ LetterboxdBase: "https://letterboxd.com",
+ },
+ }
+}
+
+// ConfigFields lists the fields of Config that hold a setting (those of its groups, not the groups themselves), in
+// order. Use reflect.Value.FieldByIndex with their Index.
+func ConfigFields() []reflect.StructField {
+ var out []reflect.StructField
+ for _, f := range reflect.VisibleFields(reflect.TypeOf(Config{})) {
+ if !f.Anonymous {
+ out = append(out, f)
+ }
}
+ return out
}
// LoadConfig applies the keys present in a user's JSON on top of the defaults. It is a shallow merge:
@@ -184,16 +255,14 @@ func LoadConfig(userJSON []byte) Config {
return cfg
}
v := reflect.ValueOf(&cfg).Elem()
- t := v.Type()
- for i := 0; i < t.NumField(); i++ {
- key := t.Field(i).Tag.Get("json")
- msg, ok := raw[key]
+ for _, f := range ConfigFields() {
+ msg, ok := raw[f.Tag.Get("json")]
if !ok || string(msg) == "null" {
continue
}
- fresh := reflect.New(t.Field(i).Type)
+ fresh := reflect.New(f.Type)
if json.Unmarshal(msg, fresh.Interface()) == nil {
- v.Field(i).Set(fresh.Elem())
+ v.FieldByIndex(f.Index).Set(fresh.Elem())
}
}
return cfg
diff --git a/internal/core/config_default_test.go b/internal/core/config_default_test.go
index 0e9b340..82d82f4 100644
--- a/internal/core/config_default_test.go
+++ b/internal/core/config_default_test.go
@@ -7,3 +7,21 @@ func TestDefaultPauseClearIsThirtyMinutes(t *testing.T) {
t.Errorf("PauseClearMinutes default = %d, want 30", got)
}
}
+
+// The groups of Config (Settings, Accounts, Secrets, Hooks) are embedded: config.json stays one flat object, and every
+// setting is read and written under its own name.
+func TestConfigGroupsStayFlat(t *testing.T) {
+ m := ConfigAsMap(&Config{})
+ for _, group := range []string{"Settings", "Accounts", "Secrets", "Hooks"} {
+ if _, ok := m[group]; ok {
+ t.Errorf("config.json would hold a %q object", group)
+ }
+ }
+ if len(m) != len(ConfigFields()) {
+ t.Errorf("config.json has %d keys, Config %d settings", len(m), len(ConfigFields()))
+ }
+ cfg := LoadConfig([]byte(`{"plexToken":"t","clientId":"1","cinemetaBase":"http://127.0.0.1:1","plexUser":"u"}`))
+ if cfg.PlexToken != "t" || cfg.ClientID != "1" || cfg.CinemetaBase != "http://127.0.0.1:1" || cfg.PlexUser != "u" {
+ t.Errorf("a setting of a group was not loaded: %+v", cfg)
+ }
+}
diff --git a/internal/core/fixes.go b/internal/core/fixes.go
new file mode 100644
index 0000000..54c87fe
--- /dev/null
+++ b/internal/core/fixes.go
@@ -0,0 +1,177 @@
+package core
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+)
+
+// MatchFix is one fix made in Fix a match: what the user said a title, or one file, is.
+//
+// A fix applies to every file read as Match (the read title, compared the way the cover finder compares titles), or,
+// with File set, to the one file whose base name is Match (any case). A file fix wins over a title fix. Entry pins a
+// catalog page (IMDb, TMDB, TVmaze, AniList or Kitsu); Search searches under another name instead; Cover is an image
+// address shown in place of the catalog's cover. The offsets are added to the season and episode read from the file
+// before the catalogs are asked (0 and 0: none). Label and Poster only describe the pinned entry in the window.
+type MatchFix struct {
+ Match string `json:"match"`
+ File bool `json:"file,omitempty"`
+ Entry string `json:"entry,omitempty"`
+ Search string `json:"search,omitempty"`
+ Cover string `json:"cover,omitempty"`
+ SeasonOffset int `json:"seasonOffset,omitempty"`
+ EpisodeOffset int `json:"episodeOffset,omitempty"`
+ Label string `json:"label,omitempty"`
+ Poster string `json:"poster,omitempty"`
+}
+
+// Fixes is Fix a match as the program uses it: matchFixes, or, while config.json has none (an install from before
+// matchFixes), the legacy artworkAliases and artworkOverrides lines read as fixes, so they act as before.
+func (c *Config) Fixes() []MatchFix {
+ if c.MatchFixes != nil {
+ return c.MatchFixes
+ }
+ return LegacyFixes(c.ArtworkAliases, c.ArtworkOverrides)
+}
+
+// LegacyFixes turns the legacy maps into fixes: one per title (sorted), the alias as Search and the pinned cover as
+// Cover; a title in both is one fix. nil when both are empty.
+func LegacyFixes(aliases, overrides map[string]string) []MatchFix {
+ var keys []string
+ seen := map[string]bool{}
+ for _, m := range []map[string]string{aliases, overrides} {
+ for k := range m {
+ if !seen[k] {
+ seen[k] = true
+ keys = append(keys, k)
+ }
+ }
+ }
+ sort.Strings(keys)
+ var out []MatchFix
+ for _, k := range keys {
+ f := MatchFix{Match: k, Search: aliases[k], Cover: overrides[k]}
+ if f.Search != "" || f.Cover != "" {
+ out = append(out, f)
+ }
+ }
+ return out
+}
+
+var (
+ reLabelSE = regexp.MustCompile(`^S(\d+)E(\d+)$`)
+ reLabelE = regexp.MustCompile(`^E(\d+)$`)
+
+ reEntryImdb = regexp.MustCompile(`^https?://(?:www\.|m\.)?imdb\.com/title/(tt\d{5,10})/?(?:[?#].*)?$`)
+ reEntryTmdb = regexp.MustCompile(`^https?://(?:www\.)?themoviedb\.org/(movie|tv)/(\d{1,10})(?:-[\w-]*)?/?(?:[?#].*)?$`)
+ reEntryTvmaze = regexp.MustCompile(`^https?://(?:www\.)?tvmaze\.com/shows/(\d{1,10})(?:/[\w-]*)?/?(?:[?#].*)?$`)
+ reEntryAnilist = regexp.MustCompile(`^https?://anilist\.co/anime/(\d{1,10})(?:/[^/?#]*)?/?(?:[?#].*)?$`)
+ reEntryKitsu = regexp.MustCompile(`^https?://kitsu\.(?:io|app)/anime/([\w-]{1,100})/?(?:[?#].*)?$`)
+)
+
+// Entry is a catalog page a fix pins: which catalog (a core.Sources id), the kind when the address tells it ("movie",
+// "series" or ""), and the catalog's own id (a Kitsu slug for Kitsu).
+type Entry struct{ Catalog, Kind, ID string }
+
+// EntryPage reads a catalog page address (IMDb, TMDB, TVmaze, AniList or Kitsu); ok is false for anything else.
+func EntryPage(u string) (e Entry, ok bool) {
+ if len(u) > 512 {
+ return e, false
+ }
+ if m := reEntryImdb.FindStringSubmatch(u); m != nil {
+ return Entry{Catalog: "imdb", ID: m[1]}, true
+ }
+ if m := reEntryTmdb.FindStringSubmatch(u); m != nil {
+ kind := "movie"
+ if m[1] == "tv" {
+ kind = "series"
+ }
+ return Entry{Catalog: "tmdb", Kind: kind, ID: m[2]}, true
+ }
+ if m := reEntryTvmaze.FindStringSubmatch(u); m != nil {
+ return Entry{Catalog: "tvmaze", Kind: "series", ID: m[1]}, true
+ }
+ if m := reEntryAnilist.FindStringSubmatch(u); m != nil {
+ return Entry{Catalog: "anilist", ID: m[1]}, true
+ }
+ if m := reEntryKitsu.FindStringSubmatch(u); m != nil {
+ return Entry{Catalog: "kitsu", ID: m[1]}, true
+ }
+ return e, false
+}
+
+// ShiftMedia adds a fix's season and episode offsets to what was read from the file (after folderEpisodeNumbers chose
+// the file's number), so that the catalogs are asked, and the card shows, the catalog's numbers. ok is false, and
+// media is returned as it is, when a number would fall below 1. A season offset needs a season read from the file.
+func ShiftMedia(media *Media, season, episode int) (out *Media, ok bool) {
+ if media == nil || !media.IsEpisode || (season == 0 && episode == 0) {
+ return media, true
+ }
+ cp := *media
+ if season != 0 && cp.Season != NA {
+ cp.Season += season
+ if cp.Season < 1 {
+ return media, false
+ }
+ }
+ if episode != 0 && cp.Episode != NA {
+ cp.Episode += episode
+ if cp.Episode < 1 {
+ return media, false
+ }
+ if truthy(cp.BadgeEpisode) {
+ cp.BadgeEpisode += episode
+ if cp.BadgeEpisode < 1 {
+ return media, false
+ }
+ }
+ }
+ relabel := func(p string) string {
+ if m := reLabelSE.FindStringSubmatch(p); m != nil && cp.Season != NA && cp.Episode != NA {
+ return "S" + pad2n(cp.Season) + "E" + pad2n(cp.Episode)
+ }
+ if m := reLabelE.FindStringSubmatch(p); m != nil && cp.Episode != NA {
+ return "E" + pad2n(cp.Episode)
+ }
+ return p
+ }
+ cp.Parts = make([]string, len(media.Parts))
+ for i, p := range media.Parts {
+ cp.Parts[i] = relabel(p)
+ }
+ if len(cp.Parts) > 0 {
+ cp.Label = joinParts(cp.Parts)
+ } else {
+ cp.Label = relabel(cp.Label)
+ }
+ return &cp, true
+}
+
+func joinParts(parts []string) string {
+ s := ""
+ for i, p := range parts {
+ if i > 0 {
+ s += " · "
+ }
+ s += p
+ }
+ return s
+}
+
+// OffsetText says what a fix's offsets do, for the window and the reports: "seasons +1, episodes +12" ("" for none).
+func OffsetText(season, episode int) string {
+ sign := func(n int) string {
+ if n > 0 {
+ return "+" + strconv.Itoa(n)
+ }
+ return strconv.Itoa(n)
+ }
+ var parts []string
+ if season != 0 {
+ parts = append(parts, "seasons "+sign(season))
+ }
+ if episode != 0 {
+ parts = append(parts, "episodes "+sign(episode))
+ }
+ return joinNonEmpty(", ", parts...)
+}
diff --git a/internal/core/icons.go b/internal/core/icons.go
index b43258b..008879f 100644
--- a/internal/core/icons.go
+++ b/internal/core/icons.go
@@ -4,7 +4,7 @@ import "strings"
// PlayerIconBase is where the player logos in docs/players are served from. Discord fetches the small icon of a
// status by its address (through its own image proxy), so nothing is uploaded and nothing about the user is sent.
-const PlayerIconBase = "https://raw.githubusercontent.com/CptPakundo/MPCvibedRPC/master/docs/players/"
+const PlayerIconBase = "https://raw.githubusercontent.com/CptPakundo/MPRP/master/docs/players/"
// playerIcons names the logo file of each player that has one. The MPC family has its own too: the default Discord
// application has no mpc-hc image (its assets are default, pause_small, play_small, stop_small and mpcbe_logo, checked
diff --git a/internal/core/lines.go b/internal/core/lines.go
new file mode 100644
index 0000000..f2b19d9
--- /dev/null
+++ b/internal/core/lines.go
@@ -0,0 +1,117 @@
+package core
+
+import (
+ "regexp"
+ "strings"
+)
+
+// Text lines (Look > Text lines): the two text lines of the status, and a film's cover text, written as a line with
+// placeholders. "standard" is not a template: it is BuildActivity's own code path, which the recorded golden data
+// pins. The page draws its sample with the same rules (MPRP_LINES in ui.js; testdata/lines.json holds the cases both
+// must agree on).
+
+// LineSep separates the parts of a line; a part that ends up empty is dropped with its separator.
+const LineSep = " · "
+
+// lineSet is one layout: an episode's two lines, or a film's two lines and its cover text ("" = today's).
+type lineSet struct{ details, state, cover string }
+
+// DefaultCoverLine is a film's cover text in every layout, and what an empty custom cover text falls back to.
+const DefaultCoverLine = "{title}[ ({year})]"
+
+// linePresets are Short and Detailed: episode first and second line, film first and second line.
+var linePresets = map[string][4]string{
+ "short": {"{code}" + LineSep + "{episodeTitle}", "", "{year}", "{director}"},
+ "detailed": {"{code}" + LineSep + "{episodeTitle}", "{genres}" + LineSep + "{rating}" + LineSep + "[on {player}]", "{year}" + LineSep + "{genres}" + LineSep + "{length}", "{rating}" + LineSep + "{director}" + LineSep + "[on {player}]"},
+}
+
+// CustomLineKeys are the keys of customLines.
+var CustomLineKeys = []string{"episodeDetails", "episodeState", "movieDetails", "movieState", "movieCover"}
+
+// linesFor is the layout textLines asks for, or nil for Standard (and for a value this version does not know).
+func linesFor(cfg *Config, episode bool) *lineSet {
+ var l [4]string
+ cover := DefaultCoverLine
+ switch cfg.TextLines {
+ case "short", "detailed":
+ l = linePresets[cfg.TextLines]
+ case "custom":
+ c := cfg.CustomLines
+ l = [4]string{c["episodeDetails"], c["episodeState"], c["movieDetails"], c["movieState"]}
+ if strings.TrimSpace(c["movieCover"]) != "" {
+ cover = c["movieCover"]
+ }
+ default:
+ return nil
+ }
+ if episode {
+ return &lineSet{details: l[0], state: l[1]}
+ }
+ return &lineSet{details: l[2], state: l[3], cover: cover}
+}
+
+var (
+ rePlaceholder = regexp.MustCompile(`\{(\w+)\}`)
+ reSection = regexp.MustCompile(`\[([^\[\]]*)\]`)
+)
+
+// Expand fills a line: each known {name} becomes its value (an unknown name stays as typed); a part in [ ] drops out
+// whole when a placeholder in it is empty (its brackets go either way); the line is split at " · " and empty parts are
+// dropped; then it is trimmed and cut to Discord's 128 characters (125 and "...").
+func Expand(tpl string, vals map[string]string) string {
+ s := reSection.ReplaceAllStringFunc(tpl, func(m string) string {
+ inner := m[1 : len(m)-1]
+ for _, p := range rePlaceholder.FindAllStringSubmatch(inner, -1) {
+ if v, ok := vals[p[1]]; ok && v == "" {
+ return ""
+ }
+ }
+ return inner
+ })
+ s = rePlaceholder.ReplaceAllStringFunc(s, func(m string) string {
+ if v, ok := vals[m[1:len(m)-1]]; ok {
+ return v
+ }
+ return m
+ })
+ var keep []string
+ for _, p := range strings.Split(s, LineSep) {
+ if p = trim(p); p != "" {
+ keep = append(keep, p)
+ }
+ }
+ s = trim(strings.Join(keep, LineSep))
+ if u16len(s) > 128 {
+ s = u16slice(s, 0, 125) + "..."
+ }
+ return s
+}
+
+// lineValues are the placeholders' values for one status, from what BuildActivity already worked out. An episode
+// knows every name (empty where it has no value); a film has no episode names, so {code} stays as typed there.
+func lineValues(info *Info, media *Media, cfg *Config, art *Art, title string, effSeason int) map[string]string {
+ genres, rating, director := richParts(media, cfg, art)
+ length := ""
+ if info.Duration > 0 {
+ length = fmtTime(info.Duration)
+ }
+ v := map[string]string{"title": title, "genres": genres, "rating": rating, "director": director, "player": cfg.AppName, "length": length}
+ if !media.IsEpisode {
+ v["year"] = filmYear(media, art)
+ return v
+ }
+ v["year"] = ""
+ if truthy(media.Year) {
+ v["year"] = itoa(media.Year)
+ }
+ p := episodeParts(media, art, title, effSeason)
+ v["code"], v["episodeTitle"], v["seasonName"] = p.label, p.epTitle, p.seasonName
+ v["season"], v["episode"] = "", ""
+ if effSeason != NA {
+ v["season"] = itoa(effSeason)
+ }
+ if n := badgeEpisode(media, art); n != NA {
+ v["episode"] = itoa(n)
+ }
+ return v
+}
diff --git a/internal/core/lines_test.go b/internal/core/lines_test.go
new file mode 100644
index 0000000..476d3b0
--- /dev/null
+++ b/internal/core/lines_test.go
@@ -0,0 +1,191 @@
+package core
+
+import (
+ "encoding/json"
+ "os"
+ "strings"
+ "testing"
+)
+
+// linesTable is testdata/lines.json, which the page's test reads too (internal/assets): the page's sample and the card
+// must fill a line the same way.
+type linesTable struct {
+ Values map[string]map[string]string `json:"values"`
+ Cases []struct {
+ Values, Tpl, Want string
+ } `json:"cases"`
+}
+
+func TestExpandFollowsTheSharedTable(t *testing.T) {
+ b, err := os.ReadFile("testdata/lines.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var tab linesTable
+ if err := json.Unmarshal(b, &tab); err != nil {
+ t.Fatal(err)
+ }
+ if len(tab.Cases) < 10 {
+ t.Fatalf("only %d cases", len(tab.Cases))
+ }
+ for _, c := range tab.Cases {
+ vals, ok := tab.Values[c.Values]
+ if !ok {
+ t.Fatalf("no values %q", c.Values)
+ }
+ if got := Expand(c.Tpl, vals); got != c.Want {
+ t.Errorf("Expand(%q) = %q, want %q", c.Tpl, got, c.Want)
+ }
+ if u16len(Expand(c.Tpl, vals)) > 128 {
+ t.Errorf("Expand(%q) is longer than 128", c.Tpl)
+ }
+ }
+}
+
+// sample: an episode with a catalog title and info, and a film, as the design's table has them.
+func sampleEpisode() (*Info, *Art) {
+ info := &Info{File: "Sample.Show.S01E02.mkv", State: 2, Position: 60000, Duration: 2700000, Rate: 1}
+ art := NewArt()
+ art.Type, art.Name, art.Source, art.Poster = "series", "Sample Show", "TVmaze", "https://img.example/show.jpg"
+ art.Info = &ArtInfo{Genres: []string{"Drama", "Comedy"}, Rating: 8.3}
+ art.Episode = &ArtEpisode{Title: "Sample Episode", Season: 1, Number: 2, Source: "TVmaze"}
+ return info, art
+}
+
+func sampleMovie() (*Info, *Art) {
+ info := &Info{File: "Sample.Movie.2020.mkv", State: 2, Position: 60000, Duration: 6730000, Rate: 1}
+ art := NewArt()
+ art.Type, art.Name, art.Source, art.Poster, art.Year = "movie", "Sample Movie", "Cinemeta", "https://img.example/movie.jpg", 2020
+ art.Info = &ArtInfo{Genres: []string{"Drama", "Comedy"}, Rating: 7.1, Director: "Sample Name"}
+ return info, art
+}
+
+func withLines(mode string, custom map[string]string) Config {
+ cfg := DefaultConfig()
+ cfg.AppName = "VLC media player"
+ cfg.TextLines = mode
+ if custom != nil {
+ cfg.CustomLines = custom
+ }
+ return cfg
+}
+
+func TestTextLinesPresets(t *testing.T) {
+ cases := []struct {
+ mode string
+ epDetails, epState string
+ mvDetails, mvState, mvLargeTx string
+ }{
+ {"standard", "Sample Episode", "Drama, Comedy · ★ 8.3", "2020 · Drama, Comedy", "★ 7.1 · Dir. Sample Name", "Sample Movie (2020)"},
+ {"short", "S01E02 · Sample Episode", "", "2020", "Dir. Sample Name", "Sample Movie (2020)"},
+ {"detailed", "S01E02 · Sample Episode", "Drama, Comedy · ★ 8.3 · on VLC media player", "2020 · Drama, Comedy · 1:52:10", "★ 7.1 · Dir. Sample Name · on VLC media player", "Sample Movie (2020)"},
+ {"something new", "Sample Episode", "Drama, Comedy · ★ 8.3", "2020 · Drama, Comedy", "★ 7.1 · Dir. Sample Name", "Sample Movie (2020)"}, // read as Standard
+ }
+ for _, c := range cases {
+ cfg := withLines(c.mode, nil)
+ info, art := sampleEpisode()
+ a := BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Name != "Sample Show" || a.Details != c.epDetails || a.State != c.epState {
+ t.Errorf("%s episode: name %q, details %q, state %q", c.mode, a.Name, a.Details, a.State)
+ }
+ if a.Assets == nil || a.Assets.LargeText != "Season 1, Episode 2" {
+ t.Errorf("%s episode: the cover text must stay the badge's: %+v", c.mode, a.Assets)
+ }
+ info, art = sampleMovie()
+ a = BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Name != "Sample Movie" || a.Details != c.mvDetails || a.State != c.mvState || a.Assets.LargeText != c.mvLargeTx {
+ t.Errorf("%s film: name %q, details %q, state %q, cover %q", c.mode, a.Name, a.Details, a.State, a.Assets.LargeText)
+ }
+ }
+}
+
+func TestTextLinesCustom(t *testing.T) {
+ custom := map[string]string{
+ "episodeDetails": "{title} {code} · {episodeTitle}",
+ "episodeState": "[{seasonName}] · {genres} · [on {player}]",
+ "movieDetails": "{director} · {titel}",
+ "movieCover": "{title} · {length}",
+ }
+ cfg := withLines("custom", custom)
+ info, art := sampleEpisode()
+ a := BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Details != "Sample Show S01E02 · Sample Episode" || a.State != "Drama, Comedy · on VLC media player" {
+ t.Errorf("episode: %q / %q", a.Details, a.State)
+ }
+ if a.Timestamps == nil || a.Timestamps.End == 0 {
+ t.Errorf("the progress bar must stay: %+v", a.Timestamps)
+ }
+ info, art = sampleMovie()
+ a = BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Details != "Dir. Sample Name · {titel}" || a.State != "" || a.Assets.LargeText != "Sample Movie · 1:52:10" {
+ t.Errorf("film: %q / %q / %q (a missing line is an empty line)", a.Details, a.State, a.Assets.LargeText)
+ }
+
+ // an empty cover text is today's; a film without a year drops the brackets
+ cfg.CustomLines = map[string]string{"movieDetails": "{year}", "movieCover": " "}
+ info, art = sampleMovie()
+ art.Year = NA
+ info.File = "Sample.Movie.mkv"
+ a = BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Details != "" || a.Assets.LargeText != "Sample Movie" {
+ t.Errorf("film without a year: details %q, cover %q", a.Details, a.Assets.LargeText)
+ }
+
+ // a film without catalog data: no cover of its own, so no cover text of the user's (the logo's text stays)
+ a = BuildActivity(&Info{File: "Sample Movie (2020).mkv", State: 2, Duration: 6000000, Rate: 1}, &cfg, 1_700_000_000_000, nil, nil)
+ if a.Details != "2020" || a.Assets == nil || a.Assets.LargeText != cfg.AppName {
+ t.Errorf("film without catalog data: %q, %+v", a.Details, a.Assets)
+ }
+}
+
+// Text lines never reach the pause line, the stream form, a hidden title, a status without the title as its name,
+// or a song (the engine builds songs with "standard").
+func TestTextLinesLeaveTheFixedPartsAlone(t *testing.T) {
+ custom := map[string]string{"episodeDetails": "X {title}", "episodeState": "Y {code}", "movieDetails": "X", "movieState": "Y", "movieCover": "Z"}
+ cfg := withLines("custom", custom)
+ std := withLines("standard", nil)
+
+ info, art := sampleEpisode()
+ info.State = 1
+ a := BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a.Details != "X Sample Show" || !strings.HasPrefix(a.State, "⏸ ") {
+ t.Errorf("paused: %q / %q, want the custom first line and the pause line", a.Details, a.State)
+ }
+
+ same := func(what string) {
+ t.Helper()
+ info, art := sampleEpisode()
+ if got, want := BuildActivity(info, &cfg, 1_700_000_000_000, nil, art), BuildActivity(info, &std, 1_700_000_000_000, nil, art); mustJSON(got) != mustJSON(want) {
+ t.Errorf("%s changed:\n%s\n%s", what, mustJSON(got), mustJSON(want))
+ }
+ }
+ cfg.StreamTitle, std.StreamTitle = "always", "always"
+ same("the stream form")
+ cfg.StreamTitle, std.StreamTitle = "off", "off"
+
+ cfg.TitleAsName, std.TitleAsName = false, false
+ same("without the title as the name, the status")
+ cfg.TitleAsName, std.TitleAsName = true, true
+
+ cfg.ActivityType, std.ActivityType = "playing", "playing" // the Playing style has no title in the name either
+ same("the Playing style")
+ cfg.ActivityType, std.ActivityType = "watching", "watching"
+
+ cfg.HideTitle, std.HideTitle = true, true
+ info, _ = sampleEpisode()
+ if got, want := HiddenActivity(info, &cfg, 1_700_000_000_000), HiddenActivity(info, &std, 1_700_000_000_000); mustJSON(got) != mustJSON(want) {
+ t.Errorf("a hidden title changed:\n%s\n%s", mustJSON(got), mustJSON(want))
+ }
+}
+
+// A special's own words fill {code}; Standard's fallbacks are not template rules.
+func TestTextLinesSpecial(t *testing.T) {
+ cfg := withLines("short", nil)
+ info := &Info{File: "Sample Show - Special 03.mkv", State: 2, Duration: 1500000, Rate: 1}
+ art := NewArt()
+ art.Type, art.Name, art.Source, art.Special = "series", "Sample Show", "TVmaze", true
+ a := BuildActivity(info, &cfg, 1_700_000_000_000, nil, art)
+ if a == nil || a.Details != "Special 3" || a.State != "" {
+ t.Errorf("special: %+v", a)
+ }
+}
diff --git a/internal/core/name.go b/internal/core/name.go
new file mode 100644
index 0000000..1687e4e
--- /dev/null
+++ b/internal/core/name.go
@@ -0,0 +1,35 @@
+package core
+
+import "os"
+
+// Name is the program's name: its data folder, run-at-login entry, window identity and the answer of its local API
+// ("app" in /api/ping) carry it.
+const Name = "MPRP"
+
+// FormerName is the name the program had before it was renamed. Only the steps that carry an existing install over
+// use it: the data folder, the run-at-login entry and the check for a copy of the former version that still runs.
+const FormerName = "MPCvibedRPC"
+
+// FormerEnv pairs each environment variable the program reads with the one the former version read for the same
+// thing ({current, former}). The former version starts the copy it updated itself to with its own environment: a copy
+// with a data folder of its own passes it as MPCRPC_HOME, and the new copy must use that folder too. The env lines of
+// tools/ci/former-names.txt list the same pairs (TestFormerEnvMatchesTheList).
+var FormerEnv = [][2]string{
+ {"MPRP_HOME", "MPCRPC_HOME"},
+ {"MPRP_BROWSER", "MPCRPC_BROWSER"},
+ {"MPRP_FOREGROUND", "MPCRPC_FOREGROUND"},
+ {"MPRP_UPDATE_API", "MPCRPC_UPDATE_API"},
+}
+
+// AdoptFormerEnv gives each variable of FormerEnv that is not set the value of its former twin, when that one is set.
+// main calls it first, before anything reads the environment.
+func AdoptFormerEnv() {
+ for _, p := range FormerEnv {
+ if _, set := os.LookupEnv(p[0]); set {
+ continue
+ }
+ if v, set := os.LookupEnv(p[1]); set {
+ _ = os.Setenv(p[0], v)
+ }
+ }
+}
diff --git a/internal/core/name_test.go b/internal/core/name_test.go
new file mode 100644
index 0000000..4623b3e
--- /dev/null
+++ b/internal/core/name_test.go
@@ -0,0 +1,52 @@
+package core
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+// The env lines of tools/ci/former-names.txt (which the release check reads) are FormerEnv, in the same order.
+func TestFormerEnvMatchesTheList(t *testing.T) {
+ b, err := os.ReadFile(filepath.Join("..", "..", "tools", "ci", "former-names.txt"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var listed [][2]string
+ for _, line := range strings.Split(string(b), "\n") {
+ if w := strings.Fields(line); len(w) == 3 && w[0] == "env" {
+ listed = append(listed, [2]string{w[1], w[2]})
+ }
+ }
+ if !reflect.DeepEqual(listed, FormerEnv) {
+ t.Errorf("former-names.txt lists %v, FormerEnv is %v", listed, FormerEnv)
+ }
+}
+
+// unsetEnv removes a variable for the rest of the test (and puts it back afterwards).
+func unsetEnv(t *testing.T, k string) {
+ t.Setenv(k, "")
+ os.Unsetenv(k)
+}
+
+func TestAdoptFormerEnv(t *testing.T) {
+ for _, p := range FormerEnv {
+ unsetEnv(t, p[0])
+ unsetEnv(t, p[1])
+ }
+ t.Setenv("MPCRPC_HOME", "/tmp/sample-home")
+ t.Setenv("MPCRPC_BROWSER", "none")
+ t.Setenv("MPRP_BROWSER", "") // set, even if empty: the current name wins
+ AdoptFormerEnv()
+ if v, ok := os.LookupEnv("MPRP_HOME"); !ok || v != "/tmp/sample-home" {
+ t.Errorf("MPRP_HOME = %q (%v), want the former variable's value", v, ok)
+ }
+ if v := os.Getenv("MPRP_BROWSER"); v != "" {
+ t.Errorf("MPRP_BROWSER = %q: a variable that is set must be left as it is", v)
+ }
+ if _, ok := os.LookupEnv("MPRP_UPDATE_API"); ok {
+ t.Error("MPRP_UPDATE_API was set although neither name was")
+ }
+}
diff --git a/internal/core/parse.go b/internal/core/parse.go
index 30f1bb7..b2761c2 100644
--- a/internal/core/parse.go
+++ b/internal/core/parse.go
@@ -3,7 +3,7 @@ package core
import (
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// ---- MPC-HC variables.html ---------------------------------------------------------
@@ -491,9 +491,10 @@ type Media struct {
Junk bool
// filled in by later stages
- DurationMin int // 0 = unknown
- CodeEpisode int // NA
- BadgeEpisode int // NA
+ DurationMin int // 0 = unknown
+ CodeEpisode int // NA
+ BadgeEpisode int // NA
+ File string // the file's base name, set by the engine for Fix a match's "only this file" ("" = none)
}
func newMedia() *Media {
diff --git a/internal/core/preview.go b/internal/core/preview.go
index b10963b..40d9f43 100644
--- a/internal/core/preview.go
+++ b/internal/core/preview.go
@@ -21,8 +21,8 @@ type Preview struct {
Linked bool `json:"linked,omitempty"` // the details line and the cover open the catalog page
}
-// PreviewOf describes an activity for the window. The name falls back to the configured application name, which is
-// what Discord shows when an activity carries none.
+// PreviewOf describes an activity for the window. When an activity carries no name, Discord shows the application's:
+// MPRP for the default application, else the configured application name (the best guess for one of the user's own).
func PreviewOf(a *Activity, cfg *Config) *Preview {
if a == nil {
return nil
@@ -30,6 +30,9 @@ func PreviewOf(a *Activity, cfg *Config) *Preview {
p := &Preview{Watching: a.Type == 3, Listening: a.Type == 2, Name: a.Name, Details: a.Details, State: a.State}
if p.Name == "" && cfg != nil {
p.Name = cfg.AppName
+ if cfg.ClientID == DefaultClientID {
+ p.Name = Name
+ }
}
if a.Assets != nil {
if strings.HasPrefix(a.Assets.LargeImage, "http://") || strings.HasPrefix(a.Assets.LargeImage, "https://") {
diff --git a/internal/core/preview_test.go b/internal/core/preview_test.go
index 5a7374c..393021b 100644
--- a/internal/core/preview_test.go
+++ b/internal/core/preview_test.go
@@ -22,12 +22,18 @@ func TestPreviewOf(t *testing.T) {
t.Errorf("times/button: %+v", p)
}
- // an uploaded Discord asset (not an address) gives no image to load; the name falls back to the app name
+ // an uploaded Discord asset (not an address) gives no image to load; the name falls back to the application's:
+ // MPRP for the default one, the configured app name for one of the user's own
b := &Activity{Details: "Movie", Assets: &Assets{LargeImage: "mpc-hc"}}
q := PreviewOf(b, &cfg)
- if q.Watching || q.Name != cfg.AppName || q.LargeImage != "" {
+ if q.Watching || q.Name != Name || q.LargeImage != "" {
t.Errorf("asset-key preview: %+v", q)
}
+ own := cfg
+ own.ClientID = "123456789012345678"
+ if q := PreviewOf(b, &own); q.Name != own.AppName {
+ t.Errorf("own application: name %q want %q", q.Name, own.AppName)
+ }
// only web addresses are ever handed to the page
for _, bad := range []string{"javascript:alert(1)", "file:///etc/passwd", "data:image/png;base64,AAAA", "//host/x.jpg"} {
if r := PreviewOf(&Activity{Assets: &Assets{LargeImage: bad}}, &cfg); r.LargeImage != "" {
diff --git a/internal/core/privacy.go b/internal/core/privacy.go
index 68bd361..c27d262 100644
--- a/internal/core/privacy.go
+++ b/internal/core/privacy.go
@@ -133,7 +133,8 @@ func HiddenActivity(info *Info, cfg *Config, now int64) *Activity {
}
c := *cfg
c.TitleAsName, c.RichInfo, c.LinkButton, c.EpisodeInDetails, c.CatalogTitle, c.ShowArtwork = false, false, false, false, false, false
- c.StreamTitle = "off" // a hidden title names nothing, on a stream either
+ c.StreamTitle = "off" // a hidden title names nothing, on a stream either
+ c.TextLines = "standard" // and no text lines of the user's reach it
plain := &Info{File: "video", State: info.State, Position: info.Position, Duration: info.Duration, Rate: info.Rate}
a := BuildActivity(plain, &c, now, nil, nil)
if a == nil {
diff --git a/internal/core/testdata/lines.json b/internal/core/testdata/lines.json
new file mode 100644
index 0000000..7f29221
--- /dev/null
+++ b/internal/core/testdata/lines.json
@@ -0,0 +1,144 @@
+{
+ "note": "Text lines: templates, values and the line each must give. Read by internal/core (Expand) and by the page's test in internal/assets (MPRP_LINES.expand in ui.js), so the two cannot drift.",
+ "values": {
+ "episode": {
+ "title": "Sample Show",
+ "year": "",
+ "genres": "Drama, Comedy",
+ "rating": "★ 8.3",
+ "director": "",
+ "player": "VLC media player",
+ "length": "45:00",
+ "code": "S01E02",
+ "season": "1",
+ "episode": "2",
+ "episodeTitle": "Sample Episode",
+ "seasonName": ""
+ },
+ "movie": {
+ "title": "Sample Movie",
+ "year": "2020",
+ "genres": "Drama, Comedy",
+ "rating": "★ 7.1",
+ "director": "Dir. Sample Name",
+ "player": "VLC media player",
+ "length": "1:52:10"
+ },
+ "bare": {
+ "title": "Sample Movie",
+ "year": "",
+ "genres": "",
+ "rating": "",
+ "director": "",
+ "player": "",
+ "length": ""
+ }
+ },
+ "cases": [
+ {
+ "values": "episode",
+ "tpl": "{episodeTitle}",
+ "want": "Sample Episode"
+ },
+ {
+ "values": "episode",
+ "tpl": "{code} · {episodeTitle}",
+ "want": "S01E02 · Sample Episode"
+ },
+ {
+ "values": "episode",
+ "tpl": "{seasonName} · {genres} · {rating}",
+ "want": "Drama, Comedy · ★ 8.3"
+ },
+ {
+ "values": "episode",
+ "tpl": "{genres} · {rating} · [on {player}]",
+ "want": "Drama, Comedy · ★ 8.3 · on VLC media player"
+ },
+ {
+ "values": "episode",
+ "tpl": "[Season {season}] [{seasonName} arc]",
+ "want": "Season 1"
+ },
+ {
+ "values": "episode",
+ "tpl": "{titel} · {title}",
+ "want": "{titel} · Sample Show"
+ },
+ {
+ "values": "episode",
+ "tpl": "[{titel}]",
+ "want": "{titel}"
+ },
+ {
+ "values": "episode",
+ "tpl": " · {seasonName} · ",
+ "want": ""
+ },
+ {
+ "values": "episode",
+ "tpl": "",
+ "want": ""
+ },
+ {
+ "values": "episode",
+ "tpl": " {title} ",
+ "want": "Sample Show"
+ },
+ {
+ "values": "episode",
+ "tpl": "E{episode} of S{season}",
+ "want": "E2 of S1"
+ },
+ {
+ "values": "episode",
+ "tpl": "[no placeholder] {title}",
+ "want": "no placeholder Sample Show"
+ },
+ {
+ "values": "episode",
+ "tpl": "[unclosed {title}",
+ "want": "[unclosed Sample Show"
+ },
+ {
+ "values": "movie",
+ "tpl": "{year} · {genres} · {length}",
+ "want": "2020 · Drama, Comedy · 1:52:10"
+ },
+ {
+ "values": "movie",
+ "tpl": "{rating} · {director} · [on {player}]",
+ "want": "★ 7.1 · Dir. Sample Name · on VLC media player"
+ },
+ {
+ "values": "movie",
+ "tpl": "{title}[ ({year})]",
+ "want": "Sample Movie (2020)"
+ },
+ {
+ "values": "movie",
+ "tpl": "{code} · {title}",
+ "want": "{code} · Sample Movie"
+ },
+ {
+ "values": "bare",
+ "tpl": "{title}[ ({year})]",
+ "want": "Sample Movie"
+ },
+ {
+ "values": "bare",
+ "tpl": "{year} · {genres} · [on {player}]",
+ "want": ""
+ },
+ {
+ "values": "movie",
+ "tpl": "{title} ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★",
+ "want": "Sample Movie ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★..."
+ },
+ {
+ "values": "movie",
+ "tpl": "🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬 {title}",
+ "want": "🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬🎬 ..."
+ }
+ ]
+}
diff --git a/internal/core/util.go b/internal/core/util.go
index 8253c06..fd43497 100644
--- a/internal/core/util.go
+++ b/internal/core/util.go
@@ -7,7 +7,7 @@ import (
"unicode"
"unicode/utf16"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// NA marks "no value" for the optional numbers (season, episode, year, ...), like null/undefined in JavaScript.
diff --git a/internal/dbus/dbus.go b/internal/dbus/dbus.go
index 6b49c53..74f6ddc 100644
--- a/internal/dbus/dbus.go
+++ b/internal/dbus/dbus.go
@@ -86,14 +86,23 @@ func unescape(s string) string {
return b.String()
}
-// Conn is a connection to a bus. Calls are made one at a time.
+// Conn is a connection to a bus. Calls are made one at a time, unless Receive reads the connection in the background.
type Conn struct {
- mu sync.Mutex
- c net.Conn
- r *bufio.Reader
- serial uint32
+ mu sync.Mutex
+ c net.Conn
+ r *bufio.Reader
+ serial uint32
+ replies map[uint32]chan *Message // while Receive reads: the calls waiting for their answer
+ ended error // why Receive's reading stopped (the connection is then of no more use)
}
+// ErrEnded is returned by a call on a connection whose reading (Receive) has stopped.
+var ErrEnded = errors.New("dbus: the connection has ended")
+
+// ErrNoAnswer is the error (wrapped) of a call made while Receive reads the connection that got no answer in time. The
+// connection itself may still be fine: the other side may only be slow.
+var ErrNoAnswer = errors.New("dbus: no answer")
+
// Dial connects to the bus at address, logs in and says Hello. each step (connecting, logging in, Hello) gets the timeout.
func Dial(address string, timeout time.Duration) (*Conn, error) {
paths := socketPaths(address)
@@ -175,12 +184,62 @@ func (e *Error) Error() string {
return e.Name + ": " + e.Message
}
-// Call calls a method and returns the values of its answer. sig is the signature of args ("" for none).
+// Call calls a method and returns the values of its answer. sig is the signature of args ("" for none). The bus does
+// not start a program to answer it (FlagNoAutoStart).
func (c *Conn) Call(dest, path, iface, member string, timeout time.Duration, sig string, args ...any) ([]any, error) {
+ return c.call(FlagNoAutoStart, dest, path, iface, member, timeout, sig, args)
+}
+
+// CallStart is Call for a service that the bus may start to answer (a notification service started on demand).
+func (c *Conn) CallStart(dest, path, iface, member string, timeout time.Duration, sig string, args ...any) ([]any, error) {
+ return c.call(0, dest, path, iface, member, timeout, sig, args)
+}
+
+// Receive reads the connection in the background from now on: answers go to the calls that wait for them, and
+// on is called with each signal (on the reading goroutine: it must not block, nor make calls itself). Calls may then
+// be made from several goroutines at once. When the connection ends, so does the reading; calls then fail with
+// ErrEnded.
+func (c *Conn) Receive(on func(*Message)) {
+ c.mu.Lock()
+ c.replies = map[uint32]chan *Message{}
+ c.mu.Unlock()
+ go func() {
+ for {
+ m, err := ReadMessage(c.r)
+ if err != nil {
+ c.mu.Lock()
+ c.ended = err
+ for s, ch := range c.replies {
+ close(ch)
+ delete(c.replies, s)
+ }
+ c.mu.Unlock()
+ return
+ }
+ switch m.Type {
+ case TypeSignal:
+ on(m)
+ case TypeMethodReturn, TypeError:
+ c.mu.Lock()
+ ch := c.replies[m.ReplySerial]
+ delete(c.replies, m.ReplySerial)
+ c.mu.Unlock()
+ if ch != nil {
+ ch <- m // buffered: never blocks
+ }
+ }
+ }
+ }()
+}
+
+func (c *Conn) call(flags byte, dest, path, iface, member string, timeout time.Duration, sig string, args []any) ([]any, error) {
c.mu.Lock()
+ if c.replies != nil {
+ return c.callReceiving(flags, dest, path, iface, member, timeout, sig, args) // unlocks c.mu
+ }
defer c.mu.Unlock()
c.serial++
- m := &Message{Type: TypeMethodCall, Flags: FlagNoAutoStart, Serial: c.serial, Path: path, Interface: iface,
+ m := &Message{Type: TypeMethodCall, Flags: flags, Serial: c.serial, Path: path, Interface: iface,
Member: member, Destination: dest, Signature: sig, Body: args}
b, err := m.Marshal()
if err != nil {
@@ -199,13 +258,60 @@ func (c *Conn) Call(dest, path, iface, member string, timeout time.Duration, sig
if r.ReplySerial != m.Serial || (r.Type != TypeMethodReturn && r.Type != TypeError) {
continue // a signal (NameAcquired, ...) or someone else's answer
}
- if r.Type == TypeError {
- e := &Error{Name: r.ErrorName}
- if len(r.Body) > 0 {
- e.Message, _ = r.Body[0].(string)
- }
- return nil, e
+ return answer(r)
+ }
+}
+
+// callReceiving makes a call while Receive reads the connection: it waits for the answer the reader hands over.
+// c.mu is held on entry and released here.
+func (c *Conn) callReceiving(flags byte, dest, path, iface, member string, timeout time.Duration, sig string, args []any) ([]any, error) {
+ if c.ended != nil {
+ c.mu.Unlock()
+ return nil, ErrEnded
+ }
+ c.serial++
+ m := &Message{Type: TypeMethodCall, Flags: flags, Serial: c.serial, Path: path, Interface: iface,
+ Member: member, Destination: dest, Signature: sig, Body: args}
+ b, err := m.Marshal()
+ if err != nil {
+ c.mu.Unlock()
+ return nil, err
+ }
+ ch := make(chan *Message, 1)
+ c.replies[m.Serial] = ch
+ _ = c.c.SetWriteDeadline(time.Now().Add(timeout))
+ _, err = c.c.Write(b)
+ _ = c.c.SetWriteDeadline(time.Time{})
+ if err != nil {
+ delete(c.replies, m.Serial)
+ c.mu.Unlock()
+ return nil, err
+ }
+ c.mu.Unlock()
+ t := time.NewTimer(timeout)
+ defer t.Stop()
+ select {
+ case r, ok := <-ch:
+ if !ok {
+ return nil, ErrEnded
+ }
+ return answer(r)
+ case <-t.C:
+ c.mu.Lock()
+ delete(c.replies, m.Serial)
+ c.mu.Unlock()
+ return nil, fmt.Errorf("%w to %s.%s within %v", ErrNoAnswer, iface, member, timeout)
+ }
+}
+
+// answer turns a method return into its values and an error reply into an *Error.
+func answer(r *Message) ([]any, error) {
+ if r.Type == TypeError {
+ e := &Error{Name: r.ErrorName}
+ if len(r.Body) > 0 {
+ e.Message, _ = r.Body[0].(string)
}
- return r.Body, nil
+ return nil, e
}
+ return r.Body, nil
}
diff --git a/internal/dbus/dbus_test.go b/internal/dbus/dbus_test.go
index c722c71..77b558d 100644
--- a/internal/dbus/dbus_test.go
+++ b/internal/dbus/dbus_test.go
@@ -3,12 +3,14 @@ package dbus_test
import (
"bytes"
"errors"
+ "fmt"
"reflect"
+ "sync"
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
)
func TestRoundTrip(t *testing.T) {
@@ -45,6 +47,30 @@ func TestRoundTrip(t *testing.T) {
}
}
+// A []byte is a byte array, also inside a struct in a variant (as a notification's image-data hint carries it), and
+// comes back as the same bytes.
+func TestByteSlices(t *testing.T) {
+ pix := []byte{1, 2, 3, 4, 250, 251, 252, 253}
+ hints := map[string]any{"image-data": dbus.Variant{Sig: "(iiibiiay)", Value: []any{int32(2), int32(1), int32(8), true, int32(8), int32(4), pix}}}
+ m := &dbus.Message{Type: dbus.TypeMethodCall, Serial: 3, Path: "/p", Member: "M", Signature: "yaya{sv}", Body: []any{byte(9), []byte{}, hints}}
+ raw, err := m.Marshal()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := dbus.ReadMessage(bytes.NewReader(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ asAny := []any{}
+ for _, b := range pix {
+ asAny = append(asAny, b)
+ }
+ want := []any{byte(9), []any{}, map[string]any{"image-data": []any{int32(2), int32(1), int32(8), true, int32(8), int32(4), asAny}}}
+ if !reflect.DeepEqual(got.Body, want) {
+ t.Errorf("body:\n got %#v\nwant %#v", got.Body, want)
+ }
+}
+
// A message as a big-endian bus would send it: a method return carrying the string "ok" (written out by hand from the
// specification).
func TestBigEndian(t *testing.T) {
@@ -86,6 +112,7 @@ func TestMarshalRejectsWrongValues(t *testing.T) {
{Signature: "ss", Body: []any{"one"}},
{Signature: "a{sv}", Body: []any{map[string]any{"k": "not a variant"}}},
{Signature: "z", Body: []any{1}},
+ {Signature: "as", Body: []any{[]byte("not strings")}},
} {
if _, err := m.Marshal(); err == nil {
t.Errorf("%q %v should be refused", m.Signature, m.Body)
@@ -135,3 +162,48 @@ func TestDialFailures(t *testing.T) {
}
}
}
+
+// While Receive reads the connection, calls from several goroutines get their own answers, signals go to the
+// handler, and once the connection ends calls fail at once.
+func TestReceive(t *testing.T) {
+ bus := dbustest.New(t)
+ bus.Own("org.example.Thing", func(m *dbus.Message) dbustest.Reply {
+ return dbustest.Reply{Sig: "s", Body: []any{"echo: " + m.Body[0].(string)}}
+ })
+ c, err := dbus.Dial(bus.Address, 2*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ signals := make(chan string, 1)
+ c.Receive(func(m *dbus.Message) { signals <- m.Member })
+ if _, err := c.Call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "AddMatch", time.Second, "s", "type='signal'"); err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ s := fmt.Sprint(i)
+ got, err := c.CallStart("org.example.Thing", "/", "org.example.Thing", "Echo", time.Second, "s", s)
+ if err != nil || !reflect.DeepEqual(got, []any{"echo: " + s}) {
+ t.Errorf("call %d = %v, %v", i, got, err)
+ }
+ }(i)
+ }
+ wg.Wait()
+ bus.Emit(&dbus.Message{Serial: 5, Path: "/a", Interface: "org.example.Thing", Member: "Changed", Signature: ""})
+ select {
+ case got := <-signals:
+ if got != "Changed" {
+ t.Errorf("signal %q", got)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("the signal did not arrive")
+ }
+ c.Close()
+ time.Sleep(50 * time.Millisecond)
+ if _, err := c.Call("org.example.Thing", "/", "org.example.Thing", "Echo", time.Second, "s", "x"); err == nil {
+ t.Error("a call on an ended connection should fail")
+ }
+}
diff --git a/internal/dbus/dbustest/dbustest.go b/internal/dbus/dbustest/dbustest.go
index b86b7f4..49b8f08 100644
--- a/internal/dbus/dbustest/dbustest.go
+++ b/internal/dbus/dbustest/dbustest.go
@@ -12,7 +12,7 @@ import (
"sync"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus"
)
// Reply is what a handler answers: values with their signature, or an error name.
diff --git a/internal/dbus/message.go b/internal/dbus/message.go
index e81437e..4227b71 100644
--- a/internal/dbus/message.go
+++ b/internal/dbus/message.go
@@ -11,7 +11,8 @@ import (
// Message is one D-Bus message. Body holds the values described by Signature: strings for s/o/g, the Go integer of
// the matching size, float64 for d, bool for b, []any for arrays and structs, map[string]any for dictionaries (keys
-// written with fmt) and, when decoding, the value inside a variant. To encode a variant, pass a Variant.
+// written with fmt) and, when decoding, the value inside a variant. To encode a variant, pass a Variant; a byte array
+// (ay) can also be encoded from a []byte (it is decoded as []any).
type Message struct {
Type byte
Flags byte
@@ -385,6 +386,11 @@ func (e *encoder) value(t string, v any) error {
return err
}
}
+ } else if x, ok := v.([]byte); ok {
+ if elem != "y" {
+ return wrongType(t, v)
+ }
+ e.b = append(e.b, x...)
} else {
var items []any
switch x := v.(type) {
diff --git a/internal/diag/diag.go b/internal/diag/diag.go
index dbeb8c4..976615e 100644
--- a/internal/diag/diag.go
+++ b/internal/diag/diag.go
@@ -12,9 +12,9 @@ import (
"sort"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
// Input is everything the report is made from.
@@ -137,7 +137,7 @@ func summarise(key string, v any) string {
switch key {
case "hideFiles":
return fmt.Sprintf("(%d entries)", count(v)) // the user's private list stays private
- case "artworkOverrides":
+ case "artworkOverrides", "matchFixes":
b, _ := json.Marshal(v)
return reURL.ReplaceAllString(string(b), "${1}${2}/…") // which titles have a pinned cover, and from which server
}
@@ -192,7 +192,7 @@ func yn(b bool) string {
func Report(in Input) string {
var b strings.Builder
w := func(f string, a ...any) { fmt.Fprintf(&b, f+"\n", a...) }
- w("MPCvibedRPC diagnostics")
+ w("MPRP diagnostics")
w("Version: %s", in.Version)
w("System: %s", in.System)
if len(in.Players) > 0 {
@@ -234,12 +234,12 @@ func Report(in Input) string {
}
w("")
w("State")
- w(" Presence on: %s", yn(in.Status.Running))
+ w(" Showing on Discord: %s", yn(in.Status.Running))
w(" Discord: %s", in.Status.Discord)
- if in.Status.MPC && in.Status.Player != "" {
+ if in.Status.PlayerAnswers && in.Status.Player != "" {
w(" Player reachable: yes (%s)", in.Status.Player)
} else {
- w(" Player reachable: %s", yn(in.Status.MPC))
+ w(" Player reachable: %s", yn(in.Status.PlayerAnswers))
}
w(" Something playing: %s (paused: %s, hidden: %s, cleared while paused: %s)", yn(in.Status.NowPlaying != nil), yn(in.Status.Paused), yn(in.Status.Hidden), yn(in.Status.PauseCleared))
if in.Status.NowPlaying != nil {
@@ -257,7 +257,7 @@ func Report(in Input) string {
}
w("")
w("App settings")
- w(" start with Windows: %s, start presence at launch: %s, show window at launch: %s, minimize to the tray: %s, check for updates: %s, install them automatically: %s", yn(in.App.AutoStart), yn(in.App.StartPresence), yn(in.App.OpenWindow), yn(in.App.MinimizeToTray), yn(in.App.CheckUpdates), yn(in.App.AutoUpdate))
+ w(" start with Windows: %s, show on Discord when the app opens: %s, show window at launch: %s, minimize to the tray: %s, check for updates: %s, install them automatically: %s", yn(in.App.AutoStart), yn(in.App.StartPresence), yn(in.App.OpenWindow), yn(in.App.MinimizeToTray), yn(in.App.CheckUpdates), yn(in.App.AutoUpdate))
if in.App.UpdateRepo != store.DefaultUpdateRepo {
w(" update source: (custom)")
}
diff --git a/internal/diag/diag_test.go b/internal/diag/diag_test.go
index 8966a96..1f1ae55 100644
--- a/internal/diag/diag_test.go
+++ b/internal/diag/diag_test.go
@@ -1,13 +1,12 @@
package diag
import (
- "reflect"
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/engine"
- "github.com/CptPakundo/MPCvibedRPC/internal/store"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/engine"
+ "github.com/CptPakundo/MPRP/internal/store"
)
func TestRedact(t *testing.T) {
@@ -67,9 +66,8 @@ func TestPrivateKeysCoverEverySignIn(t *testing.T) {
// names that sound private but hold nothing personal: Discord image names, a switch, a product name, a folder rule
public := map[string]bool{"largeImageKey": true, "smallImageKey": true, "plexJwt": true, "jellyfinProduct": true, "useFolderName": true}
words := []string{"token", "key", "password", "address", "user", "account", "server", "secret", "device"}
- rt := reflect.TypeOf(core.Config{})
- for i := 0; i < rt.NumField(); i++ {
- tag := strings.Split(rt.Field(i).Tag.Get("json"), ",")[0]
+ for _, f := range core.ConfigFields() {
+ tag := strings.Split(f.Tag.Get("json"), ",")[0]
lower := strings.ToLower(tag)
private := false
for _, w := range words {
@@ -122,7 +120,7 @@ func TestReportKeepsTitlesLeavesOutPrivateThings(t *testing.T) {
in := Input{
Version: "9.9.9", System: "Test OS 1.0", Players: []string{"MPC-BE"},
Config: cfg, App: store.App{UpdateRepo: "someone/secret-fork"},
- Status: engine.Status{Running: true, Discord: "connected", MPC: true, NowPlaying: &np, LastError: &le},
+ Status: engine.Status{Running: true, Discord: "connected", PlayerAnswers: true, NowPlaying: &np, LastError: &le},
Log: []string{
`[2026-01-01T00:00:00.000Z] INFO Playing: Sample Show · S01E02 (MPC-BE: "Sample.Show.S01E02.mkv")`,
`[2026-01-01T00:00:00.000Z] INFO Artwork for "Sample Show": found via imdb.`,
diff --git a/internal/discord/discord.go b/internal/discord/discord.go
index d046d59..3432c37 100644
--- a/internal/discord/discord.go
+++ b/internal/discord/discord.go
@@ -16,7 +16,7 @@ import (
"sync/atomic"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
// Opcodes of the IPC protocol.
diff --git a/internal/engine/apply.go b/internal/engine/apply.go
new file mode 100644
index 0000000..9c889c7
--- /dev/null
+++ b/internal/engine/apply.go
@@ -0,0 +1,129 @@
+package engine
+
+import (
+ "reflect"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
+)
+
+// reach is what the running engine redoes for a changed setting: the `reach` tag of each core.Config field.
+type reach uint8
+
+const (
+ reachCheck reach = 1 << iota // the next check reads it: the status is only sent again
+ reachLookups // the cover and title finder is made again
+ reachPlayers // the players are looked for again (event watches, Plex, Stremio, Jellyfin and Emby)
+ reachDiscord // the connection to Discord is made again
+)
+
+// reachNames are the tag's values; "none" (the engine does not use the setting) is no bit.
+var reachNames = map[string]reach{"none": 0, "check": reachCheck, "lookups": reachLookups, "players": reachPlayers, "discord": reachDiscord}
+
+// settingReach is each setting's reach, in the order of core.ConfigFields. A field without a known tag counts as
+// everything (TestEverySettingHasAReach keeps that from happening).
+var settingReach = func() []reach {
+ fields := core.ConfigFields()
+ out := make([]reach, len(fields))
+ for i, f := range fields {
+ r, ok := reachNames[f.Tag.Get("reach")]
+ if !ok {
+ r = reachCheck | reachLookups | reachPlayers | reachDiscord
+ }
+ out[i] = r
+ }
+ return out
+}()
+
+// reachOf is what a change from old to cfg needs, and whether anything changed at all.
+func reachOf(old, cfg core.Config) (need reach, changed bool) {
+ a, b := reflect.ValueOf(old), reflect.ValueOf(cfg)
+ for i, f := range core.ConfigFields() {
+ if !reflect.DeepEqual(a.FieldByIndex(f.Index).Interface(), b.FieldByIndex(f.Index).Interface()) {
+ need |= settingReach[i]
+ changed = true
+ }
+ }
+ return need, changed
+}
+
+// ApplySettings gives the engine new settings. A running engine redoes only what the changed settings reach (see
+// core.Config): the run goes on, so the status does not blink, the pause clock and a status cleared after a long pause
+// stay as they are, and Discord's connection stays open unless the Discord application changed. Settings that did not
+// change (a save of an app-only option such as "Start with Windows") change nothing.
+func (e *Engine) ApplySettings(cfg core.Config) {
+ e.stopMu.Lock()
+ defer e.stopMu.Unlock()
+ e.mu.Lock()
+ old := e.cfg
+ need, changed := reachOf(old, cfg)
+ if !changed {
+ e.mu.Unlock()
+ return
+ }
+ e.cfg = cfg
+ r := e.cur
+ if r == nil || need == 0 {
+ e.mu.Unlock()
+ return
+ }
+ e.cfgGen++ // a check under way with the old settings sends nothing (the next one, asked for below, does)
+ if need&reachLookups != 0 {
+ // lookups still under way finish quietly: no title in the log, no refresh (hideTitle may be on now)
+ e.art.Close()
+ e.art = e.newArtwork(cfg)
+ }
+ if need&reachPlayers != 0 {
+ if e.stopRemote != nil {
+ e.stopRemote()
+ }
+ e.remotes, e.stopRemote = nil, nil // the next check starts them with the new sign-ins (unless it rests)
+ e.vlcProblem, e.kodiProblem = "", ""
+ e.startPlayerWatch(r)
+ }
+ if (old.StreamTitle == "auto") != (cfg.StreamTitle == "auto") {
+ e.startShareWatch(r, cfg)
+ }
+ var drop *discord.Client
+ if need&reachDiscord != 0 {
+ // The next check connects with the new settings; an attempt still under way for the old ones is let go.
+ drop, e.discGen = e.rpc, e.discGen+1
+ e.rpc, e.ready, e.connecting, e.shown, e.preview = nil, false, false, false, nil
+ e.warnedDisc, e.discRefused = false, false
+ e.modeKey, e.basicMode, e.noLinks = "", false, false
+ e.sendFails, e.retryAt = 0, time.Time{}
+ }
+ e.resend = true // what plays goes out again with the new settings (a status cleared after a long pause stays cleared)
+ e.mu.Unlock()
+
+ if need&reachPlayers != 0 {
+ e.log("INFO", "Settings changed. Looking for a player on "+lookingOn(cfg)+".")
+ }
+ if drop != nil {
+ e.log("INFO", "Settings changed. Connecting to Discord again.")
+ Go(e.log, "Closing the old Discord connection", func() { closeDiscord(e.log, drop, true) })
+ }
+ e.Wake()
+}
+
+// closeDiscord clears the status on c (when clear is set) and closes the connection, waiting at most 1.5 s for each:
+// closing a pipe that is stuck in a write (Discord stopped reading) can block in Windows until the write ends, and
+// stopping, quitting or a settings change must not wait for that.
+func closeDiscord(log func(level, msg string), c *discord.Client, clear bool) {
+ if clear {
+ done := make(chan struct{})
+ go func() { _ = c.ClearActivity(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(1500 * time.Millisecond):
+ }
+ }
+ closed := make(chan struct{})
+ go func() { c.Close(); close(closed) }()
+ select {
+ case <-closed:
+ case <-time.After(1500 * time.Millisecond):
+ log("WARN", "Discord did not let go of the connection; leaving it behind.")
+ }
+}
diff --git a/internal/engine/apply_test.go b/internal/engine/apply_test.go
new file mode 100644
index 0000000..f4e4592
--- /dev/null
+++ b/internal/engine/apply_test.go
@@ -0,0 +1,146 @@
+package engine
+
+import (
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+func (d *disc) handshakes() []string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return append([]string(nil), d.hellos...)
+}
+
+// A change that touches no player or Discord setting leaves the connection to Discord open: the status goes out again
+// on the same connection, and is never cleared in between. That holds for every reach but Discord's: the look, the
+// lookups, the players, a secret, a test hook and a name for the window.
+func TestSettingsChangeKeepsTheDiscordConnection(t *testing.T) {
+ t.Parallel()
+ e, _, d, l := setup(t)
+ e.Start()
+ eventually(t, "shown", func() bool { return len(d.showing()) == 1 && e.Status().NowPlaying != nil })
+ changes := []struct {
+ name string
+ f func(*core.Config)
+ }{
+ {"the look (check)", func(c *core.Config) { c.ActivityType = "playing" }},
+ {"the lookups", func(c *core.Config) { c.ArtworkWaitMs++ }},
+ {"a test hook (lookups)", func(c *core.Config) { c.CinemetaBase = "http://127.0.0.1:9" }},
+ {"the players", func(c *core.Config) { c.MpvPipe = "" }},
+ {"a secret (players)", func(c *core.Config) { c.JellyfinToken = "sample" }}, // no server address: nothing is asked
+ {"a name for the window (none)", func(c *core.Config) { c.PlexUser = "Sample User" }},
+ }
+ for _, ch := range changes {
+ n := len(d.list())
+ cfg := e.Config()
+ ch.f(&cfg)
+ e.ApplySettings(cfg)
+ if ch.name != "a name for the window (none)" {
+ eventually(t, "sent again after "+ch.name, func() bool { return len(d.list()) > n && len(d.showing()) == 1 })
+ } else {
+ time.Sleep(10 * testPoll)
+ if len(d.list()) != n {
+ t.Errorf("%s sent %d requests to Discord", ch.name, len(d.list())-n)
+ }
+ }
+ for _, a := range d.list()[n:] {
+ if _, has := a["activity"]; !has {
+ t.Errorf("%s cleared the status", ch.name)
+ }
+ }
+ if h := d.handshakes(); len(h) != 1 {
+ t.Fatalf("%s connected to Discord again: %v", ch.name, h)
+ }
+ }
+ if l.count("Connected to Discord") != 1 || l.has("Stopped sending the status to Discord") {
+ t.Errorf("the run was restarted:\n%s", strings.Join(l.list(), "\n"))
+ }
+ if !l.has("Settings changed. Looking for a player on the web interface") {
+ t.Errorf("a change of the players is not in the log:\n%s", strings.Join(l.list(), "\n"))
+ }
+}
+
+// Another Discord application (clientId) needs a new connection: the old one is let go (its status with it), and what
+// plays goes up on the new one.
+func TestClientIDChangeReconnectsToDiscord(t *testing.T) {
+ t.Parallel()
+ e, _, d, l := setup(t)
+ e.Start()
+ eventually(t, "shown", func() bool { return len(d.showing()) == 1 })
+ cfg := e.Config()
+ cfg.ClientID = "123456789012345678"
+ e.ApplySettings(cfg)
+ eventually(t, "connected with the new application", func() bool {
+ h := d.handshakes()
+ return len(h) == 2 && h[1] == cfg.ClientID && e.Status().Discord == "connected"
+ })
+ eventually(t, "the status on the new connection only", func() bool { return len(d.showing()) == 1 })
+ if h := d.handshakes(); h[0] != core.DefaultConfig().ClientID {
+ t.Errorf("the first connection used %q", h[0])
+ }
+ if l.has("Stopped sending the status to Discord") || l.has("Lost connection") {
+ t.Errorf("the reconnect was not a quiet one:\n%s", strings.Join(l.list(), "\n"))
+ }
+ time.Sleep(10 * testPoll)
+ if h := d.handshakes(); len(h) != 2 {
+ t.Errorf("connected %d times", len(h))
+ }
+}
+
+// Every setting says what a change of it reaches (core.Config's reach tag).
+func TestEverySettingHasAReach(t *testing.T) {
+ for _, f := range core.ConfigFields() {
+ if _, ok := reachNames[f.Tag.Get("reach")]; !ok {
+ t.Errorf("%s has no known reach tag (one of check, lookups, players, discord, none): %q", f.Name, f.Tag.Get("reach"))
+ }
+ }
+}
+
+// What keeps a copy of the settings, or reads them only when it starts, must be made again when they change: every
+// setting internal/artwork reads must reach "lookups" (the finder keeps its own copy), every one the player watches
+// and the Plex, Stremio, Jellyfin and Emby watchers read must reach "players", and the Discord application "discord".
+// Otherwise a change would not get there until the engine is started again.
+func TestSettingsReachWhatReadsThem(t *testing.T) {
+ reaches := map[string]string{}
+ for _, f := range core.ConfigFields() {
+ reaches[f.Name] = f.Tag.Get("reach")
+ }
+ artwork, _ := filepath.Glob(filepath.Join("..", "artwork", "*.go"))
+ want := map[string][]string{
+ "lookups": artwork,
+ "players": {"remote.go", "events.go", "players.go"},
+ "discord": {"discord.go"},
+ }
+ read := regexp.MustCompile(`\bcfg\.([A-Z]\w*)`)
+ for reach, files := range want {
+ seen := 0
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ b, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, m := range read.FindAllStringSubmatch(string(b), -1) {
+ r, field := reaches[m[1]]
+ if !field {
+ continue // a method (SourceOn reads disabledSources)
+ }
+ seen++
+ if r != reach {
+ t.Errorf("%s reads %s, whose reach is %q: it must be %s", filepath.ToSlash(name), m[1], r, reach)
+ }
+ }
+ }
+ if seen == 0 {
+ t.Errorf("found no setting read for %s", reach)
+ }
+ }
+}
diff --git a/internal/engine/disc_test.go b/internal/engine/disc_test.go
index ce65e14..53a7a67 100644
--- a/internal/engine/disc_test.go
+++ b/internal/engine/disc_test.go
@@ -5,7 +5,7 @@ import (
"path/filepath"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func TestDiscNamesItself(t *testing.T) {
diff --git a/internal/engine/discord.go b/internal/engine/discord.go
index 94139f1..aa6688c 100644
--- a/internal/engine/discord.go
+++ b/internal/engine/discord.go
@@ -5,8 +5,8 @@ import (
"fmt"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
)
func (e *Engine) connectDiscord(r *run) {
@@ -16,7 +16,7 @@ func (e *Engine) connectDiscord(r *run) {
return
}
e.connecting = true
- cfg := e.cfg
+ cfg, gen := e.cfg, e.discGen
e.mu.Unlock()
Go(e.log, "The Discord connection", func() {
@@ -24,7 +24,7 @@ func (e *Engine) connectDiscord(r *run) {
defer func() {
if !tried { // a panic while connecting (Go logs it) must not leave the flag set: nothing would connect again
e.mu.Lock()
- if e.cur == r {
+ if e.cur == r && e.discGen == gen {
e.connecting = false
}
e.mu.Unlock()
@@ -41,13 +41,14 @@ func (e *Engine) connectDiscord(r *run) {
e.mu.Lock()
// A run that ended has had its flag reset by stop; a newer run may be connecting now, so only the current run's
- // attempt clears it.
+ // attempt clears it, and only while the Discord settings are still the ones it started with (discGen).
+ current := e.cur == r && e.discGen == gen
if err != nil {
- if e.cur == r {
+ if current {
e.connecting = false
e.discRefused = errors.Is(err, discord.ErrRefused)
}
- warn := !e.warnedDisc && e.cur == r
+ warn := !e.warnedDisc && current
if warn {
e.warnedDisc = true
}
@@ -58,7 +59,7 @@ func (e *Engine) connectDiscord(r *run) {
}
return
}
- if e.cur != r {
+ if !current {
e.mu.Unlock()
client.Close()
return
diff --git a/internal/engine/engine.go b/internal/engine/engine.go
index 6698ba3..c5639c5 100644
--- a/internal/engine/engine.go
+++ b/internal/engine/engine.go
@@ -7,17 +7,16 @@ import (
"context"
"net/http"
"os"
- "reflect"
"strings"
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/artwork"
- "github.com/CptPakundo/MPCvibedRPC/internal/capture"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
- "github.com/CptPakundo/MPCvibedRPC/internal/kodi"
- "github.com/CptPakundo/MPCvibedRPC/internal/vlchttp"
+ "github.com/CptPakundo/MPRP/internal/artwork"
+ "github.com/CptPakundo/MPRP/internal/capture"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/kodi"
+ "github.com/CptPakundo/MPRP/internal/vlchttp"
)
// Options are the engine's collaborators; all of them are optional.
@@ -75,12 +74,12 @@ type Options struct {
// Status is what the settings window shows.
type Status struct {
- Running bool `json:"running"`
- Discord string `json:"discord"` // off | standby (nothing played yet) | waiting (Discord not found yet) | connected
- MPC bool `json:"mpc"` // some player answers (the name is historic; it is not only MPC)
- Player string `json:"player"` // which one: MPC-HC, MPC-BE, MPC-QT, mpv, VLC, IINA, PotPlayer, a Linux player found through MPRIS, Kodi, Plex, Jellyfin, Emby or Stremio
- NowPlaying *string `json:"nowPlaying"`
- Paused bool `json:"paused"`
+ Running bool `json:"running"`
+ Discord string `json:"discord"` // off | standby (nothing played yet) | waiting (Discord not found yet) | connected
+ PlayerAnswers bool `json:"playerAnswers"` // some player answers
+ Player string `json:"player"` // which one: MPC-HC, MPC-BE, MPC-QT, mpv, VLC, IINA, PotPlayer, a Linux player found through MPRIS, Kodi, Plex, Jellyfin, Emby or Stremio
+ NowPlaying *string `json:"nowPlaying"`
+ Paused bool `json:"paused"`
// PauseCleared is true while the status is hidden because the video stayed paused (see Config.PauseClearMinutes).
PauseCleared bool `json:"pauseCleared"`
// Hidden is true while the playing file is on the user's "don't show" list (nothing is shown or looked up).
@@ -98,6 +97,9 @@ type Status struct {
// Why is "Why this title?" for Copy diagnostics: how the title shown was read from the file and found in the
// catalogs. Never for a hidden title or a song. Not sent to the window.
Why []string `json:"-"`
+ // Match is what the window's Fix this match dialog starts from: the file's name (never its folder), what it was read
+ // as and what it matched. Never for a hidden title or a song.
+ Match *MatchInfo `json:"match,omitempty"`
}
// run is one start..stop period; a stale run can never touch the newer one's state.
@@ -134,11 +136,16 @@ type Engine struct {
vlcProblem string // why VLC's web interface did not answer (logged once; the window shows it)
remotes []remote // the Plex, Stremio and Jellyfin/Emby watchers of the run, in the order they are asked
stopRemote context.CancelFunc // ends the remotes (they stop while resting)
+ stopWatch context.CancelFunc // ends the player watch (watchPlayers); a settings change for the players starts another
+ stopShare context.CancelFunc // ends the screen-share watch (nil: none runs; it runs while streamTitle is "auto")
+ discGen uint64 // counts the Discord connections dropped for new settings: an attempt of an older one is let go
+ cfgGen uint64 // counts the settings changes that reach the engine: a check that read older ones sends nothing
resting bool // Discord is not running: nothing is asked until it is (see Options.MayRest)
wake chan struct{} // makes the loop check at once (the window opened)
nudges nudger // early checks after mpv or IINA reported a change (events.go)
nowPlaying *string
- why []string // how the title shown was read and found (Status.Why; only while nowPlaying is set)
+ why []string // how the title shown was read and found (Status.Why; only while nowPlaying is set)
+ match *MatchInfo // what the Fix this match dialog starts from (Status.Match; only while nowPlaying is set)
preview *core.Preview
paused bool
lastError *string
@@ -150,8 +157,6 @@ type Engine struct {
// pause handling: when the current pause began, and whether the status was cleared because of it
pausedSince time.Time
pauseCleared bool
- // carry is what a settings change hands from the stopped run to the next one (see ApplySettings); nil otherwise
- carry *carried
hidden bool // the playing file is on the user's "don't show" list
pauseUnit time.Duration // one "minute" of PauseClearMinutes (shortened in tests)
minPoll time.Duration // the pace (see Options.MinPoll, ReclearEvery and RecheckAfter)
@@ -254,13 +259,6 @@ func (e *Engine) client() *http.Client {
return http.DefaultClient
}
-// isCurrent reports whether r is still the active run.
-func (e *Engine) isCurrent(r *run) bool {
- e.mu.Lock()
- defer e.mu.Unlock()
- return e.cur == r
-}
-
// Start begins watching for a player (no-op when already running).
func (e *Engine) Start() {
e.stopMu.Lock()
@@ -279,32 +277,54 @@ func (e *Engine) start() {
e.cur = r
e.basicMode, e.noLinks, e.prev, e.shown, e.warnedDisc, e.player = false, false, nil, false, false, ""
e.pausedSince, e.pauseCleared, e.preview, e.hidden = time.Time{}, false, nil, false
- if c := e.carry; c != nil { // a restart for new settings (ApplySettings): before the first check can run
- e.prev, e.pausedSince, e.pauseCleared = c.prev, c.pausedSince, c.pauseCleared
- }
- e.carry = nil
e.vlcProblem, e.kodiProblem, e.discRefused = "", "", false
e.lastError, e.nowPlaying, e.why = nil, nil, nil
e.resend, e.modeKey, e.sendFails, e.retryAt, e.live, e.missed = false, "", 0, time.Time{}, false, false
e.clearStuck, e.clearedAt = false, time.Time{}
e.recheckKey, e.recheckAt, e.rechecks = "", time.Time{}, 0
cfg := e.cfg
- cfgCopy := cfg
- e.art = artwork.New(&cfgCopy, artwork.Options{
+ e.art = e.newArtwork(cfg)
+ e.remotes, e.stopRemote, e.resting = nil, nil, false // the first check starts them (unless it rests)
+ e.startPlayerWatch(r)
+ e.startShareWatch(r, cfg)
+ e.mu.Unlock()
+ e.log("INFO", "Sending the status to Discord. Looking for a player on "+lookingOn(cfg)+".")
+ go e.loop(r) // recovers from a panic in a check itself
+}
+
+// newArtwork makes the cover and title finder for the settings cfg (it keeps a copy of them).
+func (e *Engine) newArtwork(cfg core.Config) *artwork.Artwork {
+ return artwork.New(&cfg, artwork.Options{
CacheFile: e.opts.CacheFile,
Log: e.log,
Client: e.opts.HTTPClient,
OnResolved: func(*core.Art) { e.mu.Lock(); e.resend = true; e.mu.Unlock() },
})
- e.remotes, e.stopRemote, e.resting = nil, nil, false // the first check starts them (unless it rests)
- e.mu.Unlock()
- e.log("INFO", "Presence started. Looking for a player on "+lookingOn(cfg)+".")
- go e.loop(r, e.pollInterval(cfg)) // recovers from a panic in a check itself
- Go(e.log, "The player watch", func() { e.watchPlayers(r) })
- if cfg.StreamTitle == "auto" {
- // a stream that begins or ends shows at once, not at the next check
- Go(e.log, "The screen share watch", func() { e.watchSharing(r.ctx, e.Wake) })
+}
+
+// startPlayerWatch starts the player watch of run r (watchPlayers), ending the one before (e.mu held).
+func (e *Engine) startPlayerWatch(r *run) {
+ if e.stopWatch != nil {
+ e.stopWatch()
+ }
+ ctx, cancel := context.WithCancel(r.ctx)
+ e.stopWatch = cancel
+ Go(e.log, "The player watch", func() { e.watchPlayers(ctx) })
+}
+
+// startShareWatch starts the screen-share watch of run r when streamTitle is "auto", ending the one before (e.mu
+// held): a stream that begins or ends then shows at once, not at the next check.
+func (e *Engine) startShareWatch(r *run, cfg core.Config) {
+ if e.stopShare != nil {
+ e.stopShare()
+ e.stopShare = nil
+ }
+ if cfg.StreamTitle != "auto" {
+ return
}
+ ctx, cancel := context.WithCancel(r.ctx)
+ e.stopShare = cancel
+ Go(e.log, "The screen share watch", func() { e.watchSharing(ctx, e.Wake) })
}
// Stop clears the presence (waiting at most 1.5 s for Discord) and disconnects.
@@ -326,30 +346,15 @@ func (e *Engine) stop() {
e.mu.Unlock()
r.cancel()
- if c != nil && ready {
- done := make(chan struct{})
- go func() { _ = c.ClearActivity(); close(done) }()
- select {
- case <-done:
- case <-time.After(1500 * time.Millisecond):
- }
- }
if c != nil {
- // Closing a pipe that is stuck in a write (Discord stopped reading) can block in Windows until the write
- // ends; stopping, and quitting, must not wait for that.
- closed := make(chan struct{})
- go func() { c.Close(); close(closed) }()
- select {
- case <-closed:
- case <-time.After(1500 * time.Millisecond):
- e.log("WARN", "Discord did not let go of the connection; leaving it behind.")
- }
+ closeDiscord(e.log, c, ready)
}
e.mu.Lock()
e.rpc, e.ready, e.connecting, e.shown, e.prev, e.resend = nil, false, false, false, nil, false
e.nowPlaying, e.preview = nil, nil
e.pausedSince, e.pauseCleared, e.hidden, e.paused = time.Time{}, false, false, false
e.remotes, e.stopRemote, e.resting = nil, nil, false // their runs ended with the run's context
+ e.stopWatch, e.stopShare = nil, nil // so did the watches
save := e.statSnapshot(time.Now())
if save == nil {
save = e.statLast // a write another goroutine took but has not finished: wait for it, so Quit loses nothing
@@ -361,46 +366,7 @@ func (e *Engine) stop() {
e.mu.Unlock()
e.writeStats(save)
e.folders.forget()
- e.log("INFO", "Presence stopped.")
-}
-
-// ApplySettings restarts the engine with new settings if it was running. Settings that did not change (a save of
-// an app-only option such as "Start with Windows") leave it alone, so Discord is not cleared and reconnected for nothing.
-func (e *Engine) ApplySettings(cfg core.Config) {
- e.stopMu.Lock()
- defer e.stopMu.Unlock()
- e.mu.Lock()
- was := e.cur != nil
- same := reflect.DeepEqual(e.cfg, cfg)
- e.mu.Unlock()
- if same {
- return
- }
- var keep *carried
- if was {
- // What the player last reported and the pause clock go on into the new run: a settings change is not a change
- // by the player, so it must not bring back a status cleared after a long pause, nor restart the pause wait.
- e.mu.Lock()
- if e.prev != nil {
- keep = &carried{prev: e.prev, pausedSince: e.pausedSince, pauseCleared: e.pauseCleared}
- }
- e.mu.Unlock()
- e.stop()
- }
- e.mu.Lock()
- e.cfg = cfg
- e.carry = keep
- e.mu.Unlock()
- if was {
- e.start()
- }
-}
-
-// carried is the playback state a settings change keeps across the restart of the run.
-type carried struct {
- prev *core.Prev
- pausedSince time.Time
- pauseCleared bool
+ e.log("INFO", "Stopped sending the status to Discord.")
}
// ClearArtworkCache forgets every cover and title that was looked up (in memory and on disk). While presence is
@@ -437,11 +403,11 @@ func (e *Engine) Status() Status {
s.DiscordProblem = "Discord refused the connection. It is probably running as administrator: start it normally."
}
s.Paused = e.paused
- s.MPC = e.player != ""
+ s.PlayerAnswers = e.player != ""
s.Player = e.player
s.NowPlaying = e.nowPlaying
if e.nowPlaying != nil {
- s.Why = e.why
+ s.Why, s.Match = e.why, e.match
}
s.PauseCleared = e.pauseCleared
s.Hidden = e.hidden
diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go
index ecf88bd..277028b 100644
--- a/internal/engine/engine_test.go
+++ b/internal/engine/engine_test.go
@@ -16,7 +16,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
type mpc struct {
@@ -77,8 +77,10 @@ type disc struct {
rejectAll bool
// failClears answers a clearing SET_ACTIVITY (no activity) with an error, as if Discord did not take it
failClears bool
- ln fakeListener
- conns []io.ReadWriteCloser
+ // hellos are the application ids of the handshakes, one per connection made
+ hellos []string
+ ln fakeListener
+ conns []io.ReadWriteCloser
// up is what each live connection shows: the last status it took, until it is cleared or the connection ends
// (Discord drops a status with its connection)
up map[io.ReadWriteCloser]map[string]any
@@ -138,6 +140,9 @@ func (d *disc) serve(c io.ReadWriteCloser) {
var m map[string]any
json.Unmarshal(body, &m)
if op == 0 {
+ d.mu.Lock()
+ d.hellos = append(d.hellos, fmt.Sprint(m["client_id"]))
+ d.mu.Unlock()
reply(c, map[string]any{"cmd": "DISPATCH", "evt": "READY", "data": map[string]any{}})
continue
}
@@ -295,7 +300,7 @@ func TestPlayPauseClearStop(t *testing.T) {
// the activity reaches Discord a moment before the status shows what is playing
eventually(t, "now playing published", func() bool { return e.Status().NowPlaying != nil })
s := e.Status()
- if !s.Running || s.Discord != "connected" || !s.MPC || s.NowPlaying == nil || s.Paused {
+ if !s.Running || s.Discord != "connected" || !s.PlayerAnswers || s.NowPlaying == nil || s.Paused {
t.Fatalf("%+v", s)
}
if !l.has("Connected to Discord") || !l.has("MPC-HC detected") || !l.has("Playing: ") {
@@ -322,7 +327,7 @@ func TestPlayPauseClearStop(t *testing.T) {
// MPC disappears
m.set(func(m *mpc) { m.down = true })
- eventually(t, "mpc down", func() bool { return !e.Status().MPC })
+ eventually(t, "mpc down", func() bool { return !e.Status().PlayerAnswers })
// play again, then stop: presence is cleared
m.set(func(m *mpc) { m.down = false; m.state = 2 })
@@ -421,7 +426,9 @@ func TestDiscordLateAndReconnect(t *testing.T) {
eventually(t, "resent", func() bool { return len(d.list()) > n })
}
-func TestApplySettingsRestarts(t *testing.T) {
+// A settings change applies to the running engine without a restart: the status goes out again in the new form, and
+// nothing is stopped or cleared.
+func TestApplySettingsAppliesWithoutARestart(t *testing.T) {
t.Parallel()
e, _, d, l := setup(t)
e.Start()
@@ -429,12 +436,12 @@ func TestApplySettingsRestarts(t *testing.T) {
cfg := e.Config()
cfg.ActivityType = "playing"
e.ApplySettings(cfg)
- eventually(t, "restart resend", func() bool { return len(d.list()) >= 3 }) // clear + new set
+ eventually(t, "sent again", func() bool { return len(d.list()) >= 2 })
last := d.list()[len(d.list())-1]["activity"].(map[string]any)
if last["type"] != nil && last["type"] != float64(0) {
t.Fatalf("playing mode must not be type 3: %v", last)
}
- if !l.has("Presence stopped") {
+ if l.has("Stopped sending the status to Discord") || isClear(d) {
t.Fatal(l.l)
}
// a stopped engine stays stopped after ApplySettings
@@ -732,7 +739,7 @@ func TestDontShowListHidesAndLooksNothingUp(t *testing.T) {
// the fake player is playing C:\TV\Show Name\Season 1\Show.Name.S01E01.720p.mkv
e, m, d, l, lc := privacySetup(t, func(c *core.Config) { c.HideFiles = []string{"tv/show name"} })
e.Start()
- eventually(t, "MPC-HC detected", func() bool { return e.Status().MPC })
+ eventually(t, "MPC-HC detected", func() bool { return e.Status().PlayerAnswers })
time.Sleep(1200 * time.Millisecond) // several polls
if len(d.list()) != 0 {
t.Fatalf("a listed file must show nothing, but %d message(s) were sent: %v", len(d.list()), d.list())
diff --git a/internal/engine/events.go b/internal/engine/events.go
index 970e22e..ab34993 100644
--- a/internal/engine/events.go
+++ b/internal/engine/events.go
@@ -7,13 +7,13 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/conns"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/kodi"
- "github.com/CptPakundo/MPCvibedRPC/internal/mpris"
- "github.com/CptPakundo/MPCvibedRPC/internal/mpvipc"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/conns"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/kodi"
+ "github.com/CptPakundo/MPRP/internal/mpris"
+ "github.com/CptPakundo/MPRP/internal/mpvipc"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
var (
@@ -134,7 +134,7 @@ func (e *Engine) kodiEvents(cfg core.Config) string {
// watchPlayers keeps a connection open to each player that reports its changes, so that a pause, a seek or a new
// file shows at once instead of at the next check. What plays is still read by the checks; a player that is not
// there is looked for again every watchRetry, and none is while the engine rests.
-func (e *Engine) watchPlayers(r *run) {
+func (e *Engine) watchPlayers(ctx context.Context) {
var mu sync.Mutex
watching := map[string]bool{}
t := time.NewTicker(watchRetry)
@@ -159,20 +159,20 @@ func (e *Engine) watchPlayers(r *run) {
delete(watching, s.key)
mu.Unlock()
}()
- if r.ctx.Err() != nil {
+ if ctx.Err() != nil {
return
}
c, watch := s.open()
if c == nil {
return
}
- stop := context.AfterFunc(r.ctx, func() { c.Close() })
+ stop := context.AfterFunc(ctx, func() { c.Close() })
defer stop()
_ = watch()
})
}
select {
- case <-r.ctx.Done():
+ case <-ctx.Done():
return
case <-t.C:
}
diff --git a/internal/engine/events_test.go b/internal/engine/events_test.go
index f30b0e2..5f96d7b 100644
--- a/internal/engine/events_test.go
+++ b/internal/engine/events_test.go
@@ -14,9 +14,9 @@ import (
"testing/synctest"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
)
// With mpv's events, a pause shows at once although the next regular check is a minute away.
diff --git a/internal/engine/fakepipe_windows_test.go b/internal/engine/fakepipe_windows_test.go
index c5c1c82..d01f2e4 100644
--- a/internal/engine/fakepipe_windows_test.go
+++ b/internal/engine/fakepipe_windows_test.go
@@ -42,7 +42,7 @@ func fakePath(string) string {
pipeCounterMu.Lock()
defer pipeCounterMu.Unlock()
pipeCounter++
- return fmt.Sprintf(`\\.\pipe\mpcvibedrpc-test-%d-%d`, os.Getpid(), pipeCounter)
+ return fmt.Sprintf(`\\.\pipe\mprp-test-%d-%d`, os.Getpid(), pipeCounter)
}
type pipeListener struct {
diff --git a/internal/engine/fixes.go b/internal/engine/fixes.go
new file mode 100644
index 0000000..bc0331a
--- /dev/null
+++ b/internal/engine/fixes.go
@@ -0,0 +1,31 @@
+package engine
+
+import "github.com/CptPakundo/MPRP/internal/artwork"
+
+// matchFinder is the cover and title finder the window's Fix this match dialog searches with: the running one (its
+// request gaps and caches are shared with the lookups), else one made for the current settings, with no cache file.
+func (e *Engine) matchFinder() *artwork.Artwork {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.cur != nil && e.art != nil {
+ return e.art
+ }
+ cfg := e.cfg
+ return artwork.New(&cfg, artwork.Options{Log: e.log, Client: e.opts.HTTPClient})
+}
+
+// MatchSearch is the Fix this match dialog's search (artwork.Suggest), with the names of the catalogs it asks (none:
+// every catalog is off under Privacy, or lookups are off).
+func (e *Engine) MatchSearch(query string) (list []artwork.Suggestion, catalogs []string, err error) {
+ f := e.matchFinder()
+ for _, p := range f.SuggestCatalogs() {
+ catalogs = append(catalogs, p.Label)
+ }
+ list, err = f.Suggest(query)
+ return list, catalogs, err
+}
+
+// MatchCovers are the other catalogs' covers of a title pinned in the dialog (artwork.Covers).
+func (e *Engine) MatchCovers(name string, year int, kind, except string) []artwork.Cover {
+ return e.matchFinder().Covers(name, year, kind, except)
+}
diff --git a/internal/engine/fixes_test.go b/internal/engine/fixes_test.go
new file mode 100644
index 0000000..48c34e0
--- /dev/null
+++ b/internal/engine/fixes_test.go
@@ -0,0 +1,49 @@
+package engine
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/artwork"
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// What the Fix this match dialog starts from names the file but never its folder; a fix's offset moves the numbers
+// the card shows and the catalogs are asked; a fix for the file wins over one for its title.
+func TestBuildWithAFix(t *testing.T) {
+ cfg := core.DefaultConfig()
+ cfg.ArtworkSources, cfg.EpisodeSources, cfg.EpisodeTitles = []string{}, []string{}, false // nothing is asked online
+ cfg.MatchFixes = []core.MatchFix{
+ {Match: "Sample Show", Cover: "https://img.example/show.jpg", EpisodeOffset: 12},
+ {Match: "Sample.Show.S01E03.mkv", File: true, Cover: "https://img.example/three.jpg"},
+ }
+ art := artwork.New(&cfg, artwork.Options{})
+ info := &core.Info{File: "Sample.Show.S01E02.mkv", Dir: []string{"Season 1"}, FullDir: "/videos/private/Season 1", State: 2, Duration: 1500000, Rate: 1, Player: "MPC-HC"}
+ b := buildActivity(info, &cfg, art, nil, time.Now())
+ if b.match == nil || b.match.File != "Sample.Show.S01E02.mkv" || b.match.Title != "Sample Show" || b.match.Season != 1 || b.match.Episode != 2 || !b.match.Fixed || b.match.Now != "your image" {
+ t.Fatalf("match: %+v", b.match)
+ }
+ if b.activity.Assets == nil || b.activity.Assets.LargeText != "Season 1, Episode 14" || b.activity.Assets.LargeImage != "https://img.example/show.jpg" {
+ t.Errorf("the offset should move the badge: %+v", b.activity.Assets)
+ }
+ if why := strings.Join(b.why, "\n"); !strings.Contains(why, "looked up as S01E14") || strings.Contains(why, "private") {
+ t.Errorf("why:\n%s", why)
+ }
+
+ info.File = "Sample.Show.S01E03.mkv"
+ b = buildActivity(info, &cfg, art, nil, time.Now())
+ if b.activity.Assets.LargeImage != "https://img.example/three.jpg" || b.activity.Assets.LargeText != "Season 1, Episode 3" {
+ t.Errorf("the file fix should win (and has no offset): %+v", b.activity.Assets)
+ }
+
+ info.File = "sample song.mp3"
+ if b = buildActivity(info, &cfg, art, nil, time.Now()); b.match != nil {
+ t.Errorf("a song has nothing to fix: %+v", b.match)
+ }
+ cfg.HideTitle = true
+ info.File = "Sample.Show.S01E02.mkv"
+ if b = buildActivity(info, &cfg, art, nil, time.Now()); b.match != nil {
+ t.Errorf("a hidden title has nothing to fix: %+v", b.match)
+ }
+}
diff --git a/internal/engine/folder_test.go b/internal/engine/folder_test.go
index ea52844..87760f1 100644
--- a/internal/engine/folder_test.go
+++ b/internal/engine/folder_test.go
@@ -7,7 +7,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// seasonFolder makes a folder of episodes named with a running production code, from..to.
diff --git a/internal/engine/jellyfin_test.go b/internal/engine/jellyfin_test.go
index d1cd32a..b3b5f21 100644
--- a/internal/engine/jellyfin_test.go
+++ b/internal/engine/jellyfin_test.go
@@ -9,7 +9,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakeJellyfin is a Jellyfin (or Emby) server whose session list shows the user's episode, shaped like Jellyfin's
diff --git a/internal/engine/kodi_test.go b/internal/engine/kodi_test.go
index 68cde12..d1e99ff 100644
--- a/internal/engine/kodi_test.go
+++ b/internal/engine/kodi_test.go
@@ -9,7 +9,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// newFakeKodi is Kodi's JSON-RPC web server playing a library episode (user kodi, password secret).
diff --git a/internal/engine/links_test.go b/internal/engine/links_test.go
index c4dd408..275b556 100644
--- a/internal/engine/links_test.go
+++ b/internal/engine/links_test.go
@@ -7,7 +7,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// linkSetup plays a movie that a fake Cinemeta knows, so the activity has a cover and a catalog page.
diff --git a/internal/engine/live_test.go b/internal/engine/live_test.go
index 372e6e6..6c8eedd 100644
--- a/internal/engine/live_test.go
+++ b/internal/engine/live_test.go
@@ -10,70 +10,70 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/jellyfin"
- "github.com/CptPakundo/MPCvibedRPC/internal/kodi"
- "github.com/CptPakundo/MPCvibedRPC/internal/mpris"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/jellyfin"
+ "github.com/CptPakundo/MPRP/internal/kodi"
+ "github.com/CptPakundo/MPRP/internal/mpris"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
// TestLivePlayer runs against a real player on this computer (MPC-QT, mpv, VLC, IINA or a Linux player that offers
// MPRIS, set up as their docs say) and the test's own fake Discord. It only runs on request:
//
-// MPCRPC_LIVE_PLAYER=mpv MPCRPC_LIVE_TITLE="Sample Movie" go test -run TestLivePlayer ./internal/engine
+// MPRP_LIVE_PLAYER=mpv MPRP_LIVE_TITLE="Sample Movie" go test -run TestLivePlayer ./internal/engine
//
-// MPCRPC_LIVE_PORT optionally names a web-interface port to ask first (default: none). For VLC, set
-// MPCRPC_LIVE_VLC_PASSWORD (and MPCRPC_LIVE_VLC_PORT when it is not 8080). MPCRPC_LIVE_MPV_PIPE and
-// MPCRPC_LIVE_IINA_PIPE replace the default connection names of mpv and IINA. For Plex, MPCRPC_LIVE_PLEX_ADDRESS is the
-// server (followed without plex.tv; MPCRPC_LIVE_PLEX_TOKEN is its token, if it needs one). For Jellyfin or
-// Emby, MPCRPC_LIVE_JELLYFIN_ADDRESS, MPCRPC_LIVE_JELLYFIN_USER and MPCRPC_LIVE_JELLYFIN_PASSWORD sign in to the server. For Kodi, MPCRPC_LIVE_KODI_PASSWORD
-// (and MPCRPC_LIVE_KODI_ADDRESS when it is not 127.0.0.1:8080; the user is kodi). PotPlayer needs nothing. MPCRPC_LIVE_PLAYER is the
+// MPRP_LIVE_PORT optionally names a web-interface port to ask first (default: none). For VLC, set
+// MPRP_LIVE_VLC_PASSWORD (and MPRP_LIVE_VLC_PORT when it is not 8080). MPRP_LIVE_MPV_PIPE and
+// MPRP_LIVE_IINA_PIPE replace the default connection names of mpv and IINA. For Plex, MPRP_LIVE_PLEX_ADDRESS is the
+// server (followed without plex.tv; MPRP_LIVE_PLEX_TOKEN is its token, if it needs one). For Jellyfin or
+// Emby, MPRP_LIVE_JELLYFIN_ADDRESS, MPRP_LIVE_JELLYFIN_USER and MPRP_LIVE_JELLYFIN_PASSWORD sign in to the server. For Kodi, MPRP_LIVE_KODI_PASSWORD
+// (and MPRP_LIVE_KODI_ADDRESS when it is not 127.0.0.1:8080; the user is kodi). PotPlayer needs nothing. MPRP_LIVE_PLAYER is the
// name the player is shown under: MPC-QT, mpv, VLC, IINA, PotPlayer, Kodi, Celluloid, Plex, ...
func TestLivePlayer(t *testing.T) {
- want := os.Getenv("MPCRPC_LIVE_PLAYER")
+ want := os.Getenv("MPRP_LIVE_PLAYER")
if want == "" {
- t.Skip("set MPCRPC_LIVE_PLAYER to run against a real player")
+ t.Skip("set MPRP_LIVE_PLAYER to run against a real player")
}
port := deadPort(t)
- if p := os.Getenv("MPCRPC_LIVE_PORT"); p != "" {
+ if p := os.Getenv("MPRP_LIVE_PORT"); p != "" {
port = atoiOr(p, port)
}
e, d, l := pipeEngine(t, port, nil)
e.opts.Pipes, e.opts.MPRIS, e.opts.PotPlayer, e.opts.KodiEvents = nil, nil, nil, "" // the real ones: MPC-QT's, mpv's, IINA's (macOS), MPRIS (Linux), PotPlayer (Windows)
- if p := os.Getenv("MPCRPC_LIVE_MPV_PIPE"); p != "" {
+ if p := os.Getenv("MPRP_LIVE_MPV_PIPE"); p != "" {
e.cfg.MpvPipe = p
}
- if p := os.Getenv("MPCRPC_LIVE_IINA_PIPE"); p != "" {
+ if p := os.Getenv("MPRP_LIVE_IINA_PIPE"); p != "" {
e.cfg.IinaPipe = p
}
- if a := os.Getenv("MPCRPC_LIVE_PLEX_ADDRESS"); a != "" {
- e.cfg.PlexAddress, e.cfg.PlexToken = a, os.Getenv("MPCRPC_LIVE_PLEX_TOKEN")
+ if a := os.Getenv("MPRP_LIVE_PLEX_ADDRESS"); a != "" {
+ e.cfg.PlexAddress, e.cfg.PlexToken = a, os.Getenv("MPRP_LIVE_PLEX_TOKEN")
if e.cfg.PlexToken == "" {
e.cfg.PlexToken = "none" // a server that lets this computer in without signing in ignores it
}
}
- if a := os.Getenv("MPCRPC_LIVE_JELLYFIN_ADDRESS"); a != "" {
+ if a := os.Getenv("MPRP_LIVE_JELLYFIN_ADDRESS"); a != "" {
c := &jellyfin.Client{Base: a, DeviceID: "ci-engine", Version: "0.0.0"}
srv, err := c.Find(context.Background())
if err != nil {
t.Fatal(err)
}
- auth, err := c.SignIn(context.Background(), os.Getenv("MPCRPC_LIVE_JELLYFIN_USER"), os.Getenv("MPCRPC_LIVE_JELLYFIN_PASSWORD"))
+ auth, err := c.SignIn(context.Background(), os.Getenv("MPRP_LIVE_JELLYFIN_USER"), os.Getenv("MPRP_LIVE_JELLYFIN_PASSWORD"))
if err != nil {
t.Fatal(err)
}
e.cfg.JellyfinAddress, e.cfg.JellyfinToken, e.cfg.JellyfinUser, e.cfg.JellyfinProduct, e.cfg.JellyfinDevice = c.Base, auth.Token, auth.UserID, srv.Product, c.DeviceID
}
- if pw := os.Getenv("MPCRPC_LIVE_KODI_PASSWORD"); pw != "" {
+ if pw := os.Getenv("MPRP_LIVE_KODI_PASSWORD"); pw != "" {
e.cfg.KodiPassword = pw
- if a := os.Getenv("MPCRPC_LIVE_KODI_ADDRESS"); a != "" {
+ if a := os.Getenv("MPRP_LIVE_KODI_ADDRESS"); a != "" {
e.cfg.KodiAddress = a
}
}
- if pw := os.Getenv("MPCRPC_LIVE_VLC_PASSWORD"); pw != "" {
+ if pw := os.Getenv("MPRP_LIVE_VLC_PASSWORD"); pw != "" {
e.cfg.VlcPassword = pw
- if p := os.Getenv("MPCRPC_LIVE_VLC_PORT"); p != "" {
+ if p := os.Getenv("MPRP_LIVE_VLC_PORT"); p != "" {
e.cfg.VlcPort = atoiOr(p, e.cfg.VlcPort)
}
}
@@ -85,7 +85,7 @@ func TestLivePlayer(t *testing.T) {
act := d.list()[len(d.list())-1]["activity"].(map[string]any)
t.Logf("status: player=%s playing=%v paused=%v", s.Player, *s.NowPlaying, s.Paused)
t.Logf("activity: %v", act)
- if title := os.Getenv("MPCRPC_LIVE_TITLE"); title != "" && !strings.Contains(*s.NowPlaying, title) {
+ if title := os.Getenv("MPRP_LIVE_TITLE"); title != "" && !strings.Contains(*s.NowPlaying, title) {
t.Errorf("expected %q in %q", title, *s.NowPlaying)
}
if !l.has(want + " detected.") {
@@ -101,15 +101,15 @@ func TestLivePlayer(t *testing.T) {
if !l.has(`(` + want + `: "`) {
t.Error("the log should name what the player played")
}
- if how := os.Getenv("MPCRPC_LIVE_EVENTS"); how != "" {
+ if how := os.Getenv("MPRP_LIVE_EVENTS"); how != "" {
livePauseEvent(t, e, d, want, how)
}
}
// livePauseEvent pauses the real player and wants the pause shown at once, from the player's own event, while the
// regular checks are a minute apart. how says how the player is paused: "pipe" (mpv, IINA: their IPC), "kodi" (its
-// JSON-RPC, as user kodi with MPCRPC_LIVE_KODI_PASSWORD) or "mpris" (D-Bus). It changes the player's state, so it is
-// opt-in (MPCRPC_LIVE_EVENTS; CI sets it for its throwaway players), and it resumes the player afterwards.
+// JSON-RPC, as user kodi with MPRP_LIVE_KODI_PASSWORD) or "mpris" (D-Bus). It changes the player's state, so it is
+// opt-in (MPRP_LIVE_EVENTS; CI sets it for its throwaway players), and it resumes the player afterwards.
func livePauseEvent(t *testing.T, e *Engine, d *disc, name, how string) {
e.Stop()
e.cfg.PollInterval = 60000
@@ -123,6 +123,16 @@ func livePauseEvent(t *testing.T, e *Engine, d *disc, name, how string) {
}
time.Sleep(time.Second) // the event connection is made at the start
set := livePauser(t, e.cfg, name, how)
+ // the pause must be the player's own change: a player that opened paused (IINA did once) is played first, and
+ // that may only show at the next regular check
+ if e.Status().Paused {
+ set(false)
+ for until := time.Now().Add(70 * time.Second); e.Status().Paused; time.Sleep(50 * time.Millisecond) {
+ if time.Now().After(until) {
+ t.Fatal("timed out waiting for: playing before the pause")
+ }
+ }
+ }
n := len(d.list())
start := time.Now()
set(true)
@@ -212,6 +222,6 @@ func livePauser(t *testing.T, cfg core.Config, name, how string) func(paused boo
t.Fatalf("%s is not on the bus", name)
}
}
- t.Fatalf("MPCRPC_LIVE_EVENTS=%q: want pipe, kodi or mpris", how)
+ t.Fatalf("MPRP_LIVE_EVENTS=%q: want pipe, kodi or mpris", how)
return nil
}
diff --git a/internal/engine/multios_test.go b/internal/engine/multios_test.go
index f7574d5..d5e1998 100644
--- a/internal/engine/multios_test.go
+++ b/internal/engine/multios_test.go
@@ -6,8 +6,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
func largeText(d *disc) any {
diff --git a/internal/engine/pace_test.go b/internal/engine/pace_test.go
index 09a91f8..899b96e 100644
--- a/internal/engine/pace_test.go
+++ b/internal/engine/pace_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// A Discord that refuses every status is not asked at every check: the engine waits longer after each failure, names
@@ -19,7 +19,7 @@ func TestFailedSendsArePaced(t *testing.T) {
l.mu.Lock()
defer l.mu.Unlock()
for _, s := range l.l {
- if strings.Contains(s, "Failed to update presence") {
+ if strings.Contains(s, "Failed to update the status") {
n++
}
}
diff --git a/internal/engine/players.go b/internal/engine/players.go
index 927e3ae..649aeea 100644
--- a/internal/engine/players.go
+++ b/internal/engine/players.go
@@ -11,14 +11,14 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/kodi"
- "github.com/CptPakundo/MPCvibedRPC/internal/mpris"
- "github.com/CptPakundo/MPCvibedRPC/internal/mpvipc"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
- "github.com/CptPakundo/MPCvibedRPC/internal/potplayer"
- "github.com/CptPakundo/MPCvibedRPC/internal/vlchttp"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/kodi"
+ "github.com/CptPakundo/MPRP/internal/mpris"
+ "github.com/CptPakundo/MPRP/internal/mpvipc"
+ "github.com/CptPakundo/MPRP/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/potplayer"
+ "github.com/CptPakundo/MPRP/internal/vlchttp"
)
// PlayerPipe is an mpv-style IPC endpoint and the name of the player behind it.
diff --git a/internal/engine/players_test.go b/internal/engine/players_test.go
index 63180f4..5816e0e 100644
--- a/internal/engine/players_test.go
+++ b/internal/engine/players_test.go
@@ -114,15 +114,25 @@ func (f *fakeMpv) serve(c io.ReadWriteCloser) {
}
}
-// deadPort is a local port nothing listens on, so the web interface counts as off.
+// deadPort is a local port where no web interface answers, so it counts as off. The test holds the port for its whole
+// run and hangs up on every connection: a port that was only looked up and freed could be handed to a parallel test's
+// fake MPC-HC, whose video would then show up here.
func deadPort(t *testing.T) int {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
- port := ln.Addr().(*net.TCPAddr).Port
- ln.Close()
- return port
+ t.Cleanup(func() { ln.Close() })
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ return ln.Addr().(*net.TCPAddr).Port
}
func pipeEngine(t *testing.T, port int, pipes []PlayerPipe) (*Engine, *disc, *logs) {
@@ -149,7 +159,7 @@ func TestMpvOverItsPipe(t *testing.T) {
})
e, d, l := pipeEngine(t, deadPort(t), []PlayerPipe{{"mpv", m.path}})
e.Start()
- eventually(t, "mpv shown", func() bool { s := e.Status(); return s.NowPlaying != nil && s.Player == "mpv" && s.MPC })
+ eventually(t, "mpv shown", func() bool { s := e.Status(); return s.NowPlaying != nil && s.Player == "mpv" && s.PlayerAnswers })
if !l.has("mpv detected.") {
t.Error("the log should name mpv")
}
@@ -164,7 +174,7 @@ func TestMpvOverItsPipe(t *testing.T) {
m.set("idle-active", true)
eventually(t, "cleared when mpv goes idle", func() bool { return isClear(d) && e.Status().NowPlaying == nil })
- if !e.Status().MPC {
+ if !e.Status().PlayerAnswers {
t.Error("an idle mpv is still a reachable player")
}
}
@@ -240,7 +250,7 @@ func TestMissingPipesMeanNoPlayer(t *testing.T) {
e, _, l := pipeEngine(t, deadPort(t), []PlayerPipe{{"MPC-QT", fakePath(sockDir(t)) + "-none"}})
e.Start()
time.Sleep(700 * time.Millisecond)
- if s := e.Status(); s.MPC || s.Player != "" || s.NowPlaying != nil {
+ if s := e.Status(); s.PlayerAnswers || s.Player != "" || s.NowPlaying != nil {
t.Errorf("nothing listens, yet %+v", s)
}
if l.has("detected") {
diff --git a/internal/engine/plex_test.go b/internal/engine/plex_test.go
index a02d09e..e81551f 100644
--- a/internal/engine/plex_test.go
+++ b/internal/engine/plex_test.go
@@ -8,7 +8,7 @@ import (
"sync"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakePlex is plex.tv (the account's one server) and that Plex Media Server, in one test server. The answers are
@@ -91,7 +91,7 @@ func TestPlexPlayback(t *testing.T) {
p := newFakePlex(t)
e, d, l := plexEngine(t, deadPort(t), p)
e.Start()
- eventually(t, "Plex followed", func() bool { s := e.Status(); return s.Player == "Plex" && s.MPC })
+ eventually(t, "Plex followed", func() bool { s := e.Status(); return s.Player == "Plex" && s.PlayerAnswers })
if !l.has("your Plex server") || !l.has("Following the Plex server \"Sample Server\".") {
t.Error("the log should say Plex is followed")
}
@@ -128,9 +128,9 @@ func TestPlexNotAskedWithoutSignIn(t *testing.T) {
e, _, l := plexEngine(t, deadPort(t), p)
e.cfg.PlexToken = ""
e.Start()
- eventually(t, "a few ticks", func() bool { return l.has("Presence started.") })
+ eventually(t, "a few ticks", func() bool { return l.has("Sending the status to Discord.") })
for i := 0; i < 3; i++ {
- eventually(t, "no player", func() bool { return !e.Status().MPC })
+ eventually(t, "no player", func() bool { return !e.Status().PlayerAnswers })
}
if p.count() != 0 || l.has("Plex") {
t.Errorf("Plex was asked without a sign-in (%d requests)", p.count())
@@ -159,3 +159,25 @@ func TestPlexProblemShownAndStoppedWithPresence(t *testing.T) {
e.Stop()
eventually(t, "stream closed", func() bool { return e.Status().Player == "" })
}
+
+// A sign-in made while presence runs (a secret that changes) starts following Plex without a restart, and a sign-out
+// stops it.
+func TestPlexSignInWhileRunning(t *testing.T) {
+ t.Parallel()
+ p := newFakePlex(t)
+ e, _, l := plexEngine(t, deadPort(t), p)
+ token := e.cfg.PlexToken
+ e.cfg.PlexToken = ""
+ e.Start()
+ eventually(t, "started", func() bool { return l.has("Sending the status to Discord.") })
+ cfg := e.Config()
+ cfg.PlexToken = token
+ e.ApplySettings(cfg)
+ eventually(t, "Plex followed", func() bool { s := e.Status(); return s.Player == "Plex" && s.PlayerAnswers })
+ cfg.PlexToken = ""
+ e.ApplySettings(cfg)
+ eventually(t, "Plex no longer followed", func() bool { return !e.Status().PlayerAnswers })
+ if l.has("Stopped sending the status to Discord") {
+ t.Error("a sign-in restarted the engine")
+ }
+}
diff --git a/internal/engine/potplayer_test.go b/internal/engine/potplayer_test.go
index 92e42ca..14f1f6e 100644
--- a/internal/engine/potplayer_test.go
+++ b/internal/engine/potplayer_test.go
@@ -4,7 +4,7 @@ import (
"sync"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// fakePot stands in for the PotPlayer windows on this computer.
diff --git a/internal/engine/probe.go b/internal/engine/probe.go
index a5f80bb..454fe01 100644
--- a/internal/engine/probe.go
+++ b/internal/engine/probe.go
@@ -8,10 +8,10 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/kodi"
- "github.com/CptPakundo/MPCvibedRPC/internal/potplayer"
- "github.com/CptPakundo/MPCvibedRPC/internal/vlchttp"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/kodi"
+ "github.com/CptPakundo/MPRP/internal/potplayer"
+ "github.com/CptPakundo/MPRP/internal/vlchttp"
)
// Probe states of a player that answers.
diff --git a/internal/engine/probe_test.go b/internal/engine/probe_test.go
index 9e29706..570b05d 100644
--- a/internal/engine/probe_test.go
+++ b/internal/engine/probe_test.go
@@ -6,7 +6,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func probeNamed(ps []PlayerProbe, part string) *PlayerProbe {
diff --git a/internal/engine/remote.go b/internal/engine/remote.go
index 43c6e74..6b16cc1 100644
--- a/internal/engine/remote.go
+++ b/internal/engine/remote.go
@@ -4,12 +4,12 @@ import (
"context"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
- "github.com/CptPakundo/MPCvibedRPC/internal/jellyfin"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
- "github.com/CptPakundo/MPCvibedRPC/internal/plex"
- "github.com/CptPakundo/MPCvibedRPC/internal/stremio"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/jellyfin"
+ "github.com/CptPakundo/MPRP/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/plex"
+ "github.com/CptPakundo/MPRP/internal/stremio"
)
// watcher follows one account or server for what is playing on it (Plex, Stremio, Jellyfin or Emby).
diff --git a/internal/engine/remotes_test.go b/internal/engine/remotes_test.go
index 2866805..0d957a1 100644
--- a/internal/engine/remotes_test.go
+++ b/internal/engine/remotes_test.go
@@ -6,7 +6,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// remoteRig is an engine that follows one remote (Plex, Stremio, Jellyfin or Emby) whose fake shows "Sample Show".
diff --git a/internal/engine/rest_test.go b/internal/engine/rest_test.go
index 66c1ff9..e6f8787 100644
--- a/internal/engine/rest_test.go
+++ b/internal/engine/rest_test.go
@@ -13,7 +13,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func (m *mpc) count() int { m.mu.Lock(); defer m.mu.Unlock(); return m.asked }
@@ -48,14 +48,14 @@ func TestRestWhileDiscordIsClosed(t *testing.T) {
// the window opens: the player is asked at once (Wake), with Discord still closed
mayRest.Store(false)
e.Wake()
- eventually(t, "the player asked with the window open", func() bool { return m.count() > 0 && e.Status().MPC })
+ eventually(t, "the player asked with the window open", func() bool { return m.count() > 0 && e.Status().PlayerAnswers })
if s := e.Status(); s.Resting || !l.has("Resting ended") {
t.Fatalf("still resting with the window open: %+v", s)
}
// the window closes again
mayRest.Store(true)
eventually(t, "resting again", func() bool { return e.Status().Resting })
- if s := e.Status(); s.MPC || s.Player != "" {
+ if s := e.Status(); s.PlayerAnswers || s.Player != "" {
t.Fatalf("a resting status still names a player: %+v", s)
}
diff --git a/internal/engine/sharing_test.go b/internal/engine/sharing_test.go
index 1f05c9e..e574250 100644
--- a/internal/engine/sharing_test.go
+++ b/internal/engine/sharing_test.go
@@ -5,7 +5,7 @@ import (
"sync/atomic"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// No test reads this computer's record of Discord's screen capture: a test that wants a stream sets Options.Sharing.
diff --git a/internal/engine/stale_test.go b/internal/engine/stale_test.go
index a863c53..b9ea0b0 100644
--- a/internal/engine/stale_test.go
+++ b/internal/engine/stale_test.go
@@ -4,8 +4,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
)
// clears counts the SET_ACTIVITY calls without an activity (a cleared status) from the n-th call on.
@@ -58,7 +58,7 @@ func TestFailedClearIsRetried(t *testing.T) {
d.mu.Lock()
d.failClears = false
d.mu.Unlock()
- eventually(t, "cleared", func() bool { return l.has("Nothing playing - presence cleared.") })
+ eventually(t, "cleared", func() bool { return l.has("Nothing playing - status cleared.") })
k := len(d.list())
time.Sleep(600 * time.Millisecond) // more checks: no clear storm once one worked
if extra := clears(d, k); extra > 0 {
@@ -80,7 +80,7 @@ func TestNothingPlayingIsClearedAgainNowAndThen(t *testing.T) {
cleared := 0
l.mu.Lock()
for _, s := range l.l {
- if s == "INFO Nothing playing - presence cleared." {
+ if s == "INFO Nothing playing - status cleared." {
cleared++
}
}
@@ -101,7 +101,7 @@ func TestPausedAtTheEndClears(t *testing.T) {
m.set(func(m *mpc) { m.state, m.pos = 1, m.dur-1000 })
eventually(t, "cleared", func() bool { return clears(d, n) >= 1 })
// Discord gets the clear a moment before the log and the status say so
- eventually(t, "logged as ended", func() bool { return l.has("The video ended - presence cleared.") && e.Status().NowPlaying == nil })
+ eventually(t, "logged as ended", func() bool { return l.has("The video ended - status cleared.") && e.Status().NowPlaying == nil })
m.set(func(m *mpc) { m.state, m.pos = 2, 60000 }) // played again from earlier on: shown again
eventually(t, "shown again", func() bool { return e.Status().NowPlaying != nil })
}
diff --git a/internal/engine/state_test.go b/internal/engine/state_test.go
index c4227c1..ff3d6fc 100644
--- a/internal/engine/state_test.go
+++ b/internal/engine/state_test.go
@@ -10,8 +10,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
)
// count is how many log lines contain sub.
@@ -165,41 +165,55 @@ func TestConnectingSurvivesAPanic(t *testing.T) {
eventually(t, "connected at a later check", func() bool { return e.Status().Discord == "connected" && len(d.showing()) == 1 })
}
-// A settings change while a status is on its way to Discord leaves no error from the old run in the new one.
+// A settings change while a status is on its way to Discord leaves no error behind: one that keeps the connection lets
+// the send finish, one that changes the Discord application lets that connection go, and what plays goes out again.
func TestSettingsChangeDuringASendLeavesNoError(t *testing.T) {
- t.Parallel()
- e, m, d, l := setup(t)
- e.Start()
- eventually(t, "first status", func() bool { return len(d.showing()) == 1 })
- d.set(func(d *disc) { d.slow = 12 * testPoll })
- m.set(func(m *mpc) { m.pos += 600000 }) // a seek: a status goes out and waits for the slow answer
- n := len(d.list())
- eventually(t, "the seek on its way", func() bool { return len(d.list()) > n })
- cfg := e.Config()
- cfg.TextProgressBar = !cfg.TextProgressBar
- e.ApplySettings(cfg) // ends the run while the send waits
- d.set(func(d *disc) { d.slow = 0 })
- eventually(t, "the new run's status", func() bool {
- s := e.Status()
- return s.Discord == "connected" && s.NowPlaying != nil && len(d.showing()) == 1
- })
- if s := e.Status(); s.LastError != nil {
- t.Errorf("the new run shows the old run's error: %s", *s.LastError)
- }
- if l.has("Failed to update presence") {
- t.Errorf("the ended run's send was logged as a failure:\n%s", strings.Join(l.l, "\n"))
+ for _, change := range []string{"textProgressBar", "clientId"} {
+ t.Run(change, func(t *testing.T) {
+ t.Parallel()
+ e, m, d, l := setup(t)
+ e.Start()
+ eventually(t, "first status", func() bool { return len(d.showing()) == 1 })
+ slow := 12 * testPoll
+ if change == "clientId" {
+ slow = 80 * testPoll // longer than closing the old connection waits (1.5 s): the send fails with it
+ }
+ d.set(func(d *disc) { d.slow = slow })
+ m.set(func(m *mpc) { m.pos += 600000 }) // a seek: a status goes out and waits for the slow answer
+ n := len(d.list())
+ eventually(t, "the seek on its way", func() bool { return len(d.list()) > n })
+ cfg := e.Config()
+ if change == "clientId" {
+ cfg.ClientID = "123456789012345678"
+ } else {
+ cfg.TextProgressBar = !cfg.TextProgressBar
+ }
+ e.ApplySettings(cfg) // while the send waits
+ d.set(func(d *disc) { d.slow = 0 })
+ eventually(t, "the status with the new settings", func() bool {
+ s := e.Status()
+ return s.Discord == "connected" && s.NowPlaying != nil && len(d.showing()) == 1
+ })
+ time.Sleep(10 * testPoll)
+ if s := e.Status(); s.LastError != nil {
+ t.Errorf("an error after the change: %s", *s.LastError)
+ }
+ if l.has("Failed to update the status") {
+ t.Errorf("the send was logged as a failure:\n%s", strings.Join(l.list(), "\n"))
+ }
+ })
}
}
// The engine's state is spread over many fields that several goroutines change. Whatever happens in whatever order
// (the player pauses, seeks, changes file, stops or goes away; Discord refuses, answers late, fails clears or
-// restarts; the settings change; the engine is stopped and started), once things are quiet Discord must show
-// exactly what the player's last state calls for: one status for the file that plays, or none.
+// restarts; the settings change, the Discord application too; the engine is stopped and started), once things are
+// quiet Discord must show exactly what the player's last state calls for: one status for the file that plays, or none.
//
-// Eight fixed orders run every time. MPCRPC_CONVERGE_SEEDS=500 tries that many (for a hunt after a change to the tick).
+// Eight fixed orders run every time. MPRP_CONVERGE_SEEDS=500 tries that many (for a hunt after a change to the tick).
func TestStatusConverges(t *testing.T) {
seeds := int64(8)
- if n, err := strconv.ParseInt(os.Getenv("MPCRPC_CONVERGE_SEEDS"), 10, 64); err == nil && n > 0 {
+ if n, err := strconv.ParseInt(os.Getenv("MPRP_CONVERGE_SEEDS"), 10, 64); err == nil && n > 0 {
seeds = n
}
for seed := int64(1); seed <= seeds; seed++ {
@@ -246,6 +260,15 @@ func TestStatusConverges(t *testing.T) {
cfg.TextProgressBar = !cfg.TextProgressBar
e.ApplySettings(cfg)
}},
+ {"another Discord application", func() {
+ cfg := e.Config()
+ if cfg.ClientID == "1" {
+ cfg.ClientID = core.DefaultConfig().ClientID
+ } else {
+ cfg.ClientID = "1"
+ }
+ e.ApplySettings(cfg)
+ }},
{"stop and start", func() { e.Stop(); e.Start() }},
{"wake", func() { e.Wake() }},
}
diff --git a/internal/engine/stats_test.go b/internal/engine/stats_test.go
index 8862137..80beaec 100644
--- a/internal/engine/stats_test.go
+++ b/internal/engine/stats_test.go
@@ -10,7 +10,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
func TestStatsCountWhatIsShownAndStayOnThisComputer(t *testing.T) {
diff --git a/internal/engine/status_test.go b/internal/engine/status_test.go
index e6ac8f6..7cd113f 100644
--- a/internal/engine/status_test.go
+++ b/internal/engine/status_test.go
@@ -20,21 +20,26 @@ func TestDiscordOnStandbyUntilSomethingPlays(t *testing.T) {
eventually(t, "connected", func() bool { return e.Status().Discord == "connected" })
}
-// Saving settings that did not change for the engine (app-only options) must not restart it.
-func TestUnchangedSettingsDoNotRestart(t *testing.T) {
+// Saving settings that did not change for the engine (app-only options) sends nothing; a real change sends the status
+// again, without a restart.
+func TestUnchangedSettingsSendNothing(t *testing.T) {
t.Parallel()
- e, _, _, l := setup(t)
+ e, _, d, l := setup(t)
e.Start()
eventually(t, "shown", func() bool { return e.Status().NowPlaying != nil })
+ n := len(d.list())
e.ApplySettings(e.Config())
time.Sleep(300 * time.Millisecond)
- if n := strings.Count(strings.Join(l.list(), "\n"), "Presence stopped."); n != 0 || e.Status().NowPlaying == nil {
- t.Fatalf("restarted %d times for nothing", n)
+ if len(d.list()) != n || e.Status().NowPlaying == nil {
+ t.Fatalf("unchanged settings sent %d requests to Discord", len(d.list())-n)
}
cfg := e.Config()
cfg.ProgressWidth++
e.ApplySettings(cfg)
- eventually(t, "restart for a real change", func() bool { return strings.Contains(strings.Join(l.list(), "\n"), "Presence stopped.") })
+ eventually(t, "sent again for a real change", func() bool { return len(d.list()) > n })
+ if strings.Contains(strings.Join(l.list(), "\n"), "Stopped sending the status to Discord.") {
+ t.Fatal("a settings change restarted the engine")
+ }
}
func (l *logs) list() []string {
diff --git a/internal/engine/stream_test.go b/internal/engine/stream_test.go
index 4c89867..5c20946 100644
--- a/internal/engine/stream_test.go
+++ b/internal/engine/stream_test.go
@@ -4,7 +4,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The stream title is for videos: a song stays "Listening to" with it on.
diff --git a/internal/engine/stuck_windows_test.go b/internal/engine/stuck_windows_test.go
index 878faf7..fe8afeb 100644
--- a/internal/engine/stuck_windows_test.go
+++ b/internal/engine/stuck_windows_test.go
@@ -11,7 +11,7 @@ import (
"time"
"unsafe"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// A Discord that answers the handshake and then stops reading, on an unbuffered pipe: our next write blocks inside
diff --git a/internal/engine/tick.go b/internal/engine/tick.go
index 0fe7ae2..d0c96de 100644
--- a/internal/engine/tick.go
+++ b/internal/engine/tick.go
@@ -6,9 +6,9 @@ import (
"math"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/artwork"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/discord"
+ "github.com/CptPakundo/MPRP/internal/artwork"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/discord"
)
// appNameFor gives the default app name the playing player's name: the default describes Media Player Classic, other
@@ -44,9 +44,10 @@ type built struct {
display string
found *core.Art
music bool
- noEpTitle bool // an episode whose title was wanted but did not come
- fromFolder bool // the show's name came from the file's folder
- why []string // "Why this title?" (see Status.Why)
+ noEpTitle bool // an episode whose title was wanted but did not come
+ fromFolder bool // the show's name came from the file's folder
+ why []string // "Why this title?" (see Status.Why)
+ match *MatchInfo // see Status.Match
}
// buildActivity makes the activity for what plays: titles are parsed and looked up (art may be nil) unless the title
@@ -68,7 +69,8 @@ func buildActivity(info *core.Info, cfg *core.Config, art *artwork.Artwork, fold
// a song: shown as it is named, as "Listening to"; never sent to the movie and TV catalogs
media := core.MusicMedia(info.File)
c := *cfg
- c.StreamTitle = "off" // a song stays "Listening to": the stream title is for videos
+ c.StreamTitle = "off" // a song stays "Listening to": the stream title is for videos
+ c.TextLines = "standard" // and its lines stay as they are: text lines are for videos
b.activity = core.BuildActivity(info, &c, at.UnixMilli(), media, nil)
core.Listening(b.activity)
b.display = media.Display
@@ -86,7 +88,11 @@ func buildActivity(info *core.Info, cfg *core.Config, art *artwork.Artwork, fold
media.BadgeEpisode = n
}
}
+ media.File = baseName(info.File) // for a fix made for this file only (Fix a match)
+ read := media
+ shifted := false
if art != nil {
+ media, shifted = art.Offset(media) // a fix's season and episode offset: the catalog's numbers from here on
b.found = art.Lookup(media)
}
b.activity = core.BuildActivity(info, cfg, at.UnixMilli(), media, b.found)
@@ -95,7 +101,12 @@ func buildActivity(info *core.Info, cfg *core.Config, art *artwork.Artwork, fold
(b.found == nil || b.found.Episode == nil)
b.display = media.Display
b.fromFolder = media.FromFolder
- b.why = append(readAs(info, media), art.Explain(media, b.found)...)
+ b.why = readAs(info, read)
+ if shifted {
+ b.why = append(b.why, "Your fix's offset moved the numbers: looked up as "+media.Label+".")
+ }
+ b.why = append(b.why, art.Explain(media, b.found)...)
+ b.match = matchOf(read, b.found, art)
}
return b
}
@@ -108,7 +119,7 @@ func (e *Engine) tick(r *run) {
return
}
e.mu.Lock()
- cfg := e.cfg
+ cfg, st := e.cfg, stamp{cfg: e.cfgGen}
save := e.statTime(time.Now(), e.pollInterval(cfg))
e.mu.Unlock()
e.writeStats(save)
@@ -133,8 +144,10 @@ func (e *Engine) tick(r *run) {
}
e.mu.Lock()
- if e.cur != r {
- e.mu.Unlock() // stopped, or started again, while the players were asked: the answer is not this run's
+ if e.cur != r || e.cfgGen != st.cfg {
+ // stopped, or started again, while the players were asked: the answer is not this run's; or the settings changed
+ // (ApplySettings asks for the next check at once)
+ e.mu.Unlock()
return
}
// One check without any answer is not yet "the player is gone": a player that loads a file or seeks on a slow disk
@@ -165,6 +178,7 @@ func (e *Engine) tick(r *run) {
return
}
rpc := e.rpc
+ st.disc = e.discGen
if live != e.live {
// a stream began or ended: the same file goes out again in the other form
e.live, e.resend = live, true
@@ -197,9 +211,13 @@ func (e *Engine) tick(r *run) {
if !update {
return
}
- e.sendUpdate(r, rpc, info, &cfg, art, now)
+ e.sendUpdate(r, rpc, st, info, &cfg, art, now)
}
+// stamp is what a check read its settings (cfgGen) and its Discord connection (discGen) under: a send is let go
+// when either changed meanwhile (ApplySettings).
+type stamp struct{ cfg, disc uint64 }
+
// notePlayer remembers which player answers (none: "") and logs when it changes. Called with e.mu held; it is
// released around the log and returned with it held.
func (e *Engine) notePlayer(info *core.Info) {
@@ -277,11 +295,11 @@ func (e *Engine) clearWhenIdle(r *run, hidden, ended bool) {
switch failed = e.logClearResult(err, first); {
case failed || !shown:
case hidden:
- e.log("INFO", "This file is on your don't-show list - presence cleared.")
+ e.log("INFO", "This file is on your don't-show list - status cleared.")
case ended:
- e.log("INFO", "The video ended - presence cleared.")
+ e.log("INFO", "The video ended - status cleared.")
default:
- e.log("INFO", "Nothing playing - presence cleared.")
+ e.log("INFO", "Nothing playing - status cleared.")
}
}
e.mu.Lock()
@@ -359,25 +377,31 @@ func (e *Engine) clearWhenPausedLong(r *run, rpc *discord.Client, minutes int) {
if err == errStale || e.logClearResult(err, first) {
return
}
- e.log("INFO", fmt.Sprintf("Paused for %d min - presence cleared (it returns when you resume).", minutes))
+ e.log("INFO", fmt.Sprintf("Paused for %d min - status cleared (it returns when you resume).", minutes))
}
// sendUpdate builds the activity for what plays (at: when the player reported it), sends it, and records and logs
// what was shown. A status Discord did not take stays due, but the next try waits: retryAfter, doubling up to twelve
// times that while Discord keeps failing, so a Discord that refuses everything is not asked at every check (it
// limits a status to five changes in 20 seconds), and the log names a repeated failure once. Called with e.mu
-// released (it takes it only for the bookkeeping).
-func (e *Engine) sendUpdate(r *run, rpc *discord.Client, info *core.Info, cfg *core.Config, art *artwork.Artwork, at time.Time) {
+// released (it takes it only for the bookkeeping). st is what the check read cfg and rpc under: nothing is sent with
+// settings that changed meanwhile.
+func (e *Engine) sendUpdate(r *run, rpc *discord.Client, st stamp, info *core.Info, cfg *core.Config, art *artwork.Artwork, at time.Time) {
b := buildActivity(info, cfg, art, &e.folders, at)
- if !e.isCurrent(r) {
- return
+ e.mu.Lock()
+ stale := e.cur != r || e.cfgGen != st.cfg
+ e.mu.Unlock()
+ if stale {
+ return // the run ended, or the settings changed (a title hidden now must not go out): the next check sends
}
sent, err := e.sendActivity(rpc, cfg, b.activity, info.Player+"/"+info.File)
if err != nil {
msg := err.Error()
e.mu.Lock()
- if e.cur != r {
- e.mu.Unlock() // the run ended while Discord was asked (its connection was closed): not the next run's error
+ if e.cur != r || e.discGen != st.disc {
+ // the run ended while Discord was asked, or a settings change let its connection go (the status goes out again
+ // on the next one): not an error of what runs now
+ e.mu.Unlock()
return
}
again := e.lastError != nil && *e.lastError == msg
@@ -391,7 +415,7 @@ func (e *Engine) sendUpdate(r *run, rpc *discord.Client, info *core.Info, cfg *c
e.retryAt = time.Now().Add(min(wait, 12*e.retryAfter))
e.mu.Unlock()
if !again {
- e.log("ERROR", "Failed to update presence: "+msg)
+ e.log("ERROR", "Failed to update the status: "+msg)
}
return
}
@@ -428,6 +452,7 @@ func (e *Engine) recordShown(r *run, info *core.Info, cfg *core.Config, b built,
}
e.nowPlaying = &d
e.why = b.why
+ e.match = b.match
e.paused = info.State == 1
e.preview = core.PreviewOf(sent, cfg) // what Discord actually got (the basic fallback carries less)
e.barShown = streamBar(info, cfg)
@@ -465,7 +490,7 @@ func (e *Engine) logShown(info *core.Info, cfg *core.Config, b built) {
e.log("INFO", fmt.Sprintf("%s: %s%s (%s)", word, b.display, tag, src))
}
-func (e *Engine) loop(r *run, interval time.Duration) {
+func (e *Engine) loop(r *run) {
for {
func() {
defer func() {
@@ -475,6 +500,9 @@ func (e *Engine) loop(r *run, interval time.Duration) {
}()
e.tick(r)
}()
+ e.mu.Lock()
+ interval := e.pollInterval(e.cfg) // read each time: a settings change takes effect without a restart
+ e.mu.Unlock()
t := time.NewTimer(interval)
select {
case <-r.ctx.Done():
diff --git a/internal/engine/vlc_test.go b/internal/engine/vlc_test.go
index 0dae552..08e7030 100644
--- a/internal/engine/vlc_test.go
+++ b/internal/engine/vlc_test.go
@@ -66,7 +66,7 @@ func TestVLCOverItsWebInterface(t *testing.T) {
v := newFakeVLCWeb(t, "secret")
e, d, l := vlcEngine(t, deadPort(t), nil, v, "secret")
e.Start()
- eventually(t, "VLC shown", func() bool { s := e.Status(); return s.NowPlaying != nil && s.Player == "VLC" && s.MPC })
+ eventually(t, "VLC shown", func() bool { s := e.Status(); return s.NowPlaying != nil && s.Player == "VLC" && s.PlayerAnswers })
if !l.has("VLC detected.") || !l.has("VLC's web interface on port") {
t.Error("the log should name VLC")
}
@@ -84,7 +84,7 @@ func TestVLCOverItsWebInterface(t *testing.T) {
v.set(func(f *fakeVLCWeb) { f.state = "stopped" })
eventually(t, "cleared when VLC stops", func() bool { return isClear(d) && e.Status().NowPlaying == nil })
- if s := e.Status(); !s.MPC || s.Player != "VLC" {
+ if s := e.Status(); !s.PlayerAnswers || s.Player != "VLC" {
t.Errorf("a stopped VLC is still a reachable player: %+v", s)
}
}
@@ -139,7 +139,7 @@ func TestVLCNotAskedWithoutPassword(t *testing.T) {
e, _, l := vlcEngine(t, deadPort(t), nil, v, "")
e.Start()
time.Sleep(700 * time.Millisecond)
- if v.count() != 0 || e.Status().MPC {
+ if v.count() != 0 || e.Status().PlayerAnswers {
t.Errorf("VLC asked %d times", v.count())
}
if l.has("VLC") {
@@ -154,7 +154,7 @@ func TestVLCWrongPassword(t *testing.T) {
e.Start()
eventually(t, "hint", func() bool { return strings.Contains(e.Status().Hint, "refused the password") })
time.Sleep(700 * time.Millisecond)
- if s := e.Status(); s.MPC || s.Player != "" {
+ if s := e.Status(); s.PlayerAnswers || s.Player != "" {
t.Errorf("VLC refused us, yet %+v", s)
}
if n := countLogs(l, "refused the password"); n != 1 {
diff --git a/internal/engine/where_test.go b/internal/engine/where_test.go
index 955039a..d90a417 100644
--- a/internal/engine/where_test.go
+++ b/internal/engine/where_test.go
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The Never show list also matches where a server keeps the item: a Plex library's name, or a folder of the file's
diff --git a/internal/engine/why.go b/internal/engine/why.go
index ff8a025..5de99c1 100644
--- a/internal/engine/why.go
+++ b/internal/engine/why.go
@@ -4,7 +4,8 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/artwork"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// readAs is the start of "Why this title?": the name the player gave and what was read from it. The folder path is
@@ -36,3 +37,49 @@ func readAs(info *core.Info, media *core.Media) []string {
out = append(out, "Read as: "+strings.Join(parts, ", ")+".")
return out
}
+
+// MatchInfo is what the window's Fix this match dialog starts from (Status.Match). File is the file's base name,
+// never its folder; Season and Episode are the numbers read from the file (0: none); Now describes the current
+// match ("" for none), NowEntry is its catalog page, and Fixed says the user's fix applies.
+type MatchInfo struct {
+ File string `json:"file"`
+ Title string `json:"title"`
+ Season int `json:"season,omitempty"`
+ Episode int `json:"episode,omitempty"`
+ Now string `json:"now,omitempty"`
+ NowEntry string `json:"nowEntry,omitempty"`
+ Fixed bool `json:"fixed,omitempty"`
+}
+
+// matchOf is the dialog's starting point for a title read as media and found as found (nil: nothing found).
+func matchOf(media *core.Media, found *core.Art, art *artwork.Artwork) *MatchInfo {
+ m := &MatchInfo{File: media.File, Title: media.Title}
+ if media.IsEpisode && media.Season != core.NA {
+ m.Season = media.Season
+ }
+ if media.IsEpisode && media.Episode != core.NA {
+ m.Episode = media.Episode
+ }
+ if found != nil {
+ switch {
+ case found.Source == "override":
+ m.Now = "your image"
+ default:
+ m.Now = found.Name
+ if found.Year != core.NA && found.Year != 0 {
+ m.Now += " (" + strconv.Itoa(found.Year) + ")"
+ }
+ m.NowEntry = found.URL
+ }
+ }
+ m.Fixed = art.FixFor(media) != nil
+ return m
+}
+
+// baseName is a file name without its folder (a player may give a whole path or an address).
+func baseName(file string) string {
+ if i := strings.LastIndexAny(file, `/\`); i >= 0 {
+ return file[i+1:]
+ }
+ return file
+}
diff --git a/internal/engine/why_test.go b/internal/engine/why_test.go
index 506680f..92caf61 100644
--- a/internal/engine/why_test.go
+++ b/internal/engine/why_test.go
@@ -4,7 +4,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// "Why this title?" names the file and what was read from it while it shows, never the folder path, and is gone
diff --git a/internal/jellyfin/account.go b/internal/jellyfin/account.go
index 81c91cf..8f4d49a 100644
--- a/internal/jellyfin/account.go
+++ b/internal/jellyfin/account.go
@@ -16,7 +16,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
var (
@@ -88,7 +88,7 @@ func Address(s string) (string, error) {
// Authorization header ("MediaBrowser" scheme); Emby reads X-Emby-Authorization ("Emby" scheme) and X-Emby-Token.
func (c *Client) auth(req *http.Request, token string) {
q := func(s string) string { return `"` + strings.NewReplacer(`"`, "", ",", " ").Replace(s) + `"` }
- parts := `Client=` + q("MPCvibedRPC") + `, Device=` + q("MPCvibedRPC on "+remote.OSName()) + `, DeviceId=` + q(c.DeviceID) + `, Version=` + q(c.Version)
+ parts := `Client=` + q("MPRP") + `, Device=` + q("MPRP on "+remote.OSName()) + `, DeviceId=` + q(c.DeviceID) + `, Version=` + q(c.Version)
if token != "" {
parts += `, Token=` + q(token)
req.Header.Set("X-Emby-Token", token)
diff --git a/internal/jellyfin/jellyfin_test.go b/internal/jellyfin/jellyfin_test.go
index e797d57..5ebd31f 100644
--- a/internal/jellyfin/jellyfin_test.go
+++ b/internal/jellyfin/jellyfin_test.go
@@ -74,7 +74,7 @@ func newFake(t *testing.T, emby bool) *fakeServer {
} else if f.qcOff {
w.WriteHeader(401)
} else {
- fmt.Fprint(w, `{"Authenticated":false,"Secret":"qc-secret","Code":"123456","DeviceId":"d","DeviceName":"n","AppName":"MPCvibedRPC","AppVersion":"0.9.21","DateAdded":"2026-10-11T10:00:00Z"}`)
+ fmt.Fprint(w, `{"Authenticated":false,"Secret":"qc-secret","Code":"123456","DeviceId":"d","DeviceName":"n","AppName":"MPRP","AppVersion":"0.9.21","DateAdded":"2026-10-11T10:00:00Z"}`)
}
case path == "/QuickConnect/Connect" && r.URL.Query().Get("secret") == "qc-secret":
f.checks++
@@ -131,7 +131,7 @@ func TestFindJellyfinAndEmby(t *testing.T) {
if err != nil || s.Product != "Jellyfin" || s.Name != "Sample Server" || c.Base != f.URL {
t.Fatalf("Jellyfin: %+v %v base %s", s, err, c.Base)
}
- if !strings.HasPrefix(f.auth, "MediaBrowser ") || !strings.Contains(f.auth, `DeviceId="sample-device"`) || !strings.Contains(f.auth, `Client="MPCvibedRPC"`) {
+ if !strings.HasPrefix(f.auth, "MediaBrowser ") || !strings.Contains(f.auth, `DeviceId="sample-device"`) || !strings.Contains(f.auth, `Client="MPRP"`) {
t.Fatalf("the client describes itself: %q", f.auth)
}
e := newFake(t, true)
@@ -240,7 +240,7 @@ func sessionsJSON(checkIn time.Time, paused bool) string {
"NowPlayingItem":{"Name":"Sample Movie","Id":"i3","Type":"Movie","MediaType":"Video","ProductionYear":2020,"RunTimeTicks":72000000000}},
{"PlayState":{"PositionTicks":6000000000,"IsPaused":%[3]t},"Id":"s4","UserId":"%[2]s","Client":"Jellyfin Web","LastPlaybackCheckIn":"%[1]s",
"NowPlayingItem":{"Name":"The Sample","Id":"i4","Type":"Episode","MediaType":"Video","SeriesName":"Sample Show","ParentIndexNumber":1,"IndexNumber":2,"RunTimeTicks":14400000000}},
- {"Id":"s5","UserId":"%[2]s","Client":"MPCvibedRPC","LastPlaybackCheckIn":"0001-01-01T00:00:00.0000000Z","PlayState":{}}
+ {"Id":"s5","UserId":"%[2]s","Client":"MPRP","LastPlaybackCheckIn":"0001-01-01T00:00:00.0000000Z","PlayState":{}}
]`, ci, "6c8f0a0b-1c2d-4e5f-8a9b-0c1d2e3f4a5b", paused)
}
diff --git a/internal/jellyfin/live_test.go b/internal/jellyfin/live_test.go
index 6c288bb..d1054db 100644
--- a/internal/jellyfin/live_test.go
+++ b/internal/jellyfin/live_test.go
@@ -12,20 +12,20 @@ import (
// TestLiveJellyfin runs against a real Jellyfin or Emby server (tools/ci/live-jellyfin.sh starts the official images on
// CI, with a stand-in player that plays a sample episode). It only runs on request:
//
-// MPCRPC_LIVE_JELLYFIN_ADDRESS=http://127.0.0.1:8096 MPCRPC_LIVE_JELLYFIN_USER=... MPCRPC_LIVE_JELLYFIN_PASSWORD=...
-// MPCRPC_LIVE_JELLYFIN_PRODUCT=Jellyfin MPCRPC_LIVE_TITLE="Sample Show" go test -run TestLiveJellyfin ./internal/jellyfin
+// MPRP_LIVE_JELLYFIN_ADDRESS=http://127.0.0.1:8096 MPRP_LIVE_JELLYFIN_USER=... MPRP_LIVE_JELLYFIN_PASSWORD=...
+// MPRP_LIVE_JELLYFIN_PRODUCT=Jellyfin MPRP_LIVE_TITLE="Sample Show" go test -run TestLiveJellyfin ./internal/jellyfin
//
// It signs in with the password (and, on Jellyfin, with Quick Connect, approved with the first sign-in), follows what
// the user plays, and signs out again.
func TestLiveJellyfin(t *testing.T) {
- addr := os.Getenv("MPCRPC_LIVE_JELLYFIN_ADDRESS")
+ addr := os.Getenv("MPRP_LIVE_JELLYFIN_ADDRESS")
if addr == "" {
- t.Skip("set MPCRPC_LIVE_JELLYFIN_ADDRESS to run against a real Jellyfin or Emby server")
+ t.Skip("set MPRP_LIVE_JELLYFIN_ADDRESS to run against a real Jellyfin or Emby server")
}
- user, pw, product := os.Getenv("MPCRPC_LIVE_JELLYFIN_USER"), os.Getenv("MPCRPC_LIVE_JELLYFIN_PASSWORD"), os.Getenv("MPCRPC_LIVE_JELLYFIN_PRODUCT")
+ user, pw, product := os.Getenv("MPRP_LIVE_JELLYFIN_USER"), os.Getenv("MPRP_LIVE_JELLYFIN_PASSWORD"), os.Getenv("MPRP_LIVE_JELLYFIN_PRODUCT")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
- c := &Client{Base: addr, DeviceID: "ci-mpcvibedrpc", Version: "0.0.0"}
+ c := &Client{Base: addr, DeviceID: "ci-mprp", Version: "0.0.0"}
srv, err := c.Find(ctx)
if err != nil {
t.Fatal(err)
@@ -44,7 +44,7 @@ func TestLiveJellyfin(t *testing.T) {
t.Logf("signed in as %s (%s)", a.UserName, a.UserID)
if srv.Product == "Jellyfin" {
- qc := &Client{Base: c.Base, DeviceID: "ci-mpcvibedrpc-qc", Version: "0.0.0"}
+ qc := &Client{Base: c.Base, DeviceID: "ci-mprp-qc", Version: "0.0.0"}
p, err := qc.StartQuickConnect(ctx)
if err != nil {
t.Fatalf("Quick Connect: %v", err)
@@ -86,7 +86,7 @@ func TestLiveJellyfin(t *testing.T) {
}
}
w := &Watcher{Client: c, Token: a.Token, UserID: a.UserID, Product: srv.Product}
- title := os.Getenv("MPCRPC_LIVE_TITLE")
+ title := os.Getenv("MPRP_LIVE_TITLE")
for {
if err := w.poll(ctx); err != nil {
t.Fatal(err)
diff --git a/internal/jellyfin/meta.go b/internal/jellyfin/meta.go
index 9763f80..b710ba6 100644
--- a/internal/jellyfin/meta.go
+++ b/internal/jellyfin/meta.go
@@ -4,7 +4,7 @@ import (
"regexp"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Item is what the server says about what a session plays (the parts used).
diff --git a/internal/jellyfin/watcher.go b/internal/jellyfin/watcher.go
index 38f5720..150ad79 100644
--- a/internal/jellyfin/watcher.go
+++ b/internal/jellyfin/watcher.go
@@ -8,8 +8,8 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
// Watcher asks one server's session list what the user plays there, every few seconds. Run it in a goroutine; Now is
diff --git a/internal/kodi/kodi.go b/internal/kodi/kodi.go
index 9da434c..5d4c7ab 100644
--- a/internal/kodi/kodi.go
+++ b/internal/kodi/kodi.go
@@ -12,7 +12,7 @@ import (
"net/http"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
var (
diff --git a/internal/logo/logo.go b/internal/logo/logo.go
new file mode 100644
index 0000000..fa1892c
--- /dev/null
+++ b/internal/logo/logo.go
@@ -0,0 +1,136 @@
+// Package logo draws the program's icon, "the status card": a play triangle over a two-tone progress bar on an indigo
+// tile. tools/mkico makes the Windows icons, the macOS app icon and the README's picture from Image; the macOS menu
+// bar shows Template.
+//
+// The shapes are on a 256-unit grid whose 16-unit steps are the pixels of the 16-pixel icon, and every test is done in
+// whole numbers, so the same pixels come out on every system (the release build compares the icons byte for byte).
+package logo
+
+import "image"
+
+// The colours, from the settings window's tokens in ui.css.
+var (
+ tileColour = rgb{0x47, 0x52, 0xc4} // --accent (light theme)
+ whiteColour = rgb{0xff, 0xff, 0xff} // --on-accent: the triangle and the elapsed part of the bar
+ barRestColour = rgb{0xa5, 0xac, 0xf8} // --accent-text (dark theme): the rest of the bar
+ dotColour = rgb{0xd1, 0x3a, 0x3a} // --bad-fill-hover (dark theme): the update dot
+)
+
+type rgb struct{ r, g, b int }
+
+// shape is one part of the drawing. A sample takes the colour (and the template's opacity, 0-255) of the last shape
+// that covers it.
+type shape struct {
+ in func(p point) bool
+ colour rgb
+ mono int
+}
+
+// The drawing, in order. The template keeps the tile and cuts the triangle and the elapsed bar out of it; the rest of
+// the bar is cut to about 45 %.
+var shapes = []shape{
+ {roundRect(0, 0, 256, 256, 40), tileColour, 255},
+ {triangle(96, 48, 96, 160, 176, 104), whiteColour, 0},
+ {roundRect(48, 176, 208, 208, 16), barRestColour, 140},
+ {roundRect(48, 176, 136, 208, 16), whiteColour, 0},
+}
+
+// The update dot: a red circle in the top right corner, set apart from the drawing by a transparent ring.
+const dotX, dotY, dotR, dotRing = 208, 48, 44, 14
+
+// point is a sample's place on the grid, as x/d and y/d units.
+type point struct{ x, y, d int64 }
+
+func roundRect(x0, y0, x1, y1, r int64) func(point) bool {
+ return func(p point) bool {
+ dx := max((x0+r)*p.d-p.x, p.x-(x1-r)*p.d, 0)
+ dy := max((y0+r)*p.d-p.y, p.y-(y1-r)*p.d, 0)
+ return dx*dx+dy*dy <= r*r*p.d*p.d
+ }
+}
+
+func triangle(ax, ay, bx, by, cx, cy int64) func(point) bool {
+ return func(p point) bool {
+ side := func(ax, ay, bx, by int64) int64 {
+ return (p.x-bx*p.d)*(ay-by)*p.d - (ax-bx)*p.d*(p.y-by*p.d)
+ }
+ d1, d2, d3 := side(ax, ay, bx, by), side(bx, by, cx, cy), side(cx, cy, ax, ay)
+ return !((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))
+ }
+}
+
+func inCircle(p point, cx, cy, r int64) bool {
+ dx, dy := p.x-cx*p.d, p.y-cy*p.d
+ return dx*dx+dy*dy <= r*r*p.d*p.d
+}
+
+// sample is what covers one sample: its colour and template opacity, and whether anything does.
+func sample(p point, dot bool) (c rgb, mono int, covered bool) {
+ if dot {
+ if inCircle(p, dotX, dotY, dotR) {
+ return dotColour, 255, true
+ }
+ if inCircle(p, dotX, dotY, dotR+dotRing) {
+ return rgb{}, 0, false
+ }
+ }
+ for _, s := range shapes {
+ if s.in(p) {
+ c, mono, covered = s.colour, s.mono, true
+ }
+ }
+ return c, mono, covered
+}
+
+// ss is the samples per pixel along each side.
+const ss = 8
+
+// render draws the logo at n x n pixels into img at (ox, oy); each pixel is the average of its ss x ss samples.
+func render(img *image.NRGBA, ox, oy, n int, dot, template bool) {
+ d := int64(2 * ss * n) // a sample's middle is at (2*(ss*x+sx)+1)/(2*ss*n) of the side, times 256
+ for y := 0; y < n; y++ {
+ for x := 0; x < n; x++ {
+ var r, g, b, cover, alpha int
+ for sy := 0; sy < ss; sy++ {
+ for sx := 0; sx < ss; sx++ {
+ p := point{int64(256 * (2*(ss*x+sx) + 1)), int64(256 * (2*(ss*y+sy) + 1)), d}
+ c, mono, ok := sample(p, dot)
+ if !ok {
+ continue
+ }
+ cover++
+ alpha += mono
+ r, g, b = r+c.r, g+c.g, b+c.b
+ }
+ }
+ i := img.PixOffset(ox+x, oy+y)
+ px := img.Pix[i : i+4 : i+4]
+ if template {
+ px[0], px[1], px[2], px[3] = 0, 0, 0, uint8(div(alpha, ss*ss))
+ continue
+ }
+ if cover == 0 {
+ continue
+ }
+ px[0], px[1], px[2], px[3] = uint8(div(r, cover)), uint8(div(g, cover)), uint8(div(b, cover)), uint8(div(255*cover, ss*ss))
+ }
+ }
+}
+
+// div is a/b rounded to the nearest whole number (a, b >= 0).
+func div(a, b int) int { return (2*a + b) / (2 * b) }
+
+// Image is the icon at n x n pixels; with dot, the update dot in the top right corner (the tray while an update waits).
+func Image(n int, dot bool) *image.NRGBA {
+ img := image.NewNRGBA(image.Rect(0, 0, n, n))
+ render(img, 0, 0, n, dot, false)
+ return img
+}
+
+// Template is the one-colour icon for the macOS menu bar: black, with the shape in the alpha channel, which macOS
+// recolours for light and dark menu bars. It is n x n pixels with the drawing pad pixels in from each side.
+func Template(n, pad int, dot bool) *image.NRGBA {
+ img := image.NewNRGBA(image.Rect(0, 0, n, n))
+ render(img, pad, pad, n-2*pad, dot, true)
+ return img
+}
diff --git a/internal/logo/logo_test.go b/internal/logo/logo_test.go
new file mode 100644
index 0000000..0b93a04
--- /dev/null
+++ b/internal/logo/logo_test.go
@@ -0,0 +1,82 @@
+package logo
+
+import (
+ "image/color"
+ "testing"
+)
+
+// The drawing at 256 pixels, one pixel per grid unit, against the shapes of the design (concept-1.svg).
+func TestImageShapes(t *testing.T) {
+ img := Image(256, false)
+ for _, c := range []struct {
+ x, y int
+ want color.NRGBA
+ what string
+ }{
+ {128, 20, color.NRGBA{0x47, 0x52, 0xc4, 255}, "the tile"},
+ {120, 104, color.NRGBA{255, 255, 255, 255}, "the triangle"},
+ {80, 192, color.NRGBA{255, 255, 255, 255}, "the elapsed part of the bar"},
+ {180, 192, color.NRGBA{0xa5, 0xac, 0xf8, 255}, "the rest of the bar"},
+ {1, 1, color.NRGBA{}, "outside the rounded corner"},
+ } {
+ if got := img.NRGBAAt(c.x, c.y); got != c.want {
+ t.Errorf("%s at (%d,%d): %v, want %v", c.what, c.x, c.y, got, c.want)
+ }
+ }
+ dot := Image(256, true)
+ if got := dot.NRGBAAt(208, 48); got != (color.NRGBA{0xd1, 0x3a, 0x3a, 255}) {
+ t.Errorf("the update dot: %v", got)
+ }
+ if got := dot.NRGBAAt(208, 100); got.A != 0 { // 52 units below its middle: the ring
+ t.Errorf("the ring around the dot: %v", got)
+ }
+ if dot.NRGBAAt(60, 220) != img.NRGBAAt(60, 220) {
+ t.Error("the dot changes the rest of the icon")
+ }
+}
+
+// At 16 pixels the shapes land on whole pixels: the triangle's flat side and the bar are sharp.
+func TestImageIsSharpAt16(t *testing.T) {
+ img := Image(16, false)
+ if a := img.NRGBAAt(6, 4); a != (color.NRGBA{255, 255, 255, 255}) {
+ t.Errorf("the triangle's first column: %v", a)
+ }
+ if a := img.NRGBAAt(5, 11); a != (color.NRGBA{255, 255, 255, 255}) {
+ t.Errorf("the bar's elapsed part: %v", a)
+ }
+ if a := img.NRGBAAt(11, 12); a != (color.NRGBA{0xa5, 0xac, 0xf8, 255}) {
+ t.Errorf("the bar's rest: %v", a)
+ }
+ if a := img.NRGBAAt(5, 10); a != (color.NRGBA{0x47, 0x52, 0xc4, 255}) {
+ t.Errorf("the row between the triangle and the bar: %v", a)
+ }
+}
+
+// The menu bar's template: the tile is solid, the triangle and the elapsed bar are cut out, the rest of the bar is
+// partly cut, and the drawing sits pad pixels in.
+func TestTemplate(t *testing.T) {
+ img := Template(36, 2, false)
+ alpha := func(x, y int) uint8 { return img.NRGBAAt(x, y).A }
+ if a := alpha(0, 18); a != 0 {
+ t.Errorf("the margin: %d", a)
+ }
+ if a := alpha(18, 4); a != 255 {
+ t.Errorf("the tile: %d", a)
+ }
+ if a := alpha(16, 15); a != 0 {
+ t.Errorf("the triangle: %d", a)
+ }
+ if a := alpha(10, 26); a != 0 {
+ t.Errorf("the elapsed bar: %d", a)
+ }
+ if a := alpha(24, 26); a != 140 {
+ t.Errorf("the rest of the bar: %d", a)
+ }
+ for y := 0; y < 36; y++ {
+ for x := 0; x < 36; x++ {
+ if c := img.NRGBAAt(x, y); c.R != 0 || c.G != 0 || c.B != 0 {
+ t.Fatalf("(%d,%d) is not black: %v", x, y, c)
+ }
+ }
+ }
+}
diff --git a/internal/mpris/mpris.go b/internal/mpris/mpris.go
index 6b062f2..3606f52 100644
--- a/internal/mpris/mpris.go
+++ b/internal/mpris/mpris.go
@@ -13,8 +13,8 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
)
const (
diff --git a/internal/mpris/mpris_test.go b/internal/mpris/mpris_test.go
index 8992b36..3fb1774 100644
--- a/internal/mpris/mpris_test.go
+++ b/internal/mpris/mpris_test.go
@@ -5,9 +5,9 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
)
func TestPlayerName(t *testing.T) {
diff --git a/internal/mpris/watch.go b/internal/mpris/watch.go
index dd62101..571783d 100644
--- a/internal/mpris/watch.go
+++ b/internal/mpris/watch.go
@@ -3,7 +3,7 @@ package mpris
import (
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus"
)
// changeProps are the player properties whose change is news: playing or paused, another file, another speed.
diff --git a/internal/mpris/watch_test.go b/internal/mpris/watch_test.go
index 38af06e..fe084b8 100644
--- a/internal/mpris/watch_test.go
+++ b/internal/mpris/watch_test.go
@@ -5,8 +5,8 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus"
- "github.com/CptPakundo/MPCvibedRPC/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
)
// Watch reports a player that pauses, seeks or changes file, and nothing else, and returns when the bus goes away.
diff --git a/internal/mpvipc/mpvipc.go b/internal/mpvipc/mpvipc.go
index 6caebb5..d27e902 100644
--- a/internal/mpvipc/mpvipc.go
+++ b/internal/mpvipc/mpvipc.go
@@ -10,7 +10,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The properties asked for, by request id.
diff --git a/internal/notify/notify.go b/internal/notify/notify.go
new file mode 100644
index 0000000..9df29be
--- /dev/null
+++ b/internal/notify/notify.go
@@ -0,0 +1,165 @@
+// Package notify shows desktop notifications on Linux through the notification service of the session bus
+// (org.freedesktop.Notifications, which GNOME, KDE Plasma, Xfce, Cinnamon, MATE and the usual stand-alone services
+// such as dunst and mako offer). A click on a notification calls back, so the settings window can open. Each
+// notification carries the program's logo as pixels (the image-data hint), so no icon file has to be installed.
+package notify
+
+import (
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/logo"
+)
+
+const (
+ service = "org.freedesktop.Notifications"
+ object = "/org/freedesktop/Notifications"
+ // defaultAction is the action of a click on the notification itself (not on a button).
+ defaultAction = "default"
+)
+
+// iconSize is the logo's size in the notification, in pixels (64 KB of pixels; sharp on a high-DPI screen too).
+const iconSize = 128
+
+// icon is the image-data hint (iiibiiay): width, height, row stride, has alpha, bits per sample, channels and the
+// pixels, RGBA without premultiplied alpha, as image.NRGBA holds them. Version 1.2 of the notification specification
+// named it image-data (image_data in 1.1, icon_data before); every current service takes that name.
+var icon = sync.OnceValue(func() dbus.Variant {
+ img := logo.Image(iconSize, false)
+ return dbus.Variant{Sig: "(iiibiiay)", Value: []any{int32(iconSize), int32(iconSize), int32(img.Stride), true, int32(8), int32(4), img.Pix}}
+})
+
+// timeout bounds connecting to the bus and each call.
+var timeout = 2 * time.Second
+
+// Notifier shows notifications. It connects to the bus at the first one and keeps that connection, so it hears
+// the click (ActionInvoked comes to the connection that sent the notification). The zero value is not usable:
+// set Address (empty: the user's session bus, dbus.SessionAddress) and OnClick.
+type Notifier struct {
+ Address string
+ AppName string // the name the notification service shows
+ OnClick func() // a notification of this Notifier was clicked; called on a goroutine of its own
+ Log func(level, msg string)
+
+ mu sync.Mutex // one Show at a time; guards conn
+ conn *dbus.Conn
+ idMu sync.Mutex // guards ids (apart from mu: a signal can come while Show waits for its answer)
+ ids map[uint32]bool // notifications shown and not closed yet
+}
+
+// Show shows a notification with a title and a line of text, and reports whether the notification service took it.
+// With no session bus or no notification service it returns false.
+func (n *Notifier) Show(title, text string) bool {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ // A connection kept from earlier may have ended meanwhile: one new try, but only then (the connection ended, or
+ // the call could not be sent). A service that is slow to answer (one the bus starts on demand) may still show the
+ // notification: a second try would show it twice.
+ for try := 0; try < 2; try++ {
+ if n.conn == nil {
+ if err := n.connect(); err != nil {
+ n.log("INFO", "No desktop notification service ("+err.Error()+").")
+ return false
+ }
+ }
+ // actions: a click on the notification (the default action; its label is shown by services that show it as
+ // a button); hints: the logo; expire_timeout -1: the service decides how long it stays
+ got, err := n.conn.CallStart(service, object, service, "Notify", timeout, "susssasa{sv}i",
+ n.AppName, uint32(0), "", title, text, []string{defaultAction, "Open settings"}, map[string]any{"image-data": icon()}, int32(-1))
+ if err == nil {
+ if len(got) > 0 {
+ if id, ok := got[0].(uint32); ok && id != 0 {
+ n.idMu.Lock()
+ n.ids[id] = true
+ n.idMu.Unlock()
+ }
+ }
+ return true
+ }
+ var de *dbus.Error
+ if errors.As(err, &de) { // the bus answered: there is no notification service, or it refused
+ n.log("INFO", "The desktop notification service did not show the notification ("+err.Error()+").")
+ return false
+ }
+ if errors.Is(err, dbus.ErrNoAnswer) { // the connection is kept: a later answer is simply dropped
+ n.log("INFO", "The desktop notification service did not answer in time ("+err.Error()+").")
+ return false
+ }
+ n.conn.Close()
+ n.conn = nil
+ }
+ return false
+}
+
+// connect opens the connection and listens for the clicks and closings of notifications. n.mu is held.
+func (n *Notifier) connect() error {
+ addr := n.Address
+ if addr == "" {
+ addr = dbus.SessionAddress()
+ }
+ if addr == "" {
+ return errors.New("no session bus")
+ }
+ c, err := dbus.Dial(addr, timeout)
+ if err != nil {
+ return err
+ }
+ n.idMu.Lock()
+ n.ids = map[uint32]bool{}
+ n.idMu.Unlock()
+ c.Receive(n.signal)
+ // the signals of the notification service (most services send them to the sender alone, some to everyone)
+ rule := "type='signal',sender='" + service + "',interface='" + service + "',path='" + object + "'"
+ if _, err := c.Call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "AddMatch", timeout, "s", rule); err != nil {
+ c.Close()
+ return err
+ }
+ n.conn = c
+ return nil
+}
+
+// signal handles a signal of the notification service: a click on one of ours opens the window.
+func (n *Notifier) signal(m *dbus.Message) {
+ if m.Interface != service || len(m.Body) < 2 {
+ return
+ }
+ id, _ := m.Body[0].(uint32)
+ n.idMu.Lock()
+ ours := n.ids[id]
+ switch m.Member {
+ case "ActionInvoked":
+ if key, _ := m.Body[1].(string); key != defaultAction {
+ ours = false
+ }
+ case "NotificationClosed":
+ delete(n.ids, id)
+ ours = false
+ default:
+ ours = false
+ }
+ n.idMu.Unlock()
+ if ours && n.OnClick != nil {
+ go n.OnClick()
+ }
+}
+
+// Close ends the connection (when the program quits).
+func (n *Notifier) Close() {
+ if n == nil {
+ return
+ }
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ if n.conn != nil {
+ n.conn.Close()
+ n.conn = nil
+ }
+}
+
+func (n *Notifier) log(level, msg string) {
+ if n.Log != nil {
+ n.Log(level, msg)
+ }
+}
diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go
new file mode 100644
index 0000000..92f117f
--- /dev/null
+++ b/internal/notify/notify_test.go
@@ -0,0 +1,232 @@
+package notify
+
+import (
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/CptPakundo/MPRP/internal/dbus"
+ "github.com/CptPakundo/MPRP/internal/dbus/dbustest"
+ "github.com/CptPakundo/MPRP/internal/logo"
+)
+
+func keys(m map[string]any) []string {
+ var out []string
+ for k := range m {
+ out = append(out, k)
+ }
+ return out
+}
+
+// fakeService puts a notification service on the fake bus and records what it is asked.
+type fakeService struct {
+ mu sync.Mutex
+ got []*dbus.Message
+ next uint32
+ error string // answer every Notify with this error
+ delay time.Duration // answer this late (a service the bus starts on demand)
+}
+
+func (f *fakeService) handle(m *dbus.Message) dbustest.Reply {
+ f.mu.Lock()
+ f.got = append(f.got, m)
+ errName, delay := f.error, f.delay
+ f.next++
+ id := f.next
+ f.mu.Unlock()
+ time.Sleep(delay)
+ if errName != "" {
+ return dbustest.Reply{Error: errName}
+ }
+ return dbustest.Reply{Sig: "u", Body: []any{id}}
+}
+
+func (f *fakeService) setDelay(d time.Duration) {
+ f.mu.Lock()
+ f.delay = d
+ f.mu.Unlock()
+}
+
+func (f *fakeService) messages() []*dbus.Message {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]*dbus.Message(nil), f.got...)
+}
+
+func signal(member string, body ...any) *dbus.Message {
+ sig := "uu"
+ if member == "ActionInvoked" {
+ sig = "us"
+ }
+ return &dbus.Message{Serial: 77, Path: object, Interface: service, Member: member, Sender: service, Signature: sig, Body: body}
+}
+
+func TestShowSendsNotify(t *testing.T) {
+ bus := dbustest.New(t)
+ f := &fakeService{}
+ bus.Own(service, f.handle)
+ n := &Notifier{Address: bus.Address, AppName: "MPRP"}
+ defer n.Close()
+ if !n.Show("MPRP 9.9.9 is available", "You have 9.9.8. Click here to see what's new and install it.") {
+ t.Fatal("Show = false with a notification service on the bus")
+ }
+ got := f.messages()
+ if len(got) != 1 {
+ t.Fatalf("%d calls, want 1", len(got))
+ }
+ m := got[0]
+ if m.Path != object || m.Interface != service || m.Member != "Notify" || m.Signature != "susssasa{sv}i" {
+ t.Errorf("call %s %s.%s (%s)", m.Path, m.Interface, m.Member, m.Signature)
+ }
+ if m.Flags&dbus.FlagNoAutoStart != 0 {
+ t.Error("Notify must let the bus start a notification service that starts on demand")
+ }
+ hints, _ := m.Body[6].(map[string]any)
+ img, _ := hints["image-data"].([]any)
+ if len(hints) != 1 || len(img) != 7 {
+ t.Fatalf("hints %v: want image-data alone", keys(hints))
+ }
+ // the logo as the specification's raw image: width, height, row stride, has alpha, 8 bits per sample, 4 channels
+ if !reflect.DeepEqual(img[:6], []any{int32(128), int32(128), int32(512), true, int32(8), int32(4)}) {
+ t.Errorf("image-data header %v", img[:6])
+ }
+ pix := logo.Image(128, false).Pix
+ data, _ := img[6].([]any)
+ if len(data) != len(pix) {
+ t.Fatalf("%d bytes of pixels, want %d", len(data), len(pix))
+ }
+ for i, b := range data {
+ if b != any(pix[i]) {
+ t.Fatalf("pixel byte %d = %v, want %d (the logo, RGBA)", i, b, pix[i])
+ }
+ }
+ body := append([]any(nil), m.Body...)
+ body[6] = nil
+ want := []any{"MPRP", uint32(0), "", "MPRP 9.9.9 is available", "You have 9.9.8. Click here to see what's new and install it.",
+ []any{"default", "Open settings"}, nil, int32(-1)}
+ if !reflect.DeepEqual(body, want) {
+ t.Errorf("body\n got %#v\nwant %#v", body, want)
+ }
+ // the connection is kept for the next one (and for the clicks)
+ if !n.Show("second", "text") || len(f.messages()) != 2 {
+ t.Error("a second notification was not shown")
+ }
+ hello := 0
+ for _, c := range bus.Calls() {
+ if c == "org.freedesktop.DBus org.freedesktop.DBus.Hello" {
+ hello++
+ }
+ }
+ if hello != 1 {
+ t.Errorf("%d connections, want 1 kept", hello)
+ }
+}
+
+func TestClickCallsBack(t *testing.T) {
+ bus := dbustest.New(t)
+ f := &fakeService{}
+ bus.Own(service, f.handle)
+ clicked := make(chan struct{}, 4)
+ n := &Notifier{Address: bus.Address, OnClick: func() { clicked <- struct{}{} }}
+ defer n.Close()
+ if !n.Show("title", "text") { // id 1
+ t.Fatal("Show = false")
+ }
+ bus.Emit(signal("ActionInvoked", uint32(9), "default")) // someone else's notification
+ bus.Emit(signal("ActionInvoked", uint32(1), "other")) // another action of ours
+ bus.Emit(signal("ActionInvoked", uint32(1), "default"))
+ select {
+ case <-clicked:
+ case <-time.After(2 * time.Second):
+ t.Fatal("a click on the notification did not call back")
+ }
+ select {
+ case <-clicked:
+ t.Fatal("a click on another notification or another action called back")
+ case <-time.After(200 * time.Millisecond):
+ }
+ // once closed, its id may be reused by the service for another program's notification
+ bus.Emit(signal("NotificationClosed", uint32(1), uint32(2)))
+ time.Sleep(100 * time.Millisecond)
+ bus.Emit(signal("ActionInvoked", uint32(1), "default"))
+ select {
+ case <-clicked:
+ t.Fatal("a closed notification's id still called back")
+ case <-time.After(200 * time.Millisecond):
+ }
+}
+
+func TestNoService(t *testing.T) {
+ bus := dbustest.New(t) // a bus without a notification service
+ n := &Notifier{Address: bus.Address}
+ defer n.Close()
+ if n.Show("title", "text") {
+ t.Error("Show = true without a notification service")
+ }
+ f := &fakeService{error: "org.freedesktop.DBus.Error.AccessDenied"}
+ bus.Own(service, f.handle)
+ if n.Show("title", "text") {
+ t.Error("Show = true although the service refused")
+ }
+ none := &Notifier{Address: "unix:path=/nonexistent/socket/here"}
+ if none.Show("title", "text") {
+ t.Error("Show = true without a bus")
+ }
+}
+
+// A connection that ended (the bus restarted) is replaced at the next notification.
+func TestReconnects(t *testing.T) {
+ bus := dbustest.New(t)
+ f := &fakeService{}
+ bus.Own(service, f.handle)
+ n := &Notifier{Address: bus.Address}
+ defer n.Close()
+ if !n.Show("one", "text") {
+ t.Fatal("Show = false")
+ }
+ n.mu.Lock()
+ n.conn.Close() // as if the bus had dropped it
+ n.mu.Unlock()
+ time.Sleep(50 * time.Millisecond)
+ if !n.Show("two", "text") {
+ t.Fatal("Show = false after the connection ended")
+ }
+ if len(f.messages()) != 2 {
+ t.Errorf("%d notifications, want 2", len(f.messages()))
+ }
+}
+
+// A service that answers late is not asked a second time on a new connection: it may still show the notification,
+// and would then show it twice. The connection is kept for the next notification.
+func TestSlowServiceIsAskedOnce(t *testing.T) {
+ saved := timeout
+ timeout = 300 * time.Millisecond
+ t.Cleanup(func() { timeout = saved })
+ bus := dbustest.New(t)
+ f := &fakeService{}
+ bus.Own(service, f.handle)
+ n := &Notifier{Address: bus.Address}
+ defer n.Close()
+ f.setDelay(700 * time.Millisecond)
+ if n.Show("slow", "text") {
+ t.Error("Show = true without an answer")
+ }
+ time.Sleep(time.Second) // a second Notify, if one were sent, has arrived by now
+ if got := len(f.messages()); got != 1 {
+ t.Fatalf("%d Notify calls, want 1", got)
+ }
+ f.setDelay(0)
+ if !n.Show("fast", "text") || len(f.messages()) != 2 {
+ t.Error("the next notification was not shown")
+ }
+ hello := 0
+ for _, c := range bus.Calls() {
+ if c == "org.freedesktop.DBus org.freedesktop.DBus.Hello" {
+ hello++
+ }
+ }
+ if hello != 1 {
+ t.Errorf("%d connections, want 1 kept", hello)
+ }
+}
diff --git a/internal/pipe/dial_windows_test.go b/internal/pipe/dial_windows_test.go
index de0396c..8c9937a 100644
--- a/internal/pipe/dial_windows_test.go
+++ b/internal/pipe/dial_windows_test.go
@@ -17,7 +17,7 @@ func TestDialWaitsForAFreeInstance(t *testing.T) {
busyWait = 10 * time.Second
t.Cleanup(func() { busyWait = old })
- path := `\\?\pipe\mpcvibedrpc-test-busy-` + strconv.Itoa(os.Getpid())
+ path := `\\?\pipe\mprp-test-busy-` + strconv.Itoa(os.Getpid())
defer listenPipe(t, path)()
a, err := Dial(path)
if err != nil {
@@ -61,7 +61,7 @@ func TestDialGivesUpOnABusyPipe(t *testing.T) {
busyWait = 300 * time.Millisecond
t.Cleanup(func() { busyWait = old })
- path := `\\?\pipe\mpcvibedrpc-test-full-` + strconv.Itoa(os.Getpid())
+ path := `\\?\pipe\mprp-test-full-` + strconv.Itoa(os.Getpid())
defer listenPipe(t, path)()
a, err := Dial(path)
if err != nil {
diff --git a/internal/pipe/exists_test.go b/internal/pipe/exists_test.go
index 27e77ee..a9c3856 100644
--- a/internal/pipe/exists_test.go
+++ b/internal/pipe/exists_test.go
@@ -11,7 +11,7 @@ import (
)
func TestExists(t *testing.T) {
- name := "mpcvibedrpc-test-" + strconv.Itoa(os.Getpid()) + "-" + strconv.FormatInt(time.Now().UnixNano(), 36)
+ name := "mprp-test-" + strconv.Itoa(os.Getpid()) + "-" + strconv.FormatInt(time.Now().UnixNano(), 36)
var path string
if runtime.GOOS == "windows" {
path = `\\?\pipe\` + name
diff --git a/internal/plex/account.go b/internal/plex/account.go
index 4f34954..8941251 100644
--- a/internal/plex/account.go
+++ b/internal/plex/account.go
@@ -15,11 +15,11 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
// Product is how the program introduces itself to Plex (it is shown in the account's list of authorized devices).
-const Product = "MPCvibedRPC"
+const Product = "MPRP"
var (
// ErrPinExpired means the sign-in code ran out before it was approved (or plex.tv no longer knows it).
diff --git a/internal/plex/meta.go b/internal/plex/meta.go
index 6649706..5242c1a 100644
--- a/internal/plex/meta.go
+++ b/internal/plex/meta.go
@@ -3,7 +3,7 @@ package plex
import (
"regexp"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Item is what the server says about the video being played (library metadata; only the parts used).
diff --git a/internal/plex/plex_test.go b/internal/plex/plex_test.go
index f03aa4f..3a1444a 100644
--- a/internal/plex/plex_test.go
+++ b/internal/plex/plex_test.go
@@ -56,7 +56,7 @@ func fakeTV(t *testing.T, resources string) (*httptest.Server, *int) {
}
switch {
case r.Method == "POST" && r.URL.Path == "/api/v2/pins" && r.URL.Query().Get("strong") == "true":
- fmt.Fprint(w, `{"id":4242,"code":"samplecode","product":"MPCvibedRPC","trusted":false,"clientIdentifier":"test-client","expiresIn":1800,"authToken":null,"newRegistration":null}`)
+ fmt.Fprint(w, `{"id":4242,"code":"samplecode","product":"MPRP","trusted":false,"clientIdentifier":"test-client","expiresIn":1800,"authToken":null,"newRegistration":null}`)
case r.Method == "GET" && r.URL.Path == "/api/v2/pins/4242":
checks++
if checks < 3 {
diff --git a/internal/plex/watcher.go b/internal/plex/watcher.go
index 10818ad..24c4fcb 100644
--- a/internal/plex/watcher.go
+++ b/internal/plex/watcher.go
@@ -13,8 +13,8 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
// How long a player may stay silent before what it played is forgotten (players report every few seconds while they
diff --git a/internal/potplayer/live_windows_test.go b/internal/potplayer/live_windows_test.go
index f6226ee..9c09527 100644
--- a/internal/potplayer/live_windows_test.go
+++ b/internal/potplayer/live_windows_test.go
@@ -6,11 +6,11 @@ import (
"testing"
)
-// TestLivePotPlayer asks a real PotPlayer on this computer (opt-in: MPCRPC_LIVE_POTPLAYER=1, with a local file playing)
+// TestLivePotPlayer asks a real PotPlayer on this computer (opt-in: MPRP_LIVE_POTPLAYER=1, with a local file playing)
// and checks that it sends the file's path, so the Never show list can match folders.
func TestLivePotPlayer(t *testing.T) {
- if os.Getenv("MPCRPC_LIVE_POTPLAYER") == "" {
- t.Skip("set MPCRPC_LIVE_POTPLAYER=1 with PotPlayer playing a local file")
+ if os.Getenv("MPRP_LIVE_POTPLAYER") == "" {
+ t.Skip("set MPRP_LIVE_POTPLAYER=1 with PotPlayer playing a local file")
}
found := Query()
for _, in := range found {
diff --git a/internal/potplayer/potplayer.go b/internal/potplayer/potplayer.go
index b7f4b92..f774c32 100644
--- a/internal/potplayer/potplayer.go
+++ b/internal/potplayer/potplayer.go
@@ -6,7 +6,7 @@ package potplayer
import (
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The messages PotPlayer is asked with are in potplayer_windows.go; info below only needs their answers.
diff --git a/internal/potplayer/potplayer_other.go b/internal/potplayer/potplayer_other.go
index 8518cb3..467bdef 100644
--- a/internal/potplayer/potplayer_other.go
+++ b/internal/potplayer/potplayer_other.go
@@ -2,7 +2,7 @@
package potplayer
-import "github.com/CptPakundo/MPCvibedRPC/internal/core"
+import "github.com/CptPakundo/MPRP/internal/core"
// Query finds no PotPlayer outside Windows.
func Query() []*core.Info { return nil }
diff --git a/internal/potplayer/potplayer_windows.go b/internal/potplayer/potplayer_windows.go
index 38324ea..2fa88a3 100644
--- a/internal/potplayer/potplayer_windows.go
+++ b/internal/potplayer/potplayer_windows.go
@@ -9,7 +9,7 @@ import (
"time"
"unsafe"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// The messages, sent as WM_USER with one of these in wParam. The answers come back as the result, except the file
@@ -96,7 +96,7 @@ var (
func setup() {
hinst, _, _ = pGetModuleHandle.Call(0)
- replyCls, _ = syscall.UTF16PtrFromString("MPCvibedRPC.PotPlayerReply")
+ replyCls, _ = syscall.UTF16PtrFromString("MPRP.PotPlayerReply")
wc := wndClassEx{lpfnWndProc: syscall.NewCallback(replyProc), hInstance: hinst, lpszClassName: replyCls}
wc.cbSize = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
diff --git a/internal/potplayer/potplayer_windows_test.go b/internal/potplayer/potplayer_windows_test.go
index 833888a..f6a839f 100644
--- a/internal/potplayer/potplayer_windows_test.go
+++ b/internal/potplayer/potplayer_windows_test.go
@@ -7,7 +7,7 @@ import (
"testing"
"unsafe"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
var (
diff --git a/internal/server/icon_test.go b/internal/server/icon_test.go
new file mode 100644
index 0000000..468a66f
--- /dev/null
+++ b/internal/server/icon_test.go
@@ -0,0 +1,28 @@
+package server
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// The page names its icons with the version in their addresses (a browser profile keeps a page's icon and would go
+// on showing an older logo), and /icon.png serves the large logo.
+func TestPageIconAddresses(t *testing.T) {
+ s := New(Options{Token: "tok", Page: ``,
+ Icon: []byte("ICO"), IconPNG: []byte("PNG"), Version: "9.9.9"})
+ if _, err := s.Listen(0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(s.Close)
+ base := "http://127.0.0.1:" + strconv.Itoa(s.Port())
+ if code, body, _ := do(t, "GET", base+"/?t=tok", "", nil, ""); code != 200 || strings.Count(body, "?v=9.9.9") != 2 || strings.Contains(body, "__VERSION__") {
+ t.Errorf("page: %d %s", code, body)
+ }
+ if code, body, hdr := do(t, "GET", base+"/icon.png?v=9.9.9", "", nil, ""); code != 200 || body != "PNG" || hdr.Get("Content-Type") != "image/png" {
+ t.Errorf("icon.png: %d %q %s", code, body, hdr.Get("Content-Type"))
+ }
+ if code, body, _ := do(t, "GET", base+"/icon.ico?v=9.9.9", "", nil, ""); code != 200 || body != "ICO" {
+ t.Errorf("icon.ico: %d %q", code, body)
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index ffc5429..9951fc1 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -14,13 +14,15 @@ import (
"io"
"net"
"net/http"
+ "net/url"
"os"
"strconv"
"strings"
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
)
// NewToken makes a random token.
@@ -41,10 +43,11 @@ type Handler struct {
// Options configures a Server.
type Options struct {
Token string
- Page string // the settings page; __TOKEN__ is replaced by the token (it sits in a meta tag the script reads)
+ Page string // the settings page; __TOKEN__ is replaced by the token (it sits in a meta tag the script reads), __VERSION__ by Version
CSS string // the page's style sheet, served as /ui.css
JS string // the page's script, served as /ui.js
Icon []byte
+ IconPNG []byte // the logo as a large PNG (/icon.png): the browser window's own icon, sharp on the taskbar
Handlers map[string]Handler
Version string
// OnWindow is told when a settings window opens (true) and closes (false): each open window holds /api/alive.
@@ -143,11 +146,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
switch {
case r.Method == "GET" && p == "/api/ping":
- send(w, 200, map[string]any{"app": "MPCvibedRPC", "version": s.o.Version, "pid": os.Getpid()}, jsonType)
+ send(w, 200, map[string]any{"app": core.Name, "version": s.o.Version, "pid": os.Getpid()}, jsonType)
return
case r.Method == "GET" && p == "/icon.ico":
send(w, 200, s.o.Icon, "image/x-icon")
return
+ case r.Method == "GET" && p == "/icon.png" && len(s.o.IconPNG) > 0:
+ send(w, 200, s.o.IconPNG, "image/png")
+ return
case r.Method == "GET" && p == "/ui.css":
send(w, 200, s.o.CSS, "text/css; charset=utf-8")
return
@@ -162,7 +168,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// Without a code the page still comes, with no token in it: a window that reloads has kept its token (the
// script takes the code out of its address), and anyone else is told how to open the window.
- send(w, 200, strings.Replace(s.o.Page, "__TOKEN__", token, 1), "text/html; charset=utf-8")
+ page := strings.ReplaceAll(strings.Replace(s.o.Page, "__TOKEN__", token, 1), "__VERSION__", url.QueryEscape(s.o.Version))
+ send(w, 200, page, "text/html; charset=utf-8")
return
}
if !strings.HasPrefix(p, "/api/") {
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
index 4d2e4b5..58b6ff1 100644
--- a/internal/server/server_test.go
+++ b/internal/server/server_test.go
@@ -13,7 +13,7 @@ import (
"testing"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
)
type valErr struct{}
@@ -62,7 +62,7 @@ func TestServer(t *testing.T) {
_ = s
tok := map[string]string{"X-Token": "tok"}
- if c, b, h := do(t, "GET", base+"/api/ping", "", nil, ""); c != 200 || b != fmt.Sprintf(`{"app":"MPCvibedRPC","pid":%d,"version":"9.9.9"}`, os.Getpid()) || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Content-Security-Policy") == "" {
+ if c, b, h := do(t, "GET", base+"/api/ping", "", nil, ""); c != 200 || b != fmt.Sprintf(`{"app":"MPRP","pid":%d,"version":"9.9.9"}`, os.Getpid()) || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Content-Security-Policy") == "" {
t.Fatal(c, b)
}
if c, b, _ := do(t, "GET", base+"/icon.ico", "", nil, ""); c != 200 || b != "ICO" {
diff --git a/internal/store/clientid_test.go b/internal/store/clientid_test.go
new file mode 100644
index 0000000..7df94be
--- /dev/null
+++ b/internal/store/clientid_test.go
@@ -0,0 +1,32 @@
+package store
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// An install that saved the former default Discord application uses the project's own; one of the user's own stays.
+func TestFormerClientIDReadsAsTheDefault(t *testing.T) {
+ for _, c := range []struct{ saved, want string }{
+ {core.FormerClientID, core.DefaultClientID},
+ {"123456789012345678", "123456789012345678"},
+ } {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"clientId": "`+c.saved+`"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ s := openStore(t, dir)
+ if got := s.Config().ClientID; got != c.want {
+ t.Errorf("saved %s: engine uses %s, want %s", c.saved, got, c.want)
+ }
+ if got, _ := s.SettingsObj().M["clientId"].(string); got != c.want {
+ t.Errorf("saved %s: the window shows %s, want %s", c.saved, got, c.want)
+ }
+ }
+ if core.DefaultConfig().ClientID != core.DefaultClientID {
+ t.Error("the default clientId is not DefaultClientID")
+ }
+}
diff --git a/internal/store/docs_test.go b/internal/store/docs_test.go
index 5fc8603..88cb593 100644
--- a/internal/store/docs_test.go
+++ b/internal/store/docs_test.go
@@ -9,7 +9,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Every setting, with its default, has a row in docs/config.md: the program's settings (core.Config) and its own
@@ -33,15 +33,17 @@ func TestEverySettingIsDocumented(t *testing.T) {
}
}
check := func(v reflect.Value) {
- rt := v.Type()
- for i := 0; i < rt.NumField(); i++ {
- key := strings.Split(rt.Field(i).Tag.Get("json"), ",")[0]
+ for _, f := range reflect.VisibleFields(v.Type()) {
+ if f.Anonymous {
+ continue // a group of core.Config: its settings come next
+ }
+ key := strings.Split(f.Tag.Get("json"), ",")[0]
cell, ok := rows[key]
if !ok {
t.Errorf("%s has no row in docs/config.md", key)
continue
}
- if want, got := docDefault(cell), codeDefault(v.Field(i)); want != got && got != "?" && cell != "?" {
+ if want, got := docDefault(cell), codeDefault(v.FieldByIndex(f.Index)); want != got && got != "?" && cell != "?" {
t.Errorf("%s: docs/config.md says the default is %q, the code says %q", key, want, got)
}
}
diff --git a/internal/store/fixes.go b/internal/store/fixes.go
new file mode 100644
index 0000000..7145175
--- /dev/null
+++ b/internal/store/fixes.go
@@ -0,0 +1,300 @@
+package store
+
+import (
+ "fmt"
+ "math"
+ "strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+)
+
+// limits for Fix a match and the custom text lines
+const (
+ maxFixes = 500
+ maxOffset = 500
+ maxCoverLen = 256 // the cover finder takes image addresses up to this length
+ maxLineChars = 300
+)
+
+// cleanFixes validates Fix a match's list from the window (see core.MatchFix): each fix needs the title (or file name)
+// it is for, and at most one of a catalog page or another name to search; the cover is an http(s) image address. A
+// second fix for the same title (or file) replaces the first. Stored in a fixed key order, without empty fields.
+func cleanFixes(f Field, v any) (any, error) {
+ var arr []any
+ switch x := v.(type) {
+ case nil:
+ case []any:
+ arr = x
+ default:
+ return nil, &ValidationError{f.Label + ": expected a list of fixes"}
+ }
+ bad := func(msg string) error { return &ValidationError{f.Label + ": " + msg} }
+ var out []*jsonx.Obj
+ at := map[string]int{}
+ for _, e := range arr {
+ o, ok := e.(*jsonx.Obj)
+ if !ok {
+ return nil, bad("every fix must be an object")
+ }
+ text := func(key string, max int) (string, error) {
+ raw, present := o.M[key]
+ if !present || raw == nil {
+ return "", nil
+ }
+ s, ok := raw.(string)
+ if !ok {
+ return "", bad(key + " must be text")
+ }
+ s = jsTrim(s)
+ if hasControl(s) {
+ return "", bad(key + " must not contain control characters")
+ }
+ if len([]rune(s)) > max {
+ return "", bad(fmt.Sprintf("%s is longer than %d characters", key, max))
+ }
+ return s, nil
+ }
+ address := func(key string, max int) (string, error) {
+ s, err := text(key, max)
+ if err == nil && s != "" && !strings.HasPrefix(s, "https://") && !strings.HasPrefix(s, "http://") {
+ err = bad(key + " must be an http(s) address")
+ }
+ return s, err
+ }
+ offset := func(key string) (int, error) {
+ raw, present := o.M[key]
+ if !present || raw == nil || isBlank(raw) {
+ return 0, nil
+ }
+ n := jsNumber(raw)
+ if math.IsNaN(n) || n != math.Trunc(n) || math.Abs(n) > maxOffset {
+ return 0, bad(fmt.Sprintf("an offset must be a whole number from -%d to %d", maxOffset, maxOffset))
+ }
+ return int(n), nil
+ }
+ var fx core.MatchFix
+ var err error
+ if fx.Match, err = text("match", maxLineLen); err != nil {
+ return nil, err
+ }
+ if fx.Match == "" {
+ return nil, bad("every fix needs the title or file name it is for")
+ }
+ fx.File, _ = o.M["file"].(bool)
+ if fx.Entry, err = address("entry", 512); err != nil {
+ return nil, err
+ }
+ if _, ok := core.EntryPage(fx.Entry); fx.Entry != "" && !ok {
+ return nil, bad("the pinned entry must be an IMDb, TMDB, TVmaze, AniList or Kitsu page")
+ }
+ if fx.Search, err = text("search", maxLineLen); err != nil {
+ return nil, err
+ }
+ if fx.Entry != "" {
+ fx.Search = "" // a pinned entry needs no other name
+ }
+ if fx.Cover, err = address("cover", maxCoverLen); err != nil {
+ return nil, err
+ }
+ if fx.SeasonOffset, err = offset("seasonOffset"); err != nil {
+ return nil, err
+ }
+ if fx.EpisodeOffset, err = offset("episodeOffset"); err != nil {
+ return nil, err
+ }
+ if fx.Label, err = text("label", maxLineLen); err != nil {
+ return nil, err
+ }
+ if fx.Poster, err = address("poster", 512); err != nil {
+ return nil, err
+ }
+ key := fmt.Sprint(fx.File, "|", strings.ToLower(fx.Match))
+ if i, dup := at[key]; dup {
+ out[i] = fixObj(fx)
+ continue
+ }
+ at[key] = len(out)
+ out = append(out, fixObj(fx))
+ }
+ if len(out) > maxFixes {
+ return nil, bad(fmt.Sprintf("at most %d fixes", maxFixes))
+ }
+ list := make([]any, len(out))
+ for i, o := range out {
+ list[i] = o
+ }
+ return list, nil
+}
+
+// fixObj is a fix as config.json stores it.
+func fixObj(fx core.MatchFix) *jsonx.Obj {
+ o := jsonx.NewObj()
+ o.Set("match", fx.Match)
+ if fx.File {
+ o.Set("file", true)
+ }
+ for _, kv := range [][2]string{{"entry", fx.Entry}, {"search", fx.Search}, {"cover", fx.Cover}} {
+ if kv[1] != "" {
+ o.Set(kv[0], kv[1])
+ }
+ }
+ if fx.SeasonOffset != 0 {
+ o.Set("seasonOffset", float64(fx.SeasonOffset))
+ }
+ if fx.EpisodeOffset != 0 {
+ o.Set("episodeOffset", float64(fx.EpisodeOffset))
+ }
+ if fx.Label != "" {
+ o.Set("label", fx.Label)
+ }
+ if fx.Poster != "" {
+ o.Set("poster", fx.Poster)
+ }
+ return o
+}
+
+// cleanTextLines validates the custom text lines: an object with the keys of core.CustomLineKeys (others are refused),
+// each a line of text. Empty lines are left out (a missing line is an empty one).
+func cleanTextLines(f Field, v any) (any, error) {
+ out := jsonx.NewObj()
+ if v == nil {
+ return out, nil
+ }
+ o, ok := v.(*jsonx.Obj)
+ if !ok {
+ return nil, &ValidationError{f.Label + ": expected an object"}
+ }
+ known := map[string]bool{}
+ for _, k := range core.CustomLineKeys {
+ known[k] = true
+ }
+ for _, k := range o.Keys {
+ if !known[k] {
+ return nil, &ValidationError{f.Label + ": unknown line " + k}
+ }
+ }
+ for _, k := range core.CustomLineKeys {
+ raw, present := o.M[k]
+ if !present || raw == nil {
+ continue
+ }
+ s, ok := raw.(string)
+ if !ok {
+ return nil, &ValidationError{f.Label + ": every line must be text"}
+ }
+ s = jsTrim(s)
+ if hasControl(s) {
+ return nil, &ValidationError{f.Label + ": a line must not contain line breaks or other control characters"}
+ }
+ if len([]rune(s)) > maxLineChars {
+ return nil, &ValidationError{fmt.Sprintf("%s: a line is longer than %d characters", f.Label, maxLineChars)}
+ }
+ if s != "" {
+ out.Set(k, s)
+ }
+ }
+ return out, nil
+}
+
+// MigrateMatchFixes writes the legacy Fix a match lines (artworkAliases, artworkOverrides) as matchFixes, once: only
+// while config.json has no matchFixes key. Each title becomes one fix (the alias as its search, the pinned cover as
+// its cover), in the file's order. The old keys stay in the file, for a downgrade, and are not read again. Each fix
+// is made to pass the window's rules first (fitFix), since the window saves the whole list: a fix it refuses would make
+// every later save fail. It returns how many fixes were written, and whether the matchFixes key was written (also
+// with no fix in it, when every old line was left out): then the program's fixes have changed.
+func (s *Store) MigrateMatchFixes() (n int, wrote bool, err error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ cur, err := s.read()
+ if err != nil {
+ return 0, false, err
+ }
+ if _, has := cur.M["matchFixes"]; has {
+ return 0, false, nil
+ }
+ var order []string
+ fixes := map[string]*core.MatchFix{}
+ for _, src := range []string{"artworkAliases", "artworkOverrides"} {
+ m, ok := cur.M[src].(*jsonx.Obj)
+ if !ok {
+ continue
+ }
+ for _, k := range m.Keys {
+ val, _ := m.M[k].(string)
+ if jsTrim(k) == "" || val == "" {
+ continue
+ }
+ fx := fixes[k]
+ if fx == nil {
+ fx = &core.MatchFix{Match: k}
+ fixes[k] = fx
+ order = append(order, k)
+ }
+ if src == "artworkAliases" {
+ fx.Search = val
+ } else {
+ fx.Cover = val
+ }
+ }
+ }
+ if len(order) == 0 {
+ return 0, false, nil
+ }
+ var list []any
+ changed, skipped := 0, 0
+ for _, k := range order {
+ fx, ok, ch := fitFix(*fixes[k])
+ switch {
+ case !ok || len(list) == maxFixes:
+ skipped++
+ continue
+ case ch:
+ changed++
+ }
+ list = append(list, fixObj(fx))
+ }
+ if changed+skipped > 0 {
+ s.logf("WARN", fmt.Sprintf("Fix a match: %d of the old artworkAliases and artworkOverrides titles were changed to fit the rules "+
+ "(a cover that is not an http(s) address left out, text over its limit shortened) and %d were left out.", changed, skipped))
+ }
+ // an empty list is written too: the old lines, which the window could not save, are then no longer read
+ if list == nil {
+ list = []any{}
+ }
+ cur.Set("matchFixes", list)
+ if err := s.write(cur); err != nil {
+ return 0, false, err
+ }
+ return len(list), true, nil
+}
+
+// fitFix makes a fix carried over from the old Fix a match lines one that cleanFixes takes: the text trimmed, text
+// over its limit shortened, a field that still cannot pass (control characters; a cover that is not an http(s)
+// address or is too long, which could never show on Discord anyway) left out. ok is false when nothing is left to
+// act on (no title, or neither another name nor a cover); changed says that a field had to be changed beyond the
+// trimming.
+func fitFix(in core.MatchFix) (fx core.MatchFix, ok, changed bool) {
+ text := func(s string, max int) string {
+ s = jsTrim(s)
+ if hasControl(s) {
+ changed = true
+ return ""
+ }
+ if r := []rune(s); len(r) > max {
+ changed = true
+ s = jsTrim(string(r[:max]))
+ }
+ return s
+ }
+ fx.Match = text(in.Match, maxLineLen)
+ fx.Search = text(in.Search, maxLineLen)
+ if c := jsTrim(in.Cover); c != "" {
+ if hasControl(c) || len([]rune(c)) > maxCoverLen || !(strings.HasPrefix(c, "https://") || strings.HasPrefix(c, "http://")) {
+ changed = true
+ } else {
+ fx.Cover = c
+ }
+ }
+ return fx, fx.Match != "" && (fx.Search != "" || fx.Cover != ""), changed
+}
diff --git a/internal/store/fixes_test.go b/internal/store/fixes_test.go
new file mode 100644
index 0000000..8c1efda
--- /dev/null
+++ b/internal/store/fixes_test.go
@@ -0,0 +1,219 @@
+package store
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// The legacy Fix a match lines become fixes once: a title in both maps is one fix, the old keys stay in the file, and
+// a second start changes nothing.
+func TestMigrateMatchFixes(t *testing.T) {
+ dir := t.TempDir()
+ old := `{
+ "artworkAliases": {"sample movie": "Sample Film", "sample show": "Sample Series"},
+ "artworkOverrides": {"sample show": "https://img.example/show.jpg", "another sample": "https://img.example/another.jpg"},
+ "titleAsName": false
+}`
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(old), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s := openStore(t, dir)
+ c0 := s.Config()
+ legacy := c0.Fixes() // what the program used before the migration: the maps read as fixes
+ n, wrote, err := s.MigrateMatchFixes()
+ if err != nil || n != 3 || !wrote {
+ t.Fatalf("migrated %d (written %v, %v), want 3 titles", n, wrote, err)
+ }
+ cfg := s.Config()
+ want := []core.MatchFix{
+ {Match: "sample movie", Search: "Sample Film"},
+ {Match: "sample show", Search: "Sample Series", Cover: "https://img.example/show.jpg"},
+ {Match: "another sample", Cover: "https://img.example/another.jpg"},
+ }
+ if !reflect.DeepEqual(cfg.MatchFixes, want) {
+ t.Errorf("matchFixes = %+v\nwant %+v", cfg.MatchFixes, want)
+ }
+ if len(legacy) != 3 || !sameFixes(legacy, want) {
+ t.Errorf("before the migration the maps must act as the same fixes: %+v", legacy)
+ }
+ if len(cfg.ArtworkAliases) != 2 || len(cfg.ArtworkOverrides) != 2 || cfg.TitleAsName {
+ t.Errorf("the old keys and other settings must stay: %+v %+v", cfg.ArtworkAliases, cfg.ArtworkOverrides)
+ }
+ b1, _ := os.ReadFile(s.File)
+ if n, wrote, err := s.MigrateMatchFixes(); n != 0 || wrote || err != nil {
+ t.Errorf("a second run migrated %d (written %v, %v)", n, wrote, err)
+ }
+ if b2, _ := os.ReadFile(s.File); string(b1) != string(b2) {
+ t.Error("a second run changed the file")
+ }
+ // Remove in the window saves the list without it; the old line does not come back
+ if err := s.SetSettings(map[string]any{"matchFixes": []any{}}); err != nil {
+ t.Fatal(err)
+ }
+ if c1 := s.Config(); len(c1.Fixes()) != 0 {
+ t.Error("after removing every fix the old lines came back")
+ }
+
+ // nothing to migrate: the file is not written
+ empty := openStore(t, t.TempDir())
+ if n, wrote, err := empty.MigrateMatchFixes(); n != 0 || wrote || err != nil || !empty.FirstRun() {
+ t.Errorf("an install without old lines: %d %v %v, file written: %v", n, wrote, err, !empty.FirstRun())
+ }
+
+ // lines the window's rules refuse are made to pass, or left out, and that is logged once
+ s, logs := legacyStore(t)
+ if n, _, err := s.MigrateMatchFixes(); err != nil || n != 3 {
+ t.Fatalf("migrated %d (%v), want 3 titles", n, err)
+ }
+ want = []core.MatchFix{
+ {Match: "sample long", Search: strings.Repeat("a", maxLineLen)}, // clipped
+ {Match: "sample show", Search: "Sample Series"}, // its cover is not an http(s) address
+ {Match: "sample movie", Cover: "https://img.example/movie.jpg"}, // trimmed
+ }
+ if got := s.Config().MatchFixes; !reflect.DeepEqual(got, want) {
+ t.Errorf("matchFixes = %+v\nwant %+v", got, want)
+ }
+ if len(*logs) != 1 || !strings.Contains((*logs)[0], "2 of the old") || !strings.Contains((*logs)[0], "and 3 were left out") {
+ t.Errorf("log %q: want one line, 2 changed and 3 left out", *logs)
+ }
+
+ // nothing usable left: an empty list, so the old lines are no longer read (the window could not save them); the
+ // key counts as written, so the program applies its fixes again
+ none := openStore(t, t.TempDir())
+ os.WriteFile(none.File, []byte(`{"artworkOverrides": {"sample show": "C:/covers/show.jpg"}}`), 0o600)
+ if n, wrote, err := none.MigrateMatchFixes(); n != 0 || !wrote || err != nil {
+ t.Errorf("migrated %d (written %v, %v), want none, written", n, wrote, err)
+ }
+ if c := none.Config(); c.MatchFixes == nil || len(c.Fixes()) != 0 {
+ t.Errorf("fixes after the migration: %+v (matchFixes %v)", c.Fixes(), c.MatchFixes)
+ }
+}
+
+// legacyStore is an install with old Fix a match lines that the window's rules refuse: a cover that is not an
+// http(s) address, text over its limits, control characters, and a cover too long for the cover finder.
+func legacyStore(t *testing.T) (*Store, *[]string) {
+ t.Helper()
+ old := map[string]any{
+ "artworkAliases": map[string]string{
+ "sample long": strings.Repeat("a", maxLineLen+20),
+ "sample show": "Sample Series",
+ "sample broken": "Sample\u0001Title", // control character, no cover: nothing left
+ },
+ "artworkOverrides": map[string]string{
+ "sample show": "file:///covers/show.jpg",
+ "sample movie": " https://img.example/movie.jpg ",
+ "sample huge": "https://img.example/" + strings.Repeat("x", maxCoverLen), // too long: nothing left
+ "sample\u0002x": "https://img.example/x.jpg", // the title cannot pass
+ },
+ }
+ b, err := json.Marshal(old)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s := openStore(t, dir)
+ var logs []string
+ s.Log = func(level, msg string) { logs = append(logs, level+" "+msg) }
+ return s, &logs
+}
+
+// After a migration of such lines, saving in the window works: it sends the whole list back as it shows it.
+func TestSaveAfterMigratingRefusedLines(t *testing.T) {
+ s, _ := legacyStore(t)
+ if _, _, err := s.MigrateMatchFixes(); err != nil {
+ t.Fatal(err)
+ }
+ fixes := s.Values()["matchFixes"]
+ if err := s.SetSettings(map[string]any{"matchFixes": fixes, "titleAsName": false}); err != nil {
+ t.Fatalf("the window's save after the migration: %v", err)
+ }
+ if c := s.Config(); len(c.MatchFixes) != 3 || c.TitleAsName {
+ t.Errorf("saved %+v", c.MatchFixes)
+ }
+}
+
+func sameFixes(a, b []core.MatchFix) bool {
+ key := func(l []core.MatchFix) map[string]core.MatchFix {
+ m := map[string]core.MatchFix{}
+ for _, f := range l {
+ m[f.Match] = f
+ }
+ return m
+ }
+ return reflect.DeepEqual(key(a), key(b))
+}
+
+func TestCleanFixes(t *testing.T) {
+ s := openStore(t, t.TempDir())
+ ok := []any{
+ map[string]any{"match": " Sample Show ", "entry": "https://www.imdb.com/title/tt0000001/", "search": "ignored with an entry", "label": "Sample Show (2019) · Show · IMDb", "episodeOffset": 12, "seasonOffset": 0},
+ map[string]any{"match": "sample.movie.2020.mkv", "file": true, "cover": "https://img.example/a.jpg"},
+ map[string]any{"match": "SAMPLE SHOW", "search": "Sample Series"}, // replaces the first: the same title
+ }
+ if err := s.SetSettings(map[string]any{"matchFixes": ok}); err != nil {
+ t.Fatal(err)
+ }
+ got := s.Config().MatchFixes
+ want := []core.MatchFix{{Match: "SAMPLE SHOW", Search: "Sample Series"}, {Match: "sample.movie.2020.mkv", File: true, Cover: "https://img.example/a.jpg"}}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("got %+v\nwant %+v", got, want)
+ }
+ b, _ := os.ReadFile(s.File)
+ if !strings.Contains(string(b), `"match": "sample.movie.2020.mkv",
+ "file": true,
+ "cover": "https://img.example/a.jpg"`) {
+ t.Errorf("stored as:\n%s", b)
+ }
+ for _, bad := range []map[string]any{
+ {"search": "no title"},
+ {"match": "x", "entry": "https://example.com/not-a-catalog"},
+ {"match": "x", "cover": "file:///C:/poster.jpg"},
+ {"match": "x", "episodeOffset": 1.5},
+ {"match": "x", "episodeOffset": 9999},
+ {"match": "line\nbreak"},
+ } {
+ if err := s.SetSettings(map[string]any{"matchFixes": []any{bad}}); err == nil {
+ t.Errorf("%v was taken", bad)
+ }
+ }
+ if !reflect.DeepEqual(s.Config().MatchFixes, want) {
+ t.Error("a refused list changed the saved one")
+ }
+}
+
+func TestCleanTextLines(t *testing.T) {
+ s := openStore(t, t.TempDir())
+ if err := s.SetSettings(map[string]any{"textLines": "custom", "customLines": map[string]any{"episodeDetails": " {code} · {episodeTitle} ", "movieCover": ""}}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := s.Config()
+ if cfg.TextLines != "custom" || !reflect.DeepEqual(cfg.CustomLines, map[string]string{"episodeDetails": "{code} · {episodeTitle}"}) {
+ t.Errorf("got %q %+v", cfg.TextLines, cfg.CustomLines)
+ }
+ if v := s.Values()["customLines"]; !reflect.DeepEqual(v, map[string]any{"episodeDetails": "{code} · {episodeTitle}"}) {
+ t.Errorf("the window gets %#v", v)
+ }
+ for _, bad := range []map[string]any{
+ {"textLines": "fancy"},
+ {"customLines": map[string]any{"title": "x"}},
+ {"customLines": map[string]any{"episodeState": 5}},
+ {"customLines": map[string]any{"episodeState": strings.Repeat("x", 301)}},
+ {"customLines": "{title}"},
+ } {
+ if err := s.SetSettings(bad); err == nil {
+ t.Errorf("%v was taken", bad)
+ }
+ }
+ if d := core.DefaultConfig(); d.TextLines != "standard" || len(d.CustomLines) != 0 || d.MatchFixes != nil {
+ t.Errorf("the defaults must change nothing: %q %v %v", d.TextLines, d.CustomLines, d.MatchFixes)
+ }
+}
diff --git a/internal/store/formerenv_test.go b/internal/store/formerenv_test.go
new file mode 100644
index 0000000..ef98c9c
--- /dev/null
+++ b/internal/store/formerenv_test.go
@@ -0,0 +1,22 @@
+package store
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// A copy started by the former version with a data folder of its own (MPCRPC_HOME, no MPRP_HOME) uses that folder,
+// once main has adopted the variable (core.AdoptFormerEnv), and moves nothing.
+func TestDataDirFollowsTheFormerHomeVariable(t *testing.T) {
+ home := filepath.Join(t.TempDir(), "home")
+ t.Setenv("MPRP_HOME", "")
+ os.Unsetenv("MPRP_HOME")
+ t.Setenv("MPCRPC_HOME", home)
+ core.AdoptFormerEnv()
+ if DataDir() != home || FormerDataDir() != "" {
+ t.Errorf("DataDir() = %q, FormerDataDir() = %q; want %q and none", DataDir(), FormerDataDir(), home)
+ }
+}
diff --git a/internal/store/move.go b/internal/store/move.go
new file mode 100644
index 0000000..bc9231c
--- /dev/null
+++ b/internal/store/move.go
@@ -0,0 +1,158 @@
+package store
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// logName is the log file's name in the data folder.
+var logName = strings.ToLower(core.Name) + ".log"
+
+// formerLogs are the log file names under the program's former name, and what they are called now (LogPath).
+var formerLogs = [][2]string{
+ {formerLog, logName},
+ {formerLog + ".old", logName + ".old"}, // the log moved aside when it grew full
+}
+
+// formerLog is the log file's name under the program's former name.
+var formerLog = strings.ToLower(core.FormerName) + ".log"
+
+// MoveFormerData carries the data folder of the program's former name (from) over to its own (to), once: only when
+// to does not exist yet and from is a folder. The folder is renamed; when that fails (a file in it is held open, or
+// the two are on different volumes) it is copied and from is left as it is. A copy goes to a temporary folder first,
+// so a half-made one never passes for the real thing. When the copy fails too, nothing is changed and the program
+// runs on from this time (the next start tries again).
+//
+// It gives the folder to use and a sentence for the log ("" when there was nothing to do).
+func MoveFormerData(from, to string) (dir, note string) {
+ if from == "" || to == "" || exists(to) {
+ return to, ""
+ }
+ if fi, err := os.Stat(from); err != nil || !fi.IsDir() {
+ return to, ""
+ }
+ if err := os.MkdirAll(filepath.Dir(to), 0o700); err != nil {
+ return from, fmt.Sprintf("The data folder %s could not be moved to %s (%v); it is used where it is, and the next start tries again.", from, to, err)
+ }
+ err := os.Rename(from, to)
+ if err == nil {
+ renameLogs(to)
+ return to, fmt.Sprintf("Moved the data folder %s to %s (the program's new name).", from, to)
+ }
+ tmp := to + ".moving"
+ _ = os.RemoveAll(tmp) // a copy that an earlier start did not finish
+ if cerr := copyDir(from, tmp); cerr != nil {
+ _ = os.RemoveAll(tmp)
+ return from, fmt.Sprintf("The data folder %s could not be moved to %s (%v) or copied (%v); it is used where it is, and the next start tries again.", from, to, err, cerr)
+ }
+ if rerr := os.Rename(tmp, to); rerr != nil {
+ _ = os.RemoveAll(tmp)
+ return from, fmt.Sprintf("The data folder %s could not be moved to %s (%v); it is used where it is, and the next start tries again.", from, to, rerr)
+ }
+ renameLogs(to)
+ return to, fmt.Sprintf("Copied the data folder %s to %s (the program's new name); it could not be moved (%v), so the old folder is left in place.", from, to, err)
+}
+
+// exists says whether anything is at path.
+func exists(path string) bool {
+ _, err := os.Lstat(path)
+ return err == nil
+}
+
+// renameLogs gives the log files of the former name the current one. When a file of the current name is there too
+// (the copy that a former version updated itself to logs under the new name in the former folder), the former file's
+// lines go first in it; either way no file of the former name is left, which nothing would ever rotate or remove
+// (a log holds titles).
+func renameLogs(dir string) {
+ for _, l := range formerLogs {
+ old, cur := filepath.Join(dir, l[0]), filepath.Join(dir, l[1])
+ switch {
+ case !exists(old):
+ case !exists(cur):
+ _ = os.Rename(old, cur)
+ default:
+ _ = joinFiles(old, cur)
+ _ = os.Remove(old)
+ }
+ }
+}
+
+// joinFiles puts the text of first before that of second, in second (through a temporary file: a failure changes
+// nothing). It is used only for logs, so a leftover temporary file after a crash does no harm.
+func joinFiles(first, second string) error {
+ tmp := second + ".joining"
+ out, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ for _, p := range []string{first, second} {
+ in, err := os.Open(p)
+ if err == nil {
+ _, err = io.Copy(out, in)
+ in.Close()
+ }
+ if err != nil {
+ out.Close()
+ _ = os.Remove(tmp)
+ return err
+ }
+ }
+ if err := out.Close(); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ if err := os.Rename(tmp, second); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return nil
+}
+
+// copyDir copies the folder from, with everything in it, to a new folder to. Links are not followed (a data folder
+// has none of its own).
+func copyDir(from, to string) error {
+ return filepath.WalkDir(from, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(from, path)
+ if err != nil || strings.HasPrefix(rel, "..") {
+ return fmt.Errorf("%s is outside %s", path, from)
+ }
+ target := filepath.Join(to, rel)
+ switch {
+ case d.IsDir():
+ return os.MkdirAll(target, 0o700)
+ case d.Type().IsRegular():
+ return copyFile(path, target)
+ }
+ return nil // a link or another special file: left out
+ })
+}
+
+// copyFile copies one file, keeping its permission bits.
+func copyFile(from, to string) error {
+ in, err := os.Open(from)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ fi, err := in.Stat()
+ if err != nil {
+ return err
+ }
+ out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, fi.Mode().Perm())
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ out.Close()
+ return err
+ }
+ return out.Close()
+}
diff --git a/internal/store/move_test.go b/internal/store/move_test.go
new file mode 100644
index 0000000..db9e449
--- /dev/null
+++ b/internal/store/move_test.go
@@ -0,0 +1,203 @@
+package store
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// formerFolder makes a data folder as the former version left it: settings, a log and a browser profile folder.
+func formerFolder(t *testing.T, dir string) {
+ t.Helper()
+ for name, text := range map[string]string{
+ "config.json": `{"port":13580}`,
+ formerLog: "a log line\n",
+ filepath.Join("window", "Default", "Preferences"): "{}",
+ } {
+ p := filepath.Join(dir, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(text), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func readText(t *testing.T, p string) string {
+ t.Helper()
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatalf("%s: %v", p, err)
+ }
+ return string(b)
+}
+
+func TestMoveFormerDataRenames(t *testing.T) {
+ base := t.TempDir()
+ from, to := filepath.Join(base, "Old"), filepath.Join(base, "New")
+ formerFolder(t, from)
+ dir, note := MoveFormerData(from, to)
+ if dir != to || !strings.HasPrefix(note, "Moved the data folder") {
+ t.Fatalf("dir %q, note %q", dir, note)
+ }
+ if exists(from) {
+ t.Error("the former folder is still there after a move")
+ }
+ if readText(t, filepath.Join(to, "config.json")) != `{"port":13580}` || readText(t, filepath.Join(to, "window", "Default", "Preferences")) != "{}" {
+ t.Error("the settings or the window's profile did not come along")
+ }
+ if readText(t, filepath.Join(to, logName)) != "a log line\n" || exists(filepath.Join(to, formerLog)) {
+ t.Error("the log was not given its new name")
+ }
+ // once: a second start finds the new folder and leaves everything alone
+ if dir, note := MoveFormerData(from, to); dir != to || note != "" {
+ t.Errorf("second start: dir %q, note %q", dir, note)
+ }
+}
+
+// The copy that a former version updated itself to ran in the former folder and logged under the new name: at the
+// move, the former log's lines go first in it, and no file of the former name is left.
+func TestMoveFormerDataJoinsTheLogs(t *testing.T) {
+ base := t.TempDir()
+ from, to := filepath.Join(base, "Old"), filepath.Join(base, "New")
+ formerFolder(t, from)
+ if err := os.WriteFile(filepath.Join(from, logName), []byte("a line of the update\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if dir, _ := MoveFormerData(from, to); dir != to {
+ t.Fatalf("dir %q", dir)
+ }
+ if got := readText(t, filepath.Join(to, logName)); got != "a log line\na line of the update\n" {
+ t.Errorf("log %q", got)
+ }
+ entries, _ := os.ReadDir(to)
+ for _, e := range entries {
+ if strings.HasSuffix(e.Name(), ".log") && e.Name() != logName || strings.HasSuffix(e.Name(), ".joining") {
+ t.Errorf("%s is left in the data folder", e.Name())
+ }
+ }
+}
+
+func TestMoveFormerDataNothingToDo(t *testing.T) {
+ base := t.TempDir()
+ from, to := filepath.Join(base, "Old"), filepath.Join(base, "New")
+ // no former folder
+ if dir, note := MoveFormerData(from, to); dir != to || note != "" || exists(to) {
+ t.Errorf("no former folder: dir %q, note %q", dir, note)
+ }
+ // MPRP_HOME: FormerDataDir gives ""
+ if dir, note := MoveFormerData("", to); dir != to || note != "" {
+ t.Errorf("no former folder name: dir %q, note %q", dir, note)
+ }
+ // both there: the new one is used and the former one left alone
+ formerFolder(t, from)
+ os.MkdirAll(to, 0o700)
+ os.WriteFile(filepath.Join(to, "config.json"), []byte(`{"port":1}`), 0o600)
+ if dir, note := MoveFormerData(from, to); dir != to || note != "" {
+ t.Errorf("both there: dir %q, note %q", dir, note)
+ }
+ if readText(t, filepath.Join(to, "config.json")) != `{"port":1}` || !exists(filepath.Join(from, "config.json")) {
+ t.Error("a folder was changed although the new one existed")
+ }
+ // a file of the former name is not a data folder
+ f := filepath.Join(base, "File")
+ os.WriteFile(f, []byte("x"), 0o600)
+ if dir, note := MoveFormerData(f, filepath.Join(base, "New2")); note != "" || dir != filepath.Join(base, "New2") {
+ t.Errorf("a file: dir %q, note %q", dir, note)
+ }
+}
+
+func TestFormerDataDirNeverWithOwnHome(t *testing.T) {
+ t.Setenv("MPRP_HOME", t.TempDir())
+ if d := FormerDataDir(); d != "" {
+ t.Errorf("FormerDataDir with MPRP_HOME = %q, want none", d)
+ }
+}
+
+func TestDataDirNames(t *testing.T) {
+ t.Setenv("MPRP_HOME", "")
+ t.Setenv("LOCALAPPDATA", filepath.Join("C:", "Local"))
+ t.Setenv("XDG_DATA_HOME", filepath.Join(string(filepath.Separator), "xdg"))
+ now, former := DataDir(), FormerDataDir()
+ if filepath.Base(now) != "MPRP" || filepath.Base(former) != "MPCvibedRPC" || filepath.Dir(now) != filepath.Dir(former) {
+ t.Errorf("data folder %q, former %q: want the two names side by side", now, former)
+ }
+}
+
+// The copy that is made when the folder cannot be renamed: everything comes along, the former folder stays.
+func TestCopyDir(t *testing.T) {
+ base := t.TempDir()
+ from, to := filepath.Join(base, "Old"), filepath.Join(base, "New.moving")
+ formerFolder(t, from)
+ if err := copyDir(from, to); err != nil {
+ t.Fatal(err)
+ }
+ if readText(t, filepath.Join(to, "config.json")) != `{"port":13580}` || readText(t, filepath.Join(to, "window", "Default", "Preferences")) != "{}" {
+ t.Error("the copy is incomplete")
+ }
+ if !exists(filepath.Join(from, "config.json")) {
+ t.Error("the copy changed the former folder")
+ }
+ // a file that is there already is never overwritten
+ if err := copyDir(from, to); err == nil {
+ t.Error("copying over an existing copy should fail")
+ }
+}
+
+// A former folder that cannot be renamed (here: the new name's parent is a file, so neither rename nor copy can
+// work) is used where it is, untouched.
+func TestMoveFormerDataFallsBack(t *testing.T) {
+ base := t.TempDir()
+ from := filepath.Join(base, "Old")
+ formerFolder(t, from)
+ blocker := filepath.Join(base, "blocker")
+ os.WriteFile(blocker, []byte("x"), 0o600)
+ dir, note := MoveFormerData(from, filepath.Join(blocker, "New"))
+ if dir != from || !strings.Contains(note, "used where it is") {
+ t.Fatalf("dir %q, note %q", dir, note)
+ }
+ if readText(t, filepath.Join(from, "config.json")) != `{"port":13580}` {
+ t.Error("the former folder was changed")
+ }
+}
+
+func TestFormerUpdateSourceReadsAsTheCurrentOne(t *testing.T) {
+ s := openStore(t, t.TempDir())
+ os.WriteFile(s.File, []byte(`{"app":{"updateRepo":"CptPakundo/MPCvibedRPC"}}`), 0o600)
+ if r := s.App().UpdateRepo; r != DefaultUpdateRepo {
+ t.Errorf("former default reads as %q, want %q", r, DefaultUpdateRepo)
+ }
+ os.WriteFile(s.File, []byte(`{"app":{"updateRepo":"someone/fork"}}`), 0o600)
+ if r := s.App().UpdateRepo; r != "someone/fork" {
+ t.Errorf("a fork reads as %q", r)
+ }
+}
+
+// On Windows a folder with a file held open cannot be renamed (the case of a copy of the former version that still
+// runs, or a scanner): the folder is copied instead and the former one left in place.
+func TestMoveFormerDataCopiesWhenAFileIsHeld(t *testing.T) {
+ if runtime.GOOS != "windows" {
+ t.Skip("only Windows refuses to rename a folder with an open file")
+ }
+ base := t.TempDir()
+ from, to := filepath.Join(base, "Old"), filepath.Join(base, "New")
+ formerFolder(t, from)
+ held, err := os.Open(filepath.Join(from, formerLog))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Close()
+ dir, note := MoveFormerData(from, to)
+ if dir != to || !strings.HasPrefix(note, "Copied the data folder") {
+ t.Fatalf("dir %q, note %q", dir, note)
+ }
+ if readText(t, filepath.Join(to, "config.json")) != `{"port":13580}` || readText(t, filepath.Join(to, logName)) != "a log line\n" {
+ t.Error("the copy is incomplete")
+ }
+ if !exists(filepath.Join(from, "config.json")) || exists(to+".moving") {
+ t.Error("the former folder should stay and the temporary copy should be gone")
+ }
+}
diff --git a/internal/store/release_test.go b/internal/store/release_test.go
new file mode 100644
index 0000000..3850bfb
--- /dev/null
+++ b/internal/store/release_test.go
@@ -0,0 +1,37 @@
+package store
+
+import (
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// The release workflow refuses to publish from a repository whose name is not the one the code updates from: its first
+// step reads DefaultUpdateRepo out of store.go with sed. That step must stay, and must find the constant as it is
+// written here. The player logos are fetched from the same repository.
+func TestReleaseChecksTheRepositoryName(t *testing.T) {
+ wf, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "release.yml"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ const sedExpr = `s/^const DefaultUpdateRepo = "\(.*\)"$/\1/p`
+ if !strings.Contains(string(wf), sedExpr+`' internal/store/store.go`) || !strings.Contains(string(wf), `"$GITHUB_REPOSITORY" != "$want"`) {
+ t.Fatal("release.yml no longer compares the repository's name with DefaultUpdateRepo")
+ }
+ src, err := os.ReadFile("store.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // the sed expression as a Go regular expression, on the file as CI checks it out (LF)
+ m := regexp.MustCompile(`(?m)^const DefaultUpdateRepo = "(.*)"$`).FindAllStringSubmatch(strings.ReplaceAll(string(src), "\r\n", "\n"), -1)
+ if len(m) != 1 || m[0][1] != DefaultUpdateRepo {
+ t.Fatalf("the workflow would read %v from store.go, want %q once", m, DefaultUpdateRepo)
+ }
+ if !strings.Contains(core.PlayerIconBase, "/"+DefaultUpdateRepo+"/") {
+ t.Errorf("the player logos (%s) come from another repository than the updates (%s)", core.PlayerIconBase, DefaultUpdateRepo)
+ }
+}
diff --git a/internal/store/schema.go b/internal/store/schema.go
index 35aaaea..4254bc4 100644
--- a/internal/store/schema.go
+++ b/internal/store/schema.go
@@ -7,14 +7,15 @@ import (
"strconv"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// Field is one setting shown in the window. type: bool | int | text | secret | choice | map ("name = value" per line) |
// sources (a switch per online service; the value is the list of services that are OFF) | lines (one entry per line,
-// stored as a list) | heading (a group title in the window; it has no key and no value)
+// stored as a list) | fixes (Fix a match: a list of fixes, see core.MatchFix) | textlines (the custom text lines: an
+// object of core.CustomLineKeys) | heading (a group title in the window; it has no key and no value)
type Field struct {
Key string `json:"key"`
Type string `json:"type"`
@@ -27,6 +28,8 @@ type Field struct {
// OS, when set, limits the field to these systems (runtime.GOOS; "linux" also stands for the other D-Bus systems).
// Elsewhere the setting keeps its value but is not shown.
OS []string `json:"-"`
+ // Legacy keeps a setting that the window no longer shows: it is still validated and saved like the others.
+ Legacy bool `json:"-"`
}
// Section groups fields in the window.
@@ -59,7 +62,7 @@ var Sections = []Section{
}},
{ID: "look", Title: "Look", Fields: []Field{
{Key: "activityType", Type: "choice", Label: "Style", Options: [][2]string{{"watching", "Watching (with progress bar)"}, {"playing", "Playing (classic timer)"}}},
- {Key: "titleAsName", Type: "bool", Label: "Show the title as the activity name", Help: `Shows "Watching " instead of "Watching Media Player Classic".`},
+ {Key: "titleAsName", Type: "bool", Label: "Show the title as the activity name", Help: `Shows "Watching " instead of "Watching MPRP".`},
// Discord names a stream after a Playing status only. Windows can tell when Discord shares the screen, so the
// status changes by itself there; the other systems cannot, and offer all the time or never ("auto" is never
// there, so the setting's default needs no second value).
@@ -73,6 +76,9 @@ var Sections = []Section{
{Key: "richInfo", Type: "bool", Label: "Genres, rating and director", Help: "Extra info line from the catalog match."},
{Key: "linkButton", Type: "bool", Label: "Link to the title's page (IMDb, AniList, ...)", Help: `Adds "View on IMDb" style buttons (up to two) and makes the text lines, the cover and the player's logo clickable. Others can click them on your profile; Discord doesn't let you click your own.`},
{Key: "letterboxdLink", Type: "bool", Label: "Link to Letterboxd when it has the title", Help: `The link opens the title's Letterboxd page instead of IMDb or another catalog. Asks letterboxd.com once per title.`},
+ // the window shows the five custom lines under the choice while it is Custom (ui.js)
+ {Key: "textLines", Type: "choice", Label: "Text lines", Help: "The two lines under the title.", Options: [][2]string{{"standard", "Standard"}, {"short", "Short"}, {"detailed", "Detailed"}, {"custom", "Custom"}}},
+ {Key: "customLines", Type: "textlines", Label: "Custom lines"},
{Key: "episodeInDetails", Type: "bool", Label: "Also show S01E02 in the title line", Help: "Discord already shows a season and episode badge."},
}},
{ID: "titles", Title: "Titles & art", Fields: []Field{
@@ -81,8 +87,12 @@ var Sections = []Section{
{Key: "animeTitles", Type: "choice", Label: "Anime titles", Options: [][2]string{{"auto", "Closest AniList name (auto)"}, {"english", "Always English"}, {"romaji", "Always romaji"}, {"file", "Keep the file's spelling"}}},
{Key: "useFolderName", Type: "bool", Label: "Use the folder name when the file is just an episode number"},
{Type: "heading", Label: "Fix a match"},
- {Key: "artworkAliases", Type: "map", Label: "Search under another name", Help: "One per line: filename title = catalog title"},
- {Key: "artworkOverrides", Type: "map", Label: "Pin a cover image", Help: "One per line: title = https://example.com/poster.jpg"},
+ // the window draws the list of fixes and the Fix this match dialog for it (ui.js)
+ {Key: "matchFixes", Type: "fixes", Label: "Fix a match"},
+ // the legacy form of Fix a match: not in the window any more, but still read and saved as before (a hand-made
+ // config.json, the recorded store tests); the program reads them once into matchFixes (MigrateMatchFixes)
+ {Key: "artworkAliases", Type: "map", Label: "Search under another name", Help: "One per line: filename title = catalog title", Legacy: true},
+ {Key: "artworkOverrides", Type: "map", Label: "Pin a cover image", Help: "One per line: title = https://example.com/poster.jpg", Legacy: true},
{Type: "heading", Label: "More"},
{Key: "tmdbApiKey", Type: "secret", Label: "TMDB API key (optional)", Help: "Free at themoviedb.org/settings/api. Improves matches for some titles."},
{Key: "folderEpisodeNumbers", Type: "bool", Label: "Number episodes by their place in the season folder", Help: "For files named with a running production code."},
@@ -115,6 +125,9 @@ func AllFields() []Field {
// ShownOn reports whether the field belongs in the window on the system goos.
func (f Field) ShownOn(goos string) bool {
+ if f.Legacy {
+ return false
+ }
if len(f.OS) == 0 {
return true
}
@@ -350,6 +363,10 @@ func Clean(f Field, v any) (any, error) {
}
}
return out, nil
+ case "fixes":
+ return cleanFixes(f, v)
+ case "textlines":
+ return cleanTextLines(f, v)
case "map":
out := jsonx.NewObj()
var lines []string
diff --git a/internal/store/secrets.go b/internal/store/secrets.go
new file mode 100644
index 0000000..9ca374b
--- /dev/null
+++ b/internal/store/secrets.go
@@ -0,0 +1,164 @@
+package store
+
+import (
+ "encoding/base64"
+ "reflect"
+ "strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+)
+
+// sealer encrypts the sign-ins' secrets for config.json and decrypts them again. On Windows it is the per-user DPAPI
+// (secrets_windows.go): only the same user on the same computer can decrypt. macOS and Linux have none, and keep the
+// secrets as plain text.
+type sealer interface {
+ seal(plain []byte) ([]byte, error)
+ open(sealed []byte) ([]byte, error)
+}
+
+// sealedPrefix marks an encrypted value in config.json: "dpapi:" and the encrypted bytes in base64. A value without it
+// is plain text (written by a version from before the encryption, or on macOS and Linux) and is read as it is.
+const sealedPrefix = "dpapi:"
+
+// secretKeys are the settings kept encrypted: the fields of core.Secrets. The secrets typed in the window
+// (vlcPassword, kodiPassword, tmdbApiKey) stay plain text: docs/decisions.md says why.
+var secretKeys = func() []string {
+ var keys []string
+ t := reflect.TypeOf(core.Secrets{})
+ for i := 0; i < t.NumField(); i++ {
+ keys = append(keys, strings.Split(t.Field(i).Tag.Get("json"), ",")[0])
+ }
+ return keys
+}()
+
+// openSecrets decrypts the encrypted secrets of a configuration just read, in place. A value that cannot be decrypted
+// (config.json copied from another user or computer, or a system without the encryption) is taken out of o, so that
+// sign-in reads as signed out, and logged once; the file keeps it (s.unopened, put back by sealSecrets) until a new
+// sign-in or a sign-out replaces it, so a save of something else does not lose it. The caller holds s.mu.
+func (s *Store) openSecrets(o *jsonx.Obj) {
+ for _, k := range secretKeys {
+ delete(s.unopened, k)
+ v, ok := o.M[k].(string)
+ if !ok || !strings.HasPrefix(v, sealedPrefix) {
+ continue
+ }
+ if plain, ok := s.plainOf[v]; ok {
+ o.Set(k, plain)
+ continue
+ }
+ plain, err := s.openValue(v)
+ if err != nil {
+ o.Delete(k)
+ if s.unopened == nil {
+ s.unopened = map[string]string{}
+ }
+ s.unopened[k] = v
+ if !s.unreadable[v] {
+ if s.unreadable == nil {
+ s.unreadable = map[string]bool{}
+ }
+ s.unreadable[v] = true
+ s.logf("WARN", "The saved "+k+" cannot be decrypted (the settings file comes from another user or computer), so that sign-in counts as signed out: sign in again.")
+ }
+ continue
+ }
+ s.remember(v, plain)
+ o.Set(k, plain)
+ }
+}
+
+// openValue decrypts one "dpapi:" value.
+func (s *Store) openValue(v string) (string, error) {
+ if s.sealer == nil {
+ return "", errNoSealer
+ }
+ b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(v, sealedPrefix))
+ if err != nil {
+ return "", err
+ }
+ p, err := s.sealer.open(b)
+ if err != nil {
+ return "", err
+ }
+ return string(p), nil
+}
+
+// sealSecrets gives the configuration to write with its secrets encrypted (o itself is left as it is). A secret that
+// did not change keeps the encrypted text it had, so config.json does not change for nothing. When the encryption
+// fails the value is written as plain text, as before the encryption, and that is logged once: a lost sign-in would be
+// worse. A value that could not be decrypted (s.unopened) is written back as it was, unless o has a new one. The caller
+// holds s.mu.
+func (s *Store) sealSecrets(o *jsonx.Obj) *jsonx.Obj {
+ var out *jsonx.Obj
+ copyOnce := func() {
+ if out == nil {
+ out = jsonx.NewObj()
+ for _, key := range o.Keys {
+ out.Set(key, o.M[key])
+ }
+ }
+ }
+ for _, k := range secretKeys {
+ if v, kept := s.unopened[k]; kept {
+ if _, has := o.M[k]; !has {
+ copyOnce()
+ out.Set(k, v)
+ }
+ }
+ }
+ if s.sealer == nil {
+ if out == nil {
+ return o
+ }
+ return out
+ }
+ for _, k := range secretKeys {
+ v, ok := o.M[k].(string)
+ if !ok || v == "" || strings.HasPrefix(v, sealedPrefix) {
+ continue
+ }
+ sealed, ok := s.sealedOf[v]
+ if !ok {
+ b, err := s.sealer.seal([]byte(v))
+ if err != nil {
+ if !s.sealFailed {
+ s.sealFailed = true
+ s.logf("WARN", "The sign-ins could not be encrypted ("+err.Error()+"), so they are saved as plain text.")
+ }
+ continue
+ }
+ sealed = sealedPrefix + base64.StdEncoding.EncodeToString(b)
+ s.remember(sealed, v)
+ }
+ copyOnce()
+ out.Set(k, sealed)
+ }
+ if out == nil {
+ return o
+ }
+ return out
+}
+
+// remember keeps a value's encrypted and plain text in memory, so reading it again needs no decryption and writing it
+// again keeps the same encrypted text.
+func (s *Store) remember(sealed, plain string) {
+ if s.plainOf == nil {
+ s.plainOf, s.sealedOf = map[string]string{}, map[string]string{}
+ }
+ s.plainOf[sealed], s.sealedOf[plain] = plain, sealed
+}
+
+// logf writes a line to the program's log, when the program gave the store one (Store.Log).
+func (s *Store) logf(level, msg string) {
+ if s.Log != nil {
+ s.Log(level, msg)
+ }
+}
+
+type sealError string
+
+func (e sealError) Error() string { return string(e) }
+
+// errNoSealer is the error for an encrypted value on a system that has no encryption (a config.json from Windows).
+const errNoSealer = sealError("this system keeps no encrypted settings")
diff --git a/internal/store/secrets_other.go b/internal/store/secrets_other.go
new file mode 100644
index 0000000..f709ce0
--- /dev/null
+++ b/internal/store/secrets_other.go
@@ -0,0 +1,6 @@
+//go:build !windows
+
+package store
+
+// systemSealer is none on macOS and Linux: the secrets stay plain text there.
+func systemSealer() sealer { return nil }
diff --git a/internal/store/secrets_test.go b/internal/store/secrets_test.go
new file mode 100644
index 0000000..6343ed3
--- /dev/null
+++ b/internal/store/secrets_test.go
@@ -0,0 +1,207 @@
+package store
+
+import (
+ "errors"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+// fakeSealer stands in for the system's encryption: it reverses the bytes behind a marker, and cannot open what it did
+// not seal (as DPAPI cannot open another user's values).
+type fakeSealer struct{ fail bool }
+
+func (f fakeSealer) seal(p []byte) ([]byte, error) {
+ if f.fail {
+ return nil, errors.New("sealing is off")
+ }
+ b := []byte("sealed:")
+ for i := len(p) - 1; i >= 0; i-- {
+ b = append(b, p[i])
+ }
+ return b, nil
+}
+
+func (fakeSealer) open(s []byte) ([]byte, error) {
+ rest, ok := strings.CutPrefix(string(s), "sealed:")
+ if !ok {
+ return nil, errors.New("not ours")
+ }
+ b := []byte(rest)
+ for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
+ b[i], b[j] = b[j], b[i]
+ }
+ return b, nil
+}
+
+// sealedStore is a store in dir with the fake encryption, and the log lines it writes.
+func sealedStore(t *testing.T, dir string, f fakeSealer) (*Store, *[]string) {
+ t.Helper()
+ s := openStore(t, dir)
+ s.sealer = f
+ var logs []string
+ s.Log = func(level, msg string) { logs = append(logs, level+" "+msg) }
+ return s, &logs
+}
+
+func TestSecretKeysAreTheSignIns(t *testing.T) {
+ if want := []string{"plexToken", "plexKey", "stremioKey", "jellyfinToken"}; !reflect.DeepEqual(secretKeys, want) {
+ t.Errorf("secretKeys = %v, want %v", secretKeys, want)
+ }
+}
+
+func TestSecretsAreSavedEncrypted(t *testing.T) {
+ s, logs := sealedStore(t, t.TempDir(), fakeSealer{})
+ keys := []string{"plexToken", "plexKey", "stremioKey", "jellyfinToken", "plexUser"}
+ vals := map[string]any{"plexToken": "sample-token", "plexKey": "sample-key", "stremioKey": "stremio-key", "jellyfinToken": "jf-token", "plexUser": "SampleUser"}
+ if err := s.SetHidden(keys, vals); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(s.File)
+ for _, v := range []string{"sample-token", "sample-key", "stremio-key", "jf-token"} {
+ if strings.Contains(string(b), v) {
+ t.Errorf("%q is in config.json as plain text:\n%s", v, b)
+ }
+ }
+ if !strings.Contains(string(b), `"plexToken": "dpapi:`) || !strings.Contains(string(b), `"plexUser": "SampleUser"`) {
+ t.Errorf("only the secrets are encrypted:\n%s", b)
+ }
+ c := s.Config()
+ if c.PlexToken != "sample-token" || c.PlexKey != "sample-key" || c.StremioKey != "stremio-key" || c.JellyfinToken != "jf-token" {
+ t.Errorf("read back %+v", c.Secrets)
+ }
+ // another store (the next start) decrypts them too
+ if c, _ := sealedStore(t, s.Dir, fakeSealer{}); c.Config().PlexToken != "sample-token" {
+ t.Error("a new start reads the encrypted token")
+ }
+ // a write that does not change a secret keeps its encrypted text
+ if err := s.SetSettings(map[string]any{"pollInterval": 2000}); err != nil {
+ t.Fatal(err)
+ }
+ if b2, _ := os.ReadFile(s.File); !strings.Contains(string(b2), `"pollInterval": 2000`) || sealedValue(t, b2, "plexToken") != sealedValue(t, b, "plexToken") {
+ t.Errorf("the token's encrypted text changed:\n%s\n%s", b, b2)
+ }
+ for k := range s.Values() {
+ for _, sk := range secretKeys {
+ if k == sk {
+ t.Errorf("the window receives %s", k)
+ }
+ }
+ }
+ if len(*logs) != 0 {
+ t.Errorf("log %q", *logs)
+ }
+}
+
+// sealedValue is the encrypted text config.json holds for key.
+func sealedValue(t *testing.T, file []byte, key string) string {
+ t.Helper()
+ _, rest, ok := strings.Cut(string(file), `"`+key+`": "`)
+ if !ok {
+ t.Fatalf("no %s in %s", key, file)
+ }
+ v, _, _ := strings.Cut(rest, `"`)
+ return v
+}
+
+func TestPlainSecretsLoadAndAreEncryptedAtTheNextWrite(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(dir+"/config.json", []byte(`{"stremioKey": "older-key", "vlcPassword": "typed-pass", "tmdbApiKey": "typed-key"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s, _ := sealedStore(t, dir, fakeSealer{})
+ if c := s.Config(); c.StremioKey != "older-key" || c.VlcPassword != "typed-pass" {
+ t.Fatalf("a plain value from an older version loads: %+v", c)
+ }
+ if err := s.SetSettings(map[string]any{"pollInterval": 2000}); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(s.File)
+ if strings.Contains(string(b), "older-key") || !strings.Contains(string(b), `"stremioKey": "dpapi:`) {
+ t.Errorf("the next write encrypts the sign-in:\n%s", b)
+ }
+ if !strings.Contains(string(b), `"vlcPassword": "typed-pass"`) || !strings.Contains(string(b), `"tmdbApiKey": "typed-key"`) {
+ t.Errorf("the secrets typed in the window stay plain text:\n%s", b)
+ }
+ if s.Config().StremioKey != "older-key" {
+ t.Error("read back after encrypting")
+ }
+}
+
+func TestUndecryptableSecretReadsAsSignedOut(t *testing.T) {
+ dir := t.TempDir()
+ // encrypted by another user or computer: the fake cannot open it
+ if err := os.WriteFile(dir+"/config.json", []byte(`{"plexToken": "dpapi:b3RoZXI=", "plexUser": "SampleUser", "jellyfinToken": "dpapi:%%%", "pollInterval": 3000}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s, logs := sealedStore(t, dir, fakeSealer{})
+ for i := 0; i < 3; i++ {
+ if c := s.Config(); c.PlexToken != "" || c.JellyfinToken != "" || c.PlexUser != "SampleUser" || c.PollInterval != 3000 {
+ t.Fatalf("read %+v", c)
+ }
+ }
+ if len(*logs) != 2 || !strings.Contains((*logs)[0], "plexToken") || !strings.Contains((*logs)[1], "jellyfinToken") || strings.Contains(strings.Join(*logs, ""), "b3RoZXI") {
+ t.Errorf("one line per value, without it: %q", *logs)
+ }
+ // with no encryption on this system (macOS, Linux) an encrypted value cannot be read either
+ n := openStore(t, dir)
+ n.sealer = nil
+ if n.Config().PlexToken != "" {
+ t.Error("no encryption: the encrypted value reads as signed out")
+ }
+
+ // a save of something else keeps the encrypted text in the file (with and without encryption here)
+ for _, st := range []*Store{s, n} {
+ if err := st.SetSettings(map[string]any{"pollInterval": 4000}); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(st.File)
+ if !strings.Contains(string(b), `"plexToken": "dpapi:b3RoZXI="`) || !strings.Contains(string(b), `"jellyfinToken": "dpapi:%%%"`) {
+ t.Errorf("a save of another setting dropped the undecryptable values:\n%s", b)
+ }
+ if c := st.Config(); c.PlexToken != "" || c.JellyfinToken != "" || c.PollInterval != 4000 {
+ t.Errorf("after the save: %+v", c)
+ }
+ }
+ // a new sign-in replaces it; a sign-out removes it
+ if err := s.SetHidden([]string{"plexToken", "jellyfinToken"}, map[string]any{"plexToken": "sample-token"}); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(s.File)
+ if strings.Contains(string(b), "b3RoZXI") || strings.Contains(string(b), "jellyfinToken") || s.Config().PlexToken != "sample-token" {
+ t.Errorf("after a sign-in and a sign-out:\n%s", b)
+ }
+ if err := s.SetSettings(map[string]any{"pollInterval": 5000}); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(s.File); strings.Contains(string(b), "jellyfinToken") || strings.Contains(string(b), "b3RoZXI") {
+ t.Errorf("a value replaced or removed came back:\n%s", b)
+ }
+}
+
+func TestSecretsStayPlainWithoutEncryption(t *testing.T) {
+ s := openStore(t, t.TempDir())
+ s.sealer = nil // macOS and Linux
+ if err := s.SetHidden([]string{"plexToken"}, map[string]any{"plexToken": "sample-token"}); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(s.File); !strings.Contains(string(b), `"plexToken": "sample-token"`) {
+ t.Errorf("plain text as before:\n%s", b)
+ }
+}
+
+func TestFailedEncryptionSavesPlainAndLogsOnce(t *testing.T) {
+ s, logs := sealedStore(t, t.TempDir(), fakeSealer{fail: true})
+ for i := 0; i < 2; i++ {
+ if err := s.SetHidden([]string{"plexToken"}, map[string]any{"plexToken": "sample-token"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if s.Config().PlexToken != "sample-token" {
+ t.Error("the sign-in is kept")
+ }
+ if len(*logs) != 1 || strings.Contains((*logs)[0], "sample-token") {
+ t.Errorf("one log line, without the value: %q", *logs)
+ }
+}
diff --git a/internal/store/secrets_windows.go b/internal/store/secrets_windows.go
new file mode 100644
index 0000000..6e1300b
--- /dev/null
+++ b/internal/store/secrets_windows.go
@@ -0,0 +1,49 @@
+package store
+
+import (
+ "runtime"
+ "syscall"
+ "unsafe"
+)
+
+var (
+ crypt32 = syscall.NewLazyDLL("crypt32.dll")
+ procCryptProtectData = crypt32.NewProc("CryptProtectData")
+ procCryptUnprotectData = crypt32.NewProc("CryptUnprotectData")
+ procLocalFree = syscall.NewLazyDLL("kernel32.dll").NewProc("LocalFree")
+)
+
+// dataBlob is DATA_BLOB.
+type dataBlob struct {
+ size uint32
+ data *byte
+}
+
+// cryptProtectUIForbidden (CRYPTPROTECT_UI_FORBIDDEN): never show a prompt; fail instead.
+const cryptProtectUIForbidden = 0x1
+
+// dpapi is Windows' per-user data protection: what it encrypts only the same user on the same computer can decrypt.
+type dpapi struct{}
+
+func systemSealer() sealer { return dpapi{} }
+
+func (dpapi) seal(plain []byte) ([]byte, error) { return dpapiCall(procCryptProtectData, plain) }
+func (dpapi) open(sealed []byte) ([]byte, error) {
+ return dpapiCall(procCryptUnprotectData, sealed)
+}
+
+// dpapiCall runs CryptProtectData or CryptUnprotectData (both take the same arguments here: the input, no description,
+// no extra entropy, no prompt) and copies the output out of the memory Windows allocated for it, which it then frees.
+func dpapiCall(proc *syscall.LazyProc, in []byte) ([]byte, error) {
+ buf := make([]byte, len(in)+1) // one byte more, so that even empty input has an address
+ copy(buf, in)
+ inBlob := dataBlob{size: uint32(len(in)), data: &buf[0]}
+ var out dataBlob
+ r, _, err := proc.Call(uintptr(unsafe.Pointer(&inBlob)), 0, 0, 0, 0, cryptProtectUIForbidden, uintptr(unsafe.Pointer(&out)))
+ runtime.KeepAlive(buf)
+ if r == 0 {
+ return nil, err
+ }
+ defer procLocalFree.Call(uintptr(unsafe.Pointer(out.data)))
+ return append([]byte(nil), unsafe.Slice(out.data, out.size)...), nil
+}
diff --git a/internal/store/secrets_windows_test.go b/internal/store/secrets_windows_test.go
new file mode 100644
index 0000000..8c7f1ac
--- /dev/null
+++ b/internal/store/secrets_windows_test.go
@@ -0,0 +1,38 @@
+package store
+
+import (
+ "bytes"
+ "os"
+ "strings"
+ "testing"
+)
+
+// The real DPAPI, in memory, for the current user: nothing is stored and nothing on the computer changes.
+func TestDPAPIRoundTrip(t *testing.T) {
+ plain := []byte("sample-token")
+ sealed, err := dpapi{}.seal(plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(sealed, plain) {
+ t.Error("the encrypted bytes hold the plain text")
+ }
+ back, err := dpapi{}.open(sealed)
+ if err != nil || !bytes.Equal(back, plain) {
+ t.Fatalf("open = %q, %v", back, err)
+ }
+ if _, err := (dpapi{}).open([]byte("not encrypted")); err == nil {
+ t.Error("bytes DPAPI did not make cannot be opened")
+ }
+ // the store uses it by itself on Windows
+ s := openStore(t, t.TempDir())
+ if err := s.SetHidden([]string{"plexToken"}, map[string]any{"plexToken": "sample-token"}); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(s.File); strings.Contains(string(b), "sample-token") || !strings.Contains(string(b), sealedPrefix) {
+ t.Errorf("config.json:\n%s", b)
+ }
+ if openStore(t, s.Dir).Config().PlexToken != "sample-token" {
+ t.Error("read back")
+ }
+}
diff --git a/internal/store/store.go b/internal/store/store.go
index 83b73fe..4c5b718 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -13,23 +13,36 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsre"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/jsre"
)
// DataDir is where everything lives:
//
-// Windows: %LOCALAPPDATA%\MPCvibedRPC (override with MPCRPC_HOME)
-// macOS: ~/Library/Application Support/MPCvibedRPC
-// Linux: $XDG_DATA_HOME/MPCvibedRPC, else ~/.local/share/MPCvibedRPC
-// config.json settings mpcvibedrpc.log log artwork-cache.json cover cache
+// Windows: %LOCALAPPDATA%\MPRP (override with MPRP_HOME)
+// macOS: ~/Library/Application Support/MPRP
+// Linux: $XDG_DATA_HOME/MPRP, else ~/.local/share/MPRP
+// config.json settings mprp.log log artwork-cache.json cover cache
// stats.json local counts ipc.json the running copy's port and token instance.lock single instance (macOS, Linux)
func DataDir() string {
- if v := os.Getenv("MPCRPC_HOME"); v != "" {
+ if v := os.Getenv("MPRP_HOME"); v != "" {
return v
}
- const name = "MPCvibedRPC"
+ return dataDirNamed(core.Name)
+}
+
+// FormerDataDir is the data folder the program used under its former name (core.FormerName), which MoveFormerData
+// carries over; "" for a copy with a data folder of its own (MPRP_HOME), which never moves anything.
+func FormerDataDir() string {
+ if os.Getenv("MPRP_HOME") != "" {
+ return ""
+ }
+ return dataDirNamed(core.FormerName)
+}
+
+// dataDirNamed is the system's place for the data folder of a program called name.
+func dataDirNamed(name string) string {
home, _ := os.UserHomeDir()
switch runtime.GOOS {
case "windows":
@@ -54,7 +67,7 @@ type App struct {
StartPresence bool `json:"startPresence"` // begin sending presence as soon as the app opens
CheckUpdates bool `json:"checkUpdates"` // look for a newer release at start, then every six hours
AutoUpdate bool `json:"autoUpdate"` // install a found update by itself at a quiet moment (needs checkUpdates; Windows and Linux)
- UpdateRepo string `json:"updateRepo"` // "owner/repo" on GitHub that publishes releases with MPCvibedRPC.exe
+ UpdateRepo string `json:"updateRepo"` // "owner/repo" on GitHub that publishes releases with MPRP.exe
WelcomeSeen bool `json:"welcomeSeen"` // the first-run welcome card was dismissed (existing installs count as having seen it)
OpenWindow bool `json:"openWindow"` // show the window when the program is started by hand (it always starts in the tray at login)
MinimizeToTray bool `json:"minimizeToTray"` // a minimised settings window goes to the tray instead of the taskbar (Windows)
@@ -62,7 +75,19 @@ type App struct {
}
// DefaultUpdateRepo is where releases of this program are published.
-const DefaultUpdateRepo = "CptPakundo/MPCvibedRPC"
+const DefaultUpdateRepo = "CptPakundo/MPRP"
+
+// formerUpdateRepo is the default update source under the program's former name. config.json holds the default once
+// any program setting was saved, so an install from before the rename has it; it reads as DefaultUpdateRepo.
+const formerUpdateRepo = "CptPakundo/" + core.FormerName
+
+// updateRepo is the update source as saved, with the former default read as the current one.
+func updateRepo(saved string) string {
+ if strings.EqualFold(saved, formerUpdateRepo) {
+ return DefaultUpdateRepo
+ }
+ return saved
+}
var appKeys = []string{"autoStart", "startPresence", "checkUpdates", "autoUpdate", "updateRepo", "openWindow", "minimizeToTray", "welcomeSeen", "seenVersion"}
@@ -115,6 +140,16 @@ type Store struct {
readFile func(string) ([]byte, error) // os.ReadFile; tests replace it to make reading fail
retryWait time.Duration // the pause between tries to read a file that fails
+
+ // Log, when set, writes a line to the program's log (a sign-in that cannot be decrypted, see secrets.go).
+ Log func(level, msg string)
+
+ sealer sealer // encrypts the sign-ins' secrets (nil: they stay plain text)
+ plainOf map[string]string // encrypted text -> plain, for the values read or written so far
+ sealedOf map[string]string // plain -> encrypted text
+ unreadable map[string]bool // encrypted values already logged as undecryptable
+ unopened map[string]string // secret key -> its encrypted text in config.json as last read, which cannot be decrypted
+ sealFailed bool // a failed encryption was logged
}
// New opens (and creates) the data folder.
@@ -122,11 +157,11 @@ func New(dir string) (*Store, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
- return &Store{Dir: dir, File: filepath.Join(dir, "config.json"), readFile: os.ReadFile, retryWait: 50 * time.Millisecond}, nil
+ return &Store{Dir: dir, File: filepath.Join(dir, "config.json"), readFile: os.ReadFile, retryWait: 50 * time.Millisecond, sealer: systemSealer()}, nil
}
func (s *Store) CachePath() string { return filepath.Join(s.Dir, "artwork-cache.json") }
-func (s *Store) LogPath() string { return filepath.Join(s.Dir, "mpcvibedrpc.log") }
+func (s *Store) LogPath() string { return filepath.Join(s.Dir, logName) }
func (s *Store) IPCPath() string { return filepath.Join(s.Dir, "ipc.json") }
func (s *Store) StatsPath() string { return filepath.Join(s.Dir, "stats.json") }
@@ -164,6 +199,7 @@ func (s *Store) readOrLast() *jsonx.Obj {
}
if v, err := jsonx.Parse(strings.TrimPrefix(string(s.last), "\ufeff")); err == nil {
if o, ok := v.(*jsonx.Obj); ok {
+ s.openSecrets(o)
return o
}
}
@@ -182,7 +218,9 @@ func (s *Store) read() (*jsonx.Obj, error) {
return nil, err
}
s.last = b
- return s.parse(b), nil
+ o := s.parse(b)
+ s.openSecrets(o)
+ return o, nil
}
// parse reads config.json's text; text that is not a JSON object is kept as a .broken copy and counts as empty.
@@ -215,10 +253,11 @@ func (s *Store) brokenName() string {
return name
}
-// write saves config.json. The caller holds s.mu.
+// write saves config.json, with the sign-ins' secrets encrypted where the system can (sealSecrets). The caller holds
+// s.mu.
func (s *Store) write(o *jsonx.Obj) error {
tmp := s.File + ".tmp"
- text := []byte(jsonx.Stringify(o, 2))
+ text := []byte(jsonx.Stringify(s.sealSecrets(o), 2))
// Flushed before the rename: after a power loss the rename can survive while unflushed data does not, which
// would leave an empty config.json.
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
@@ -266,6 +305,7 @@ func (s *Store) Reset() error {
if err != nil {
return err
}
+ s.unopened = nil // the sign-ins go with the settings
if cur, ok := old.M["app"].(*jsonx.Obj); ok {
keep := jsonx.NewObj()
for _, k := range []string{"seenVersion"} {
@@ -300,6 +340,11 @@ func (s *Store) settingsObj() *jsonx.Obj {
out.Set(k, o.M[k])
}
}
+ // The former default Discord application, saved by an install from before the project had its own, reads as the
+ // current default (an application the user made stays as it is).
+ if id, _ := out.M["clientId"].(string); id == core.FormerClientID {
+ out.Set("clientId", core.DefaultClientID)
+ }
return out
}
@@ -320,7 +365,7 @@ func (s *Store) App() App {
StartPresence: boolOr(cur, "startPresence", d.StartPresence),
CheckUpdates: boolOr(cur, "checkUpdates", d.CheckUpdates),
AutoUpdate: boolOr(cur, "autoUpdate", d.AutoUpdate),
- UpdateRepo: strOr(cur, "updateRepo", d.UpdateRepo),
+ UpdateRepo: updateRepo(strOr(cur, "updateRepo", d.UpdateRepo)),
WelcomeSeen: boolOr(cur, "welcomeSeen", d.WelcomeSeen),
OpenWindow: boolOr(cur, "openWindow", d.OpenWindow),
MinimizeToTray: boolOr(cur, "minimizeToTray", d.MinimizeToTray),
@@ -338,6 +383,14 @@ func (s *Store) Values() map[string]any {
if f.Type == "heading" {
continue
}
+ if f.Type == "fixes" {
+ fixes := cfg.Fixes() // the legacy lines too, while they are not written as fixes yet
+ if fixes == nil {
+ fixes = []core.MatchFix{}
+ }
+ out[f.Key] = fixes
+ continue
+ }
if f.Type == "map" {
if o, ok := raw.M[f.Key].(*jsonx.Obj); ok {
out[f.Key] = MapToText(o)
@@ -449,6 +502,7 @@ func (s *Store) SetHidden(keys []string, values map[string]any) error {
}
if v := values[k]; v == nil {
cur.Delete(k)
+ delete(s.unopened, k) // a sign-out removes a value that could not be decrypted too
} else {
cur.Set(k, v)
}
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 5e80969..cd93965 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -11,7 +11,8 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
)
type goldenStep struct {
@@ -91,6 +92,9 @@ func TestStoreAgainstJS(t *testing.T) {
gb, _ := json.Marshal(got)
var gv map[string]any
json.Unmarshal(gb, &gv)
+ if s.Values["clientId"] == core.FormerClientID {
+ s.Values["clientId"] = core.DefaultClientID // recorded with the former default application; it reads as the current one
+ }
if !reflect.DeepEqual(gv, s.Values) {
for k, v := range s.Values {
if !reflect.DeepEqual(gv[k], v) {
@@ -410,10 +414,19 @@ func TestSectionsForEachSystem(t *testing.T) {
}
// everything else is shown everywhere
for _, f := range AllFields() {
- if len(f.OS) == 0 && f.Key != "" && !(win[f.Key] && mac[f.Key] && linux[f.Key]) {
+ if len(f.OS) == 0 && !f.Legacy && f.Key != "" && !(win[f.Key] && mac[f.Key] && linux[f.Key]) {
t.Errorf("%s should be shown everywhere", f.Key)
}
}
+ // the legacy Fix a match lines are shown nowhere, but still validate
+ for _, k := range []string{"artworkAliases", "artworkOverrides"} {
+ if win[k] || mac[k] || linux[k] {
+ t.Errorf("%s is shown", k)
+ }
+ if _, ok := ByKey(k); !ok {
+ t.Errorf("%s must stay a known setting", k)
+ }
+ }
// the hidden settings still validate (a config.json copied between systems keeps them)
if _, ok := ByKey("iinaPipe"); !ok {
t.Error("iinaPipe must stay a known setting")
diff --git a/internal/store/unreadable_test.go b/internal/store/unreadable_test.go
index e64e549..30e9888 100644
--- a/internal/store/unreadable_test.go
+++ b/internal/store/unreadable_test.go
@@ -6,7 +6,7 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/jsonx"
+ "github.com/CptPakundo/MPRP/internal/jsonx"
)
func patchOf(t *testing.T, js string) *jsonx.Obj {
diff --git a/internal/stremio/account.go b/internal/stremio/account.go
index 5566c7a..b2bc10d 100644
--- a/internal/stremio/account.go
+++ b/internal/stremio/account.go
@@ -16,7 +16,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
var (
diff --git a/internal/stremio/watcher.go b/internal/stremio/watcher.go
index d8a7e4c..d9e55ca 100644
--- a/internal/stremio/watcher.go
+++ b/internal/stremio/watcher.go
@@ -10,8 +10,8 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
- "github.com/CptPakundo/MPCvibedRPC/internal/remote"
+ "github.com/CptPakundo/MPRP/internal/core"
+ "github.com/CptPakundo/MPRP/internal/remote"
)
// How often Stremio's player updates the library entry of what it plays (stremio-core's PUSH_TO_LIBRARY_EVERY):
diff --git a/internal/updater/updater.go b/internal/updater/updater.go
index 8089cee..dcb9de3 100644
--- a/internal/updater/updater.go
+++ b/internal/updater/updater.go
@@ -1,5 +1,5 @@
// Package updater updates the program from GitHub Releases. Publish a release whose tag is a version ("v1.2.0")
-// with the program for each system (MPCvibedRPC.exe, MPCvibedRPC-linux-amd64, ...; see AssetFor) and a .sha256 next
+// with the program for each system (MPRP.exe, MPRP-linux-amd64, ...; see AssetFor) and a .sha256 next
// to each (without one the app only links to the release); the app offers it, downloads it and swaps itself in. The
// files must come from GitHub (see allowedHost). On macOS it only offers the release page.
package updater
@@ -28,13 +28,13 @@ import (
// program is an app bundle, and the user is sent to the release page instead).
var Asset = AssetFor(runtime.GOOS, runtime.GOARCH)
-// AssetFor names the release file of a system: MPCvibedRPC.exe, MPCvibedRPC-linux-amd64, ...
+// AssetFor names the release file of a system: MPRP.exe, MPRP-linux-amd64, ...
func AssetFor(goos, goarch string) string {
switch {
case goos == "windows":
- return "MPCvibedRPC.exe"
+ return "MPRP.exe"
case goos == "linux" && (goarch == "amd64" || goarch == "arm64"):
- return "MPCvibedRPC-linux-" + goarch
+ return "MPRP-linux-" + goarch
}
return ""
}
@@ -151,7 +151,7 @@ func get(ctx context.Context, client *http.Client, addr, accept, etag string) (*
if err != nil {
return nil, err
}
- req.Header.Set("User-Agent", "MPCvibedRPC")
+ req.Header.Set("User-Agent", "MPRP")
if accept != "" {
req.Header.Set("Accept", accept)
}
diff --git a/internal/updater/updater_host_test.go b/internal/updater/updater_host_test.go
index c9c1faf..f068e75 100644
--- a/internal/updater/updater_host_test.go
+++ b/internal/updater/updater_host_test.go
@@ -15,21 +15,21 @@ func TestAllowedHost(t *testing.T) {
APIBase, WebBase = "http://127.0.0.1:5555", "http://127.0.0.1:5555"
defer func() { APIBase, WebBase = oldAPI, oldWeb }()
for addr, want := range map[string]bool{
- "https://github.com/o/r/releases/download/v1/MPCvibedRPC.exe": true,
- "https://GitHub.com/o/r/releases/download/v1/MPCvibedRPC.exe": true,
- "https://objects.githubusercontent.com/x": true,
- "https://release-assets.githubusercontent.com/x": true,
- "http://127.0.0.1:5555/dl": true, // the base itself is plain http
- "http://127.0.0.1:6666/dl": false,
- "https://127.0.0.1:5555/dl": false, // another scheme than the base
- "http://github.com/o/r/x": false, // not https
- "https://evil.example/github.com": false,
- "https://github.com.evil.example/x": false,
- "https://evilgithubusercontent.com/x": false,
- "https://githubusercontent.com/x": false,
- "https://github.com:8443/x": false,
- "https://user:pw@github.com/x": false,
- "https://api.github.com/repos/o/r/releases/assets/1": false, // not a base here
+ "https://github.com/o/r/releases/download/v1/MPRP.exe": true,
+ "https://GitHub.com/o/r/releases/download/v1/MPRP.exe": true,
+ "https://objects.githubusercontent.com/x": true,
+ "https://release-assets.githubusercontent.com/x": true,
+ "http://127.0.0.1:5555/dl": true, // the base itself is plain http
+ "http://127.0.0.1:6666/dl": false,
+ "https://127.0.0.1:5555/dl": false, // another scheme than the base
+ "http://github.com/o/r/x": false, // not https
+ "https://evil.example/github.com": false,
+ "https://github.com.evil.example/x": false,
+ "https://evilgithubusercontent.com/x": false,
+ "https://githubusercontent.com/x": false,
+ "https://github.com:8443/x": false,
+ "https://user:pw@github.com/x": false,
+ "https://api.github.com/repos/o/r/releases/assets/1": false, // not a base here
} {
u, err := url.Parse(addr)
if err != nil {
@@ -55,7 +55,7 @@ func TestDownloadRefusesForeignHosts(t *testing.T) {
otherHost := strings.TrimPrefix(other.URL, "http://")
// the "API" lives under a name that differs from the other server's host, though both are local
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, `{"tag_name":"v3.1.0","html_url":"https://example/rel","assets":[{"name":"MPCvibedRPC.exe","browser_download_url":"%s/exe"},{"name":"MPCvibedRPC.exe.sha256","browser_download_url":"%s/sha"}]}`, other.URL, other.URL)
+ fmt.Fprintf(w, `{"tag_name":"v3.1.0","html_url":"https://example/rel","assets":[{"name":"MPRP.exe","browser_download_url":"%s/exe"},{"name":"MPRP.exe.sha256","browser_download_url":"%s/sha"}]}`, other.URL, other.URL)
}))
defer api.Close()
old := APIBase
@@ -117,7 +117,7 @@ func TestCheckIsConditional(t *testing.T) {
return
}
w.Header().Set("ETag", `"abc"`)
- fmt.Fprint(w, `{"tag_name":"v3.1.0","body":"Notes.","html_url":"https://example/rel","assets":[{"name":"MPCvibedRPC.exe","browser_download_url":"x"},{"name":"MPCvibedRPC.exe.sha256","browser_download_url":"y"}]}`)
+ fmt.Fprint(w, `{"tag_name":"v3.1.0","body":"Notes.","html_url":"https://example/rel","assets":[{"name":"MPRP.exe","browser_download_url":"x"},{"name":"MPRP.exe.sha256","browser_download_url":"y"}]}`)
}))
defer srv.Close()
old := APIBase
diff --git a/internal/updater/updater_test.go b/internal/updater/updater_test.go
index f34146c..15df84e 100644
--- a/internal/updater/updater_test.go
+++ b/internal/updater/updater_test.go
@@ -13,7 +13,7 @@ import (
"testing"
)
-func init() { Asset, Magic = "MPCvibedRPC.exe", "MZ" } // the Windows release, whatever system runs the tests
+func init() { Asset, Magic = "MPRP.exe", "MZ" } // the Windows release, whatever system runs the tests
func TestCompare(t *testing.T) {
cases := []struct {
@@ -40,17 +40,17 @@ func setup(t *testing.T, exe []byte, sha string, notes string) (*httptest.Server
mux := http.NewServeMux()
var srv *httptest.Server
mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("User-Agent") != "MPCvibedRPC" {
+ if r.Header.Get("User-Agent") != "MPRP" {
t.Error("missing UA")
}
shaAsset := ""
if sha != "" {
- shaAsset = fmt.Sprintf(`,{"name":"MPCvibedRPC.exe.sha256","browser_download_url":"%s/sha"}`, srv.URL)
+ shaAsset = fmt.Sprintf(`,{"name":"MPRP.exe.sha256","browser_download_url":"%s/sha"}`, srv.URL)
}
- fmt.Fprintf(w, `{"tag_name":"v3.1.0","body":%q,"html_url":"https://example/rel","assets":[{"name":"other.zip","browser_download_url":"x"},{"name":"MPCvibedRPC.exe","browser_download_url":"%s/exe"}%s]}`, notes, srv.URL, shaAsset)
+ fmt.Fprintf(w, `{"tag_name":"v3.1.0","body":%q,"html_url":"https://example/rel","assets":[{"name":"other.zip","browser_download_url":"x"},{"name":"MPRP.exe","browser_download_url":"%s/exe"}%s]}`, notes, srv.URL, shaAsset)
})
mux.HandleFunc("/exe", func(w http.ResponseWriter, r *http.Request) { w.Write(exe) })
- mux.HandleFunc("/sha", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, sha+" MPCvibedRPC.exe\n") })
+ mux.HandleFunc("/sha", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, sha+" MPRP.exe\n") })
srv = httptest.NewServer(mux)
old := APIBase
APIBase = srv.URL
@@ -249,9 +249,9 @@ func TestRestorePutsTheOldProgramBack(t *testing.T) {
func TestAssetFor(t *testing.T) {
cases := map[[2]string]string{
- {"windows", "amd64"}: "MPCvibedRPC.exe",
- {"linux", "amd64"}: "MPCvibedRPC-linux-amd64",
- {"linux", "arm64"}: "MPCvibedRPC-linux-arm64",
+ {"windows", "amd64"}: "MPRP.exe",
+ {"linux", "amd64"}: "MPRP-linux-amd64",
+ {"linux", "arm64"}: "MPRP-linux-arm64",
{"linux", "386"}: "",
{"darwin", "arm64"}: "", // an app bundle: the release page is offered instead
{"freebsd", "amd64"}: "",
@@ -266,7 +266,7 @@ func TestAssetFor(t *testing.T) {
// Where the program cannot install a release itself, Check still reports it, with only the page to go to.
func TestCheckWithoutAsset(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `{"tag_name":"v3.1.0","html_url":"https://example/rel","assets":[{"name":"MPCvibedRPC.exe","browser_download_url":"x"}]}`)
+ fmt.Fprint(w, `{"tag_name":"v3.1.0","html_url":"https://example/rel","assets":[{"name":"MPRP.exe","browser_download_url":"x"}]}`)
}))
defer srv.Close()
old, oldAPI := Asset, APIBase
@@ -311,7 +311,7 @@ func TestCheckFallsBackToTheWebsite(t *testing.T) {
t.Fatal(err)
}
if !info.Newer || info.Latest != "3.1.0" || !info.CanInstall || info.Page != srv.URL+"/o/r/releases/tag/v3.1.0" ||
- info.URL != srv.URL+"/o/r/releases/download/v3.1.0/MPCvibedRPC.exe" || info.ShaURL != info.URL+".sha256" {
+ info.URL != srv.URL+"/o/r/releases/download/v3.1.0/MPRP.exe" || info.ShaURL != info.URL+".sha256" {
t.Fatalf("got %+v", info)
}
if info, err := Check(nil, "o/r", "3.1.0"); err != nil || info.Newer {
@@ -326,7 +326,7 @@ func TestCheckFallsBackToTheWebsite(t *testing.T) {
}
func TestWhatsNew(t *testing.T) {
- notes := "## MPCvibedRPC 9.9.9\r\n\r\n**Sample feature.**\r\n\r\n- One thing.\r\n- Another.\r\n\r\n### Get it\r\n- Download it.\r\n\r\n### Good to know\r\n- More."
+ notes := "## MPRP 9.9.9\r\n\r\n**Sample feature.**\r\n\r\n- One thing.\r\n- Another.\r\n\r\n### Get it\r\n- Download it.\r\n\r\n### Good to know\r\n- More."
if got := whatsNew(notes); got != "**Sample feature.**\n\n- One thing.\n- Another." {
t.Errorf("got %q", got)
}
diff --git a/internal/vlchttp/vlchttp.go b/internal/vlchttp/vlchttp.go
index 928fae7..2202e15 100644
--- a/internal/vlchttp/vlchttp.go
+++ b/internal/vlchttp/vlchttp.go
@@ -14,7 +14,7 @@ import (
"strings"
"sync"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
var (
diff --git a/internal/winsys/autostart.go b/internal/winsys/autostart.go
index 95df684..9402779 100644
--- a/internal/winsys/autostart.go
+++ b/internal/winsys/autostart.go
@@ -4,19 +4,22 @@ import (
"crypto/sha256"
"encoding/hex"
"os"
+ "runtime"
"strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
)
// runNameBase is the name of the registry value that starts the program at login.
-const runNameBase = "MPCvibedRPC"
+const runNameBase = core.Name
-// runName is the registry value for run-at-login. A copy that uses a data folder of its own (MPCRPC_HOME: a portable
+// runName is the registry value for run-at-login. A copy that uses a data folder of its own (MPRP_HOME: a portable
// setup, a test, a development build) gets a value of its own, derived from that folder, so it can never switch the
// installed program's run-at-login on or off.
-func runName() string { return runNameFor(os.Getenv("MPCRPC_HOME")) }
+func runName() string { return runNameFor(os.Getenv("MPRP_HOME")) }
// runCommand is the registry value's command line. A copy with its own data folder passes it on with --home, so the
-// copy started at login uses that folder too (the registry cannot set MPCRPC_HOME the way a LaunchAgent can).
+// copy started at login uses that folder too (the registry cannot set MPRP_HOME the way a LaunchAgent can).
func runCommand(exe, home string) string {
cmd := `"` + exe + `" --background`
if home = strings.TrimRight(strings.TrimSpace(home), `\/`); home != "" {
@@ -25,13 +28,19 @@ func runCommand(exe, home string) string {
return cmd
}
-func runNameFor(home string) string {
+func runNameFor(home string) string { return nameFor(runNameBase, home) }
+
+// formerRunName is the run-at-login value (and login item) of this copy under the program's former name.
+func formerRunName() string { return nameFor(core.FormerName, os.Getenv("MPRP_HOME")) }
+
+// nameFor is the name base, for the copy with the data folder home ("": the default one).
+func nameFor(base, home string) string {
home = strings.ToLower(strings.TrimRight(strings.TrimSpace(home), `\/`))
if home == "" {
- return runNameBase
+ return base
}
sum := sha256.Sum256([]byte(home))
- return runNameBase + "-" + hex.EncodeToString(sum[:4])
+ return base + "-" + hex.EncodeToString(sum[:4])
}
// runKey is the registry key whose values start programs at login.
@@ -74,7 +83,7 @@ func runEntryNames(command, exe string) bool {
// writeRunValue makes the Run value name start exe. A value that is already right is left alone: no helper process
// at every start of the program.
func writeRunValue(name, exe string) bool {
- want := runCommand(exe, os.Getenv("MPCRPC_HOME"))
+ want := runCommand(exe, os.Getenv("MPRP_HOME"))
if cur, found := registryRunValue(name); found && cur == want {
return true
}
@@ -112,3 +121,79 @@ func SetAutoStart(enabled bool, exe string) bool {
}
return true
}
+
+// runRegistry is what the run-at-login migration needs of the registry: the Run values and Windows' own startup
+// switch for each (StartupApproved\Run). systemRegistry is the real one; the tests pass a map.
+type runRegistry struct {
+ run func(name string) (string, bool)
+ approved func(name string) ([]byte, bool)
+ setRun func(name, command string) bool
+ setApproved func(name string, data []byte) bool
+ deleteRun func(name string) bool
+ deleteApproved func(name string) bool
+}
+
+var systemRegistry = runRegistry{
+ run: registryRunValue,
+ approved: registryStartupApproved,
+ setRun: func(name, command string) bool {
+ return run("reg", "add", runKey, "/v", name, "/t", "REG_SZ", "/d", command, "/f").ok
+ },
+ setApproved: func(name string, data []byte) bool {
+ return run("reg", "add", startupApprovedKey, "/v", name, "/t", "REG_BINARY", "/d", hex.EncodeToString(data), "/f").ok
+ },
+ deleteRun: func(name string) bool { return run("reg", "delete", runKey, "/v", name, "/f").ok },
+ deleteApproved: func(name string) bool { return run("reg", "delete", startupApprovedKey, "/v", name, "/f").ok },
+}
+
+// MigrateAutoStart carries run-at-login over from the program's former name: the Run value (Windows), the
+// LaunchAgent (macOS) or the autostart entry (Linux) of that name is replaced by one of the current name that starts
+// this program file. On Windows a start switched off in Task Manager stays switched off. The program calls it at every
+// start; it does nothing when there is no entry of the former name. It gives a sentence for the log ("" when there was
+// nothing to do).
+func MigrateAutoStart(exe string) string {
+ home := os.Getenv("MPRP_HOME")
+ if !IsWindows {
+ h, _ := os.UserHomeDir()
+ return migrateLoginItem(runtime.GOOS, h, os.Getenv("XDG_CONFIG_HOME"), exe, home)
+ }
+ return migrateRunValue(systemRegistry, formerRunName(), runName(), runCommand(exe, home))
+}
+
+// migrateRunValue moves the Run value from (and its startup switch) to the name to, with command as its command line.
+// A value of that name that is there already is kept. When the new entry cannot be written, the former one is left as
+// it is: a start at login that still works beats none.
+func migrateRunValue(r runRegistry, from, to, command string) string {
+ _, hasRun := r.run(from)
+ approved, hasApproved := r.approved(from)
+ if !hasRun && !hasApproved {
+ return ""
+ }
+ if !hasRun { // a switch left without its value: Windows' leftover
+ r.deleteApproved(from)
+ return "Removed the leftover Task Manager entry " + from + " of the program's former name."
+ }
+ // the switch first: a start the user switched off must never come back on, even for a moment
+ wroteApproved := false
+ if _, has := r.approved(to); hasApproved && len(approved) > 0 && !has {
+ if !r.setApproved(to, approved) {
+ return "Could not carry the run-at-login entry " + from + " over to " + to + "; it is left as it was."
+ }
+ wroteApproved = true
+ }
+ if _, has := r.run(to); !has && !r.setRun(to, command) {
+ if wroteApproved {
+ r.deleteApproved(to)
+ }
+ return "Could not carry the run-at-login entry " + from + " over to " + to + "; it is left as it was."
+ }
+ r.deleteRun(from)
+ if hasApproved {
+ r.deleteApproved(from)
+ }
+ note := "Moved the run-at-login entry " + from + " to " + to + " (the program's new name)"
+ if startupDisabled(approved) {
+ note += "; it stays switched off in Task Manager"
+ }
+ return note + "."
+}
diff --git a/internal/winsys/autostart_test.go b/internal/winsys/autostart_test.go
index 4c29dd1..d17b39b 100644
--- a/internal/winsys/autostart_test.go
+++ b/internal/winsys/autostart_test.go
@@ -1,24 +1,30 @@
package winsys
-import "testing"
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+)
func TestRunName(t *testing.T) {
- // values computed independently in PowerShell: tools/ci/smoke.ps1 derives the same name for its own data folder
+ // values computed independently (PowerShell, sha256sum): tools/ci/smoke.ps1 derives the same name for its own data folder
for _, c := range []struct{ home, want, why string }{
- {"", "MPCvibedRPC", "the installed program keeps the plain name"},
- {" ", "MPCvibedRPC", "blank counts as unset"},
- {`C:\Temp\Home`, "MPCvibedRPC-3e950f5e", "a custom folder"},
- {`C:\Temp\HOME\`, "MPCvibedRPC-3e950f5e", "case and a trailing separator do not matter"},
- {`c:\temp\home/`, "MPCvibedRPC-3e950f5e", "case and a trailing separator do not matter"},
- {`D:\Portable\MPCvibedRPC\data`, "MPCvibedRPC-649c6423", "another custom folder"},
+ {"", "MPRP", "the installed program keeps the plain name"},
+ {" ", "MPRP", "blank counts as unset"},
+ {`C:\Temp\Home`, "MPRP-3e950f5e", "a custom folder"},
+ {`C:\Temp\HOME\`, "MPRP-3e950f5e", "case and a trailing separator do not matter"},
+ {`c:\temp\home/`, "MPRP-3e950f5e", "case and a trailing separator do not matter"},
+ {`D:\Portable\MPRP\data`, "MPRP-dd9ad258", "another custom folder"},
} {
if got := runNameFor(c.home); got != c.want {
t.Errorf("runNameFor(%q) = %q, want %q (%s)", c.home, got, c.want, c.why)
}
// the name follows the environment
- t.Setenv("MPCRPC_HOME", c.home)
+ t.Setenv("MPRP_HOME", c.home)
if got := runName(); got != c.want {
- t.Errorf("runName() with MPCRPC_HOME=%q = %q, want %q (%s)", c.home, got, c.want, c.why)
+ t.Errorf("runName() with MPRP_HOME=%q = %q, want %q (%s)", c.home, got, c.want, c.why)
}
}
if runNameFor(`C:\a`) == runNameFor(`C:\b`) {
@@ -31,11 +37,11 @@ func TestRunEntryNames(t *testing.T) {
command, exe string
want bool
}{
- {`"C:\Apps\MPCvibedRPC.exe" --background`, `C:\Other\MPCvibedRPC.exe`, true}, // the folder is not compared
- {`"c:\apps\mpcvibedrpc.EXE" --background`, `MPCvibedRPC.exe`, true}, // case does not matter
- {`"D:\Portable\MPCvibedRPC.exe" --background --home "D:\Portable\data"`, `MPCvibedRPC.exe`, true},
- {`"C:\Apps\OtherProgram.exe" --background`, `MPCvibedRPC.exe`, false},
- {``, `MPCvibedRPC.exe`, false},
+ {`"C:\Apps\MPRP.exe" --background`, `C:\Other\MPRP.exe`, true}, // the folder is not compared
+ {`"c:\apps\mprp.EXE" --background`, `MPRP.exe`, true}, // case does not matter
+ {`"D:\Portable\MPRP.exe" --background --home "D:\Portable\data"`, `MPRP.exe`, true},
+ {`"C:\Apps\OtherProgram.exe" --background`, `MPRP.exe`, false},
+ {``, `MPRP.exe`, false},
} {
if got := runEntryNames(c.command, c.exe); got != c.want {
t.Errorf("runEntryNames(%q, %q) = %v, want %v", c.command, c.exe, got, c.want)
@@ -45,11 +51,147 @@ func TestRunEntryNames(t *testing.T) {
func TestRunCommandCarriesTheDataFolder(t *testing.T) {
for _, c := range []struct{ name, exe, home, want string }{
- {"default copy", `C:\Apps\MPCvibedRPC.exe`, "", `"C:\Apps\MPCvibedRPC.exe" --background`},
- {"own data folder", `D:\Portable\MPCvibedRPC.exe`, `D:\Portable\data\`, `"D:\Portable\MPCvibedRPC.exe" --background --home "D:\Portable\data"`},
+ {"default copy", `C:\Apps\MPRP.exe`, "", `"C:\Apps\MPRP.exe" --background`},
+ {"own data folder", `D:\Portable\MPRP.exe`, `D:\Portable\data\`, `"D:\Portable\MPRP.exe" --background --home "D:\Portable\data"`},
} {
if got := runCommand(c.exe, c.home); got != c.want {
t.Errorf("%s: %s", c.name, got)
}
}
}
+
+// fakeRegistry is a runRegistry over two maps, as the migration sees the Run key and StartupApproved\Run.
+type fakeRegistry struct {
+ runs map[string]string
+ approvals map[string][]byte
+ refuse bool // every write fails
+}
+
+func (f *fakeRegistry) registry() runRegistry {
+ return runRegistry{
+ run: func(n string) (string, bool) { v, ok := f.runs[n]; return v, ok },
+ approved: func(n string) ([]byte, bool) { v, ok := f.approvals[n]; return v, ok },
+ setRun: func(n, c string) bool {
+ if f.refuse {
+ return false
+ }
+ f.runs[n] = c
+ return true
+ },
+ setApproved: func(n string, d []byte) bool {
+ if f.refuse {
+ return false
+ }
+ f.approvals[n] = d
+ return true
+ },
+ deleteRun: func(n string) bool { delete(f.runs, n); return true },
+ deleteApproved: func(n string) bool { delete(f.approvals, n); return true },
+ }
+}
+
+func TestFormerRunName(t *testing.T) {
+ t.Setenv("MPRP_HOME", "")
+ if n := formerRunName(); n != "MPCvibedRPC" {
+ t.Errorf("formerRunName() = %q", n)
+ }
+ t.Setenv("MPRP_HOME", `C:\Temp\Home`)
+ if n := formerRunName(); n != "MPCvibedRPC-3e950f5e" { // the same folder gives the same suffix as runNameFor
+ t.Errorf("formerRunName() with a data folder = %q", n)
+ }
+}
+
+func TestMigrateRunValue(t *testing.T) {
+ const cmd = `"C:\Apps\MPRP.exe" --background`
+ disabled, enabled := []byte{3, 0, 0, 0}, []byte{2, 0, 0, 0}
+ for _, c := range []struct {
+ name string
+ runs map[string]string
+ approvals map[string][]byte
+ refuse bool
+ wantRuns map[string]string
+ wantApprovals map[string][]byte
+ wantNote string
+ }{
+ {name: "nothing of the former name",
+ runs: map[string]string{"Other": "x"}, wantRuns: map[string]string{"Other": "x"}},
+ {name: "on: moved, pointing at this program file",
+ runs: map[string]string{"MPCvibedRPC": `"C:\Old\MPCvibedRPC.exe" --background`},
+ wantRuns: map[string]string{"MPRP": cmd}, wantNote: "Moved the run-at-login entry MPCvibedRPC to MPRP"},
+ {name: "switched off in Task Manager: stays off",
+ runs: map[string]string{"MPCvibedRPC": "x"}, approvals: map[string][]byte{"MPCvibedRPC": disabled},
+ wantRuns: map[string]string{"MPRP": cmd}, wantApprovals: map[string][]byte{"MPRP": disabled},
+ wantNote: "stays switched off"},
+ {name: "switched on in Task Manager: the switch comes along",
+ runs: map[string]string{"MPCvibedRPC": "x"}, approvals: map[string][]byte{"MPCvibedRPC": enabled},
+ wantRuns: map[string]string{"MPRP": cmd}, wantApprovals: map[string][]byte{"MPRP": enabled},
+ wantNote: "Moved"},
+ {name: "a value of the new name is kept",
+ runs: map[string]string{"MPCvibedRPC": "old", "MPRP": "mine"},
+ wantRuns: map[string]string{"MPRP": "mine"}, wantNote: "Moved"},
+ {name: "a leftover switch without its value goes",
+ approvals: map[string][]byte{"MPCvibedRPC": disabled}, wantNote: "leftover"},
+ {name: "writing fails: the former entry stays as it was",
+ runs: map[string]string{"MPCvibedRPC": "x"}, approvals: map[string][]byte{"MPCvibedRPC": disabled}, refuse: true,
+ wantRuns: map[string]string{"MPCvibedRPC": "x"}, wantApprovals: map[string][]byte{"MPCvibedRPC": disabled},
+ wantNote: "left as it was"},
+ } {
+ f := &fakeRegistry{runs: map[string]string{}, approvals: map[string][]byte{}, refuse: c.refuse}
+ for k, v := range c.runs {
+ f.runs[k] = v
+ }
+ for k, v := range c.approvals {
+ f.approvals[k] = v
+ }
+ note := migrateRunValue(f.registry(), "MPCvibedRPC", "MPRP", cmd)
+ if (c.wantNote == "") != (note == "") || !strings.Contains(note, c.wantNote) {
+ t.Errorf("%s: note %q, want one with %q", c.name, note, c.wantNote)
+ }
+ if c.wantRuns == nil {
+ c.wantRuns = map[string]string{}
+ }
+ if c.wantApprovals == nil {
+ c.wantApprovals = map[string][]byte{}
+ }
+ if !reflect.DeepEqual(f.runs, c.wantRuns) || !reflect.DeepEqual(f.approvals, c.wantApprovals) {
+ t.Errorf("%s: runs %v approvals %v, want %v %v", c.name, f.runs, f.approvals, c.wantRuns, c.wantApprovals)
+ }
+ }
+}
+
+func TestMigrateLoginItem(t *testing.T) {
+ for _, goos := range []string{"linux", "darwin"} {
+ t.Setenv("MPRP_HOME", "")
+ home := t.TempDir()
+ exe := "/opt/MPRP/MPRP"
+ from := loginItemPathNamed("MPCvibedRPC", goos, home, "")
+ to := loginItemPath(goos, home, "")
+ if note := migrateLoginItem(goos, home, "", exe, ""); note != "" {
+ t.Errorf("%s: nothing to move, but %q", goos, note)
+ }
+ os.MkdirAll(filepath.Dir(from), 0o755)
+ os.WriteFile(from, []byte("the former login item"), 0o644)
+ note := migrateLoginItem(goos, home, "", exe, "")
+ if !strings.HasPrefix(note, "Moved the login item") {
+ t.Fatalf("%s: note %q", goos, note)
+ }
+ if _, err := os.Stat(from); err == nil {
+ t.Errorf("%s: the former login item is still there", goos)
+ }
+ b, err := os.ReadFile(to)
+ if err != nil || string(b) != loginItem(goos, exe, "") {
+ t.Errorf("%s: new login item %q (%v)", goos, b, err)
+ }
+ // a translocated macOS app cannot be started at login: the former item stays
+ if goos == "darwin" {
+ os.Remove(to)
+ os.WriteFile(from, []byte("the former login item"), 0o644)
+ if note := migrateLoginItem(goos, home, "", "/private/var/folders/x/AppTranslocation/y/MPRP.app/Contents/MacOS/MPRP", ""); !strings.Contains(note, "left as it was") {
+ t.Errorf("translocated: note %q", note)
+ }
+ if _, err := os.Stat(from); err != nil {
+ t.Error("translocated: the former login item was removed")
+ }
+ }
+ }
+}
diff --git a/internal/winsys/autostart_unix.go b/internal/winsys/autostart_unix.go
index 01e19cb..3f966b7 100644
--- a/internal/winsys/autostart_unix.go
+++ b/internal/winsys/autostart_unix.go
@@ -6,14 +6,21 @@ import (
"path/filepath"
"runtime"
"strings"
+
+ "github.com/CptPakundo/MPRP/internal/core"
)
// Run at login on macOS (a LaunchAgent) and Linux (an XDG autostart entry, which every desktop reads). The file is the
-// source of truth, as the registry value is on Windows; a copy with its own MPCRPC_HOME gets a file of its own.
+// source of truth, as the registry value is on Windows; a copy with its own MPRP_HOME gets a file of its own.
// loginItemPath is where the login item of this copy lives on goos ("" when the home folder is unknown).
func loginItemPath(goos, home, xdgConfig string) string {
- name := strings.ToLower(runName())
+ return loginItemPathNamed(runName(), goos, home, xdgConfig)
+}
+
+// loginItemPathNamed is where the login item called name lives on goos.
+func loginItemPathNamed(name, goos, home, xdgConfig string) string {
+ name = strings.ToLower(name)
if goos == "darwin" {
if home == "" {
return ""
@@ -30,7 +37,7 @@ func loginItemPath(goos, home, xdgConfig string) string {
}
// loginItem is the content of the login item that starts exe in the background (with this copy's data folder).
-func loginItem(goos, exe, mpcHome string) string {
+func loginItem(goos, exe, dataHome string) string {
if goos == "darwin" {
x := html.EscapeString
var b strings.Builder
@@ -46,17 +53,17 @@ func loginItem(goos, exe, mpcHome string) string {
--background
`)
- if mpcHome != "" {
- b.WriteString("\tEnvironmentVariables\n\t\n\t\tMPCRPC_HOME\n\t\t" + x(mpcHome) + "\n\t\n")
+ if dataHome != "" {
+ b.WriteString("\tEnvironmentVariables\n\t\n\t\tMPRP_HOME\n\t\t" + x(dataHome) + "\n\t\n")
}
b.WriteString("\tRunAtLoad\n\t\n\tProcessType\n\tInteractive\n\n\n")
return b.String()
}
cmd := execQuote(exe) + " --background"
- if mpcHome != "" {
- cmd = "env " + execQuote("MPCRPC_HOME="+mpcHome) + " " + cmd
+ if dataHome != "" {
+ cmd = "env " + execQuote("MPRP_HOME="+dataHome) + " " + cmd
}
- return "[Desktop Entry]\nType=Application\nName=MPCvibedRPC\nComment=Shows what your video player is playing on Discord\n" +
+ return "[Desktop Entry]\nType=Application\nName=MPRP\nComment=Shows what your video player is playing on Discord\n" +
"Exec=" + cmd + "\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"
}
@@ -126,5 +133,30 @@ func setLoginItem(enabled bool, exe string) bool {
if os.MkdirAll(filepath.Dir(p), 0o755) != nil {
return false
}
- return os.WriteFile(p, []byte(loginItem(runtime.GOOS, exe, os.Getenv("MPCRPC_HOME"))), 0o644) == nil
+ return os.WriteFile(p, []byte(loginItem(runtime.GOOS, exe, os.Getenv("MPRP_HOME"))), 0o644) == nil
+}
+
+// migrateLoginItem replaces the login item of the program's former name (macOS: io.github.cptpakundo..plist; Linux: .desktop) with one of the current name that starts exe, and removes the former
+// one. A login item of the current name that is there already is kept. When the new one cannot be written (a
+// translocated app, an unwritable folder) the former one is left as it is.
+func migrateLoginItem(goos, home, xdgConfig, exe, mprpHome string) string {
+ from := loginItemPathNamed(nameFor(core.FormerName, mprpHome), goos, home, xdgConfig)
+ to := loginItemPathNamed(nameFor(runNameBase, mprpHome), goos, home, xdgConfig)
+ if from == "" || to == "" {
+ return ""
+ }
+ if _, err := os.Stat(from); err != nil {
+ return ""
+ }
+ if _, err := os.Stat(to); err != nil {
+ if translocated(exe) || os.MkdirAll(filepath.Dir(to), 0o755) != nil ||
+ os.WriteFile(to, []byte(loginItem(goos, exe, mprpHome)), 0o644) != nil {
+ return "Could not carry the login item " + from + " over to " + to + "; it is left as it was."
+ }
+ }
+ if err := os.Remove(from); err != nil {
+ return "Wrote the login item " + to + " but could not remove " + from + ": " + err.Error()
+ }
+ return "Moved the login item " + from + " to " + to + " (the program's new name)."
}
diff --git a/internal/winsys/autostart_windows_test.go b/internal/winsys/autostart_windows_test.go
index f5d0339..a3709a2 100644
--- a/internal/winsys/autostart_windows_test.go
+++ b/internal/winsys/autostart_windows_test.go
@@ -8,10 +8,10 @@ import (
// The registry read gives what `reg query` gave. Read-only: it only looks at values, and never writes.
func TestRegistryRunValueMatchesRegExe(t *testing.T) {
- if _, ok := registryRunValue("MPCvibedRPC-test-no-such-value"); ok {
+ if _, ok := registryRunValue("MPRP-test-no-such-value"); ok {
t.Error("a value that does not exist was found")
}
- for _, name := range []string{"MPCvibedRPC", "MPCvibedRPC-test-no-such-value"} {
+ for _, name := range []string{"MPRP", "MPRP-test-no-such-value"} {
r := run("reg", "query", runKey, "/v", name)
data, ok := registryRunValue(name)
if ok != r.ok {
@@ -26,16 +26,16 @@ func TestRegistryRunValueMatchesRegExe(t *testing.T) {
}
// End to end against the real registry: opt-in, because it writes the Run value that belongs to a throwaway data
-// folder (MPCRPC_HOME) and removes it again. It never touches the plain "MPCvibedRPC" value.
+// folder (MPRP_HOME) and removes it again. It never touches the plain "MPRP" value.
func TestAutostartRegistryRoundTrip(t *testing.T) {
- if os.Getenv("MPCRPC_TEST_REGISTRY") != "1" {
- t.Skip("set MPCRPC_TEST_REGISTRY=1 to write and remove a Run value for a throwaway data folder")
+ if os.Getenv("MPRP_TEST_REGISTRY") != "1" {
+ t.Skip("set MPRP_TEST_REGISTRY=1 to write and remove a Run value for a throwaway data folder")
}
- t.Setenv("MPCRPC_HOME", t.TempDir())
+ t.Setenv("MPRP_HOME", t.TempDir())
if runName() == runNameBase {
t.Fatal("the test must use a value name of its own")
}
- exe := `C:\Test\MPCvibedRPC.exe`
+ exe := `C:\Test\MPRP.exe`
t.Cleanup(func() { SetAutoStart(false, exe) })
if GetAutoStart(exe) {
t.Fatal("on before it was set")
@@ -50,11 +50,47 @@ func TestAutostartRegistryRoundTrip(t *testing.T) {
t.Error("a different program name must not match")
}
data, ok := registryRunValue(runName())
- if !ok || data != runCommand(exe, os.Getenv("MPCRPC_HOME")) {
- t.Errorf("stored command %q, want %q", data, runCommand(exe, os.Getenv("MPCRPC_HOME")))
+ if !ok || data != runCommand(exe, os.Getenv("MPRP_HOME")) {
+ t.Errorf("stored command %q, want %q", data, runCommand(exe, os.Getenv("MPRP_HOME")))
}
SetAutoStart(false, exe)
if GetAutoStart(exe) {
t.Error("still on after removing it")
}
}
+
+// The migration from the former name against the real registry: opt-in like the test above, and only with the values
+// of a throwaway data folder (never the plain "MPRP" or former-name values).
+func TestAutostartMigrationRegistry(t *testing.T) {
+ if os.Getenv("MPRP_TEST_REGISTRY") != "1" {
+ t.Skip("set MPRP_TEST_REGISTRY=1 to write and remove Run values for a throwaway data folder")
+ }
+ t.Setenv("MPRP_HOME", t.TempDir())
+ from, to := formerRunName(), runName()
+ if to == runNameBase || !strings.Contains(from, "-") {
+ t.Fatal("the test must use value names of its own")
+ }
+ exe := `C:\Test\MPRP.exe`
+ r := systemRegistry
+ t.Cleanup(func() {
+ for _, n := range []string{from, to} {
+ r.deleteRun(n)
+ r.deleteApproved(n)
+ }
+ })
+ if !r.setRun(from, `"C:\Test\Old.exe" --background`) || !r.setApproved(from, []byte{3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) {
+ t.Fatal("could not write the former values")
+ }
+ if note := MigrateAutoStart(exe); !strings.Contains(note, "stays switched off") {
+ t.Errorf("note %q", note)
+ }
+ if _, ok := registryRunValue(from); ok {
+ t.Error("the former Run value is still there")
+ }
+ if data, ok := registryRunValue(to); !ok || data != runCommand(exe, os.Getenv("MPRP_HOME")) {
+ t.Errorf("new Run value %q (%v)", data, ok)
+ }
+ if !startupDisabled(approvedData(to)) || GetAutoStart(exe) {
+ t.Error("the start switched off in Task Manager came back on")
+ }
+}
diff --git a/internal/winsys/browser.go b/internal/winsys/browser.go
index 3be4ac4..acce355 100644
--- a/internal/winsys/browser.go
+++ b/internal/winsys/browser.go
@@ -16,7 +16,9 @@ func usesProfile(cmdline, profile string) bool {
return false
}
profile = strings.TrimRight(profile, `\/`)
- cl := strings.ToLower(cmdline)
+ // A browser that restarts itself (Edge does, on some starts) writes the folder in quotes after the equals sign
+ // (--user-data-dir="C:\...\window"): that form is read like the plain one.
+ cl := strings.ReplaceAll(strings.ToLower(cmdline), `--user-data-dir="`, "--user-data-dir=")
flag := "--user-data-dir=" + strings.ToLower(profile)
for from := 0; ; {
i := strings.Index(cl[from:], flag)
diff --git a/internal/winsys/browser_other_test.go b/internal/winsys/browser_other_test.go
index e43170e..17dbdc5 100644
--- a/internal/winsys/browser_other_test.go
+++ b/internal/winsys/browser_other_test.go
@@ -9,14 +9,14 @@ import (
func TestProfilePids(t *testing.T) {
ps := ` 1 /sbin/init
- 200 /opt/google/chrome/chrome --app=http://127.0.0.1:47654/?t=x --user-data-dir=/home/someone/.local/share/MPCvibedRPC/window --no-first-run
- 201 /opt/google/chrome/chrome --type=renderer --user-data-dir=/home/someone/.local/share/MPCvibedRPC/window --lang=en
- 202 /opt/google/chrome/chrome --user-data-dir=/home/someone/.local/share/MPCvibedRPC/window2
+ 200 /opt/google/chrome/chrome --app=http://127.0.0.1:47654/?t=x --user-data-dir=/home/someone/.local/share/MPRP/window --no-first-run
+ 201 /opt/google/chrome/chrome --type=renderer --user-data-dir=/home/someone/.local/share/MPRP/window --lang=en
+ 202 /opt/google/chrome/chrome --user-data-dir=/home/someone/.local/share/MPRP/window2
203 /opt/google/chrome/chrome
- 300 /home/someone/MPCvibedRPC --user-data-dir=/home/someone/.local/share/MPCvibedRPC/window
+ 300 /home/someone/MPRP --user-data-dir=/home/someone/.local/share/MPRP/window
bad line
`
- got := profilePids(ps, "/home/someone/.local/share/MPCvibedRPC/window", 300)
+ got := profilePids(ps, "/home/someone/.local/share/MPRP/window", 300)
if !reflect.DeepEqual(got, []int{200, 201}) {
t.Errorf("got %v, want [200 201] (not another profile, not the user's browser, not ourselves)", got)
}
diff --git a/internal/winsys/browser_test.go b/internal/winsys/browser_test.go
index 4bc9d15..b6afe0e 100644
--- a/internal/winsys/browser_test.go
+++ b/internal/winsys/browser_test.go
@@ -10,7 +10,7 @@ import (
)
func TestUsesProfile(t *testing.T) {
- const p = `C:\Users\Someone\AppData\Local\MPCvibedRPC\window`
+ const p = `C:\Users\Someone\AppData\Local\MPRP\window`
cases := []struct {
cmd string
want bool
@@ -19,7 +19,10 @@ func TestUsesProfile(t *testing.T) {
{`msedge.exe --type=gpu-process --user-data-dir=` + p + ` --lang=en-GB`, true},
{`msedge.exe --user-data-dir=` + p, true},
{`msedge.exe --user-data-dir=` + p + `\`, true},
- {`msedge.exe --USER-data-DIR=` + `c:\users\someone\appdata\local\mpcvibedrpc\WINDOW`, true},
+ {`msedge.exe --USER-data-DIR=` + `c:\users\someone\appdata\local\mprp\WINDOW`, true},
+ // Edge restarted by itself writes the folder in quotes after the equals sign (seen on a real first launch)
+ {`"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --user-data-dir="` + p + `" --app=http://127.0.0.1:47654/ --flag-switches-begin --flag-switches-end`, true},
+ {`msedge.exe --user-data-dir="` + p + `2" --lang=en`, false},
{`msedge.exe --user-data-dir=` + p + `2 --lang=en`, false}, // a different folder with the same prefix
{`msedge.exe --user-data-dir=` + p + `-old`, false}, // likewise
{`msedge.exe --user-data-dir=C:\Users\Someone\Other`, false}, // another profile
diff --git a/internal/winsys/focus_other.go b/internal/winsys/focus_other.go
index b103ae1..03cb712 100644
--- a/internal/winsys/focus_other.go
+++ b/internal/winsys/focus_other.go
@@ -16,4 +16,4 @@ func SettingsWindow(profileDir string) uintptr { return 0 }
func WindowState(h uintptr) (exists, minimised bool) { return false, false }
// CloseWindow does nothing here (see SettingsWindow).
-func CloseWindow(h uintptr) {}
+func CloseWindow(h uintptr) bool { return false }
diff --git a/internal/winsys/focus_windows.go b/internal/winsys/focus_windows.go
index c04b725..c4a8fe3 100644
--- a/internal/winsys/focus_windows.go
+++ b/internal/winsys/focus_windows.go
@@ -3,6 +3,7 @@
package winsys
import (
+ "os"
"sync"
"syscall"
"unsafe"
@@ -27,13 +28,18 @@ var (
const swRestore = 9
-// topWindow is what the choice of a window to bring forward needs to know about a top-level window.
+// topWindow is what the choice of a window to bring forward, or to give the program's icon (taskbarWindow), needs to
+// know about a top-level window.
type topWindow struct {
Handle uintptr
Pid uint32
Visible bool
Titled bool
Minimised bool
+ Child bool // WS_CHILD: not a top-level window after all (a WinEvent can be about one)
+ Owned bool // it has an owner window (a bubble, a dialog)
+ Tool bool // WS_EX_TOOLWINDOW: never on the taskbar
+ AppWindow bool // WS_EX_APPWINDOW: on the taskbar even when owned
}
// pickWindow takes the first window (EnumWindows lists them from the top of the stacking order) that belongs to one
@@ -50,13 +56,76 @@ func pickWindow(wins []topWindow, pids map[uint32]bool) (topWindow, bool) {
// collectWindow is the EnumWindows callback: it notes each top-level window; returning 1 goes on with the next.
func collectWindow(hwnd uintptr, _ uintptr) uintptr {
+ enumFound = append(enumFound, describeWindow(hwnd))
+ return 1
+}
+
+const (
+ gwOwner = 4
+ wsChild = 0x40000000
+ wsExToolWindow = 0x00000080
+ wsExAppWindow = 0x00040000
+)
+
+var (
+ pGetWindow = user32.NewProc("GetWindow")
+ pGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW")
+ gwlStyle = ^uintptr(15) // GWL_STYLE (-16)
+ gwlExStyle = ^uintptr(19) // GWL_EXSTYLE (-20)
+)
+
+// describeWindow reads what topWindow holds about the window hwnd (a window that is gone has pid 0).
+func describeWindow(hwnd uintptr) topWindow {
var pid uint32
pGetWindowThreadProcessID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
vis, _, _ := pIsWindowVisible.Call(hwnd)
- n, _, _ := pGetWindowTextLengthW.Call(hwnd)
+ // GetWindowTextLength sends a message to a window of this process, and waits for the thread that owns it: when
+ // that thread is the one waiting for this list (the icon keeper's), both would wait for good. The program's own
+ // windows are never the settings window, so their titles are not asked for.
+ var n uintptr
+ if pid != ownPid {
+ n, _, _ = pGetWindowTextLengthW.Call(hwnd)
+ }
ic, _, _ := pIsIconic.Call(hwnd)
- enumFound = append(enumFound, topWindow{Handle: hwnd, Pid: pid, Visible: vis != 0, Titled: n > 0, Minimised: ic != 0})
- return 1
+ owner, _, _ := pGetWindow.Call(hwnd, gwOwner)
+ style, _, _ := pGetWindowLongPtr.Call(hwnd, gwlStyle)
+ ex, _, _ := pGetWindowLongPtr.Call(hwnd, gwlExStyle)
+ return topWindow{Handle: hwnd, Pid: pid, Visible: vis != 0, Titled: n > 0, Minimised: ic != 0,
+ Child: style&wsChild != 0, Owned: owner != 0, Tool: ex&wsExToolWindow != 0, AppWindow: ex&wsExAppWindow != 0}
+}
+
+// ownPid is this process's id (describeWindow leaves this process's own windows' titles alone).
+var ownPid = uint32(os.Getpid())
+
+// topWindows lists the top-level windows, from the top of the stacking order.
+func topWindows() []topWindow {
+ enumMu.Lock()
+ defer enumMu.Unlock()
+ enumFound = nil
+ pEnumWindows.Call(enumWindowsCallback, 0)
+ wins := enumFound
+ enumFound = nil
+ return wins
+}
+
+var (
+ // made once, as enumWindowsCallback: it only notes each window's handle
+ enumHandlesCallback = syscall.NewCallback(func(hwnd, _ uintptr) uintptr {
+ enumHandles = append(enumHandles, hwnd)
+ return 1
+ })
+ enumHandles []uintptr // under enumMu
+)
+
+// topWindowHandles lists the handles of the top-level windows, without reading anything else about them.
+func topWindowHandles() []uintptr {
+ enumMu.Lock()
+ defer enumMu.Unlock()
+ enumHandles = nil
+ pEnumWindows.Call(enumHandlesCallback, 0)
+ hwnds := enumHandles
+ enumHandles = nil
+ return hwnds
}
// FocusWindow brings the settings window that is already open to the front (restoring it when minimised). It looks
@@ -88,13 +157,7 @@ func findWindow(profileDir string) (topWindow, bool) {
if len(pids) == 0 {
return topWindow{}, false
}
- enumMu.Lock()
- enumFound = nil
- pEnumWindows.Call(enumWindowsCallback, 0)
- wins := enumFound
- enumFound = nil
- enumMu.Unlock()
- return pickWindow(wins, pids)
+ return pickWindow(topWindows(), pids)
}
// AllowForeground lets the process pid take the foreground. A second start of the program was launched by the user
@@ -122,7 +185,9 @@ func WindowState(h uintptr) (exists, minimised bool) {
return true, ic != 0
}
-// CloseWindow asks the window h to close, as its X button does (the browser then ends by itself).
-func CloseWindow(h uintptr) {
- pPostMessage.Call(h, wmClose, 0, 0)
+// CloseWindow asks the window h to close, as its X button does (the browser then ends by itself). It reports whether
+// the request was delivered (the window may still refuse it).
+func CloseWindow(h uintptr) bool {
+ r, _, _ := pPostMessage.Call(h, wmClose, 0, 0)
+ return r != 0
}
diff --git a/internal/winsys/formerenv_test.go b/internal/winsys/formerenv_test.go
new file mode 100644
index 0000000..d41f359
--- /dev/null
+++ b/internal/winsys/formerenv_test.go
@@ -0,0 +1,28 @@
+package winsys
+
+import (
+ "os"
+ "testing"
+
+ "github.com/CptPakundo/MPRP/internal/core"
+)
+
+// onlyFormerHome is the environment a copy of the former version gives the copy it updated itself to, when it has a
+// data folder of its own: MPCRPC_HOME and no MPRP_HOME. main adopts it first (core.AdoptFormerEnv).
+func onlyFormerHome(t *testing.T, home string) {
+ t.Setenv("MPRP_HOME", "")
+ os.Unsetenv("MPRP_HOME")
+ t.Setenv("MPCRPC_HOME", home)
+ core.AdoptFormerEnv()
+}
+
+// The run-at-login value follows the former variable, so the updated copy never touches the installed program's.
+func TestRunNameFollowsTheFormerHomeVariable(t *testing.T) {
+ onlyFormerHome(t, `C:\Temp\Home`)
+ if got := runName(); got != "MPRP-3e950f5e" {
+ t.Errorf("runName() = %q, want the custom folder's name", got)
+ }
+ if got := formerRunName(); got != nameFor(core.FormerName, `C:\Temp\Home`) {
+ t.Errorf("formerRunName() = %q", got)
+ }
+}
diff --git a/internal/winsys/formerenv_windows_test.go b/internal/winsys/formerenv_windows_test.go
new file mode 100644
index 0000000..ea4258b
--- /dev/null
+++ b/internal/winsys/formerenv_windows_test.go
@@ -0,0 +1,13 @@
+package winsys
+
+import "testing"
+
+// The single-instance mutexes follow the former variable too: the updated copy waits for the old copy's own mutex,
+// never for the installed program's.
+func TestInstanceNamesFollowTheFormerHomeVariable(t *testing.T) {
+ onlyFormerHome(t, `C:\Temp\Home`)
+ got := instanceNames()
+ if len(got) != 2 || got[0] != `Local\MPRP-3e950f5e-single-instance` || got[1] != `Local\`+formerRunName()+`-single-instance` || formerRunName() == "MPCvibedRPC" {
+ t.Errorf("instanceNames() = %q", got)
+ }
+}
diff --git a/internal/winsys/hardening_test.go b/internal/winsys/hardening_test.go
index a864a6c..330ae2c 100644
--- a/internal/winsys/hardening_test.go
+++ b/internal/winsys/hardening_test.go
@@ -49,7 +49,7 @@ func TestWebAddress(t *testing.T) {
func TestSetupRunsOnceAtATime(t *testing.T) {
setupLock.Lock()
defer setupLock.Unlock()
- r := EnableMpcWebInterface(13579, true, "", 0, "", "")
+ r := SetUpPlayers(13579, true, "", 0, "", "")
if r.OK || !strings.Contains(r.Message, "already running") {
t.Errorf("a second setup gave %+v, want the already-running answer", r)
}
diff --git a/internal/winsys/ini.go b/internal/winsys/ini.go
index 9ec2405..8be8d11 100644
--- a/internal/winsys/ini.go
+++ b/internal/winsys/ini.go
@@ -7,7 +7,7 @@ import (
"strings"
"unicode/utf16"
- "github.com/CptPakundo/MPCvibedRPC/internal/core"
+ "github.com/CptPakundo/MPRP/internal/core"
)
var (
@@ -112,7 +112,7 @@ func writeFileAtomic(file string, data []byte) error {
return os.WriteFile(file, data, perm)
}
}
- tmp := file + ".mpcvibedrpc.tmp"
+ tmp := file + ".mprp.tmp"
if err := os.WriteFile(tmp, data, perm); err != nil {
_ = os.Remove(tmp) // a part may have been written
return os.WriteFile(file, data, perm)
diff --git a/internal/winsys/macapp_darwin.go b/internal/winsys/macapp_darwin.go
index ebe7b42..e55762a 100644
--- a/internal/winsys/macapp_darwin.go
+++ b/internal/winsys/macapp_darwin.go
@@ -7,9 +7,10 @@ package winsys
/*
#cgo CFLAGS: -x objective-c -fobjc-arc -mmacosx-version-min=11.0
-#cgo LDFLAGS: -framework Cocoa -framework WebKit -mmacosx-version-min=11.0
+#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UserNotifications -mmacosx-version-min=11.0
#import
#import
+#import
#include
#include
@@ -19,7 +20,7 @@ static NSWindow *window;
static WKWebView *web;
static atomic_int pending; // the menu command waiting for the Go side: 1 open, 2 start/stop, 3 quit, 4 hide what is watched, 5 the title on streams
-@interface MRController : NSObject
+@interface MRController : NSObject
@end
@implementation MRController
@@ -34,6 +35,18 @@ static atomic_int pending; // the menu command waiting for the Go side: 1 open,
- (void)windowWillClose:(NSNotification *)n { window = nil; web = nil; }
+// A click on one of the program's notifications opens the settings window.
+- (void)userNotificationCenter:(UNUserNotificationCenter *)c didReceiveNotificationResponse:(UNNotificationResponse *)r
+ withCompletionHandler:(void (^)(void))done {
+ if ([r.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) atomic_store(&pending, 1);
+ done();
+}
+// The app counts as in front while its window is: show the notification all the same.
+- (void)userNotificationCenter:(UNUserNotificationCenter *)c willPresentNotification:(UNNotification *)n
+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))done {
+ done(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList);
+}
+
// alert() and confirm() from the page (WebKit shows nothing unless the app does)
- (void)webView:(WKWebView *)v runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(void))done {
@@ -98,6 +111,9 @@ static void macRunApp(void) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
controller = [MRController new];
NSApp.delegate = controller;
+ // The notification centre needs a bundle identifier: a bare program (a test build) has none, and asking for
+ // the centre would stop it with an exception. The delegate is set before the app runs, as a click must find it.
+ if ([NSBundle mainBundle].bundleIdentifier) [UNUserNotificationCenter currentNotificationCenter].delegate = controller;
mainMenu();
[NSApp run];
}
@@ -130,7 +146,7 @@ static void macTrayCreate(const void *png, int len, const char *tip) {
hideItem = menuItem(m, @"Hide what I'm watching", @"", 4);
streamItem = menuItem(m, @"Show the title on my streams", @"", 5);
[m addItem:[NSMenuItem separatorItem]];
- menuItem(m, @"Quit MPCvibedRPC", @"q", 3);
+ menuItem(m, @"Quit MPRP", @"q", 3);
item.menu = m;
});
}
@@ -178,7 +194,7 @@ static void macShowWindow(const char *url) {
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
backing:NSBackingStoreBuffered defer:NO];
window.releasedWhenClosed = NO;
- window.title = @"MPCvibedRPC";
+ window.title = @"MPRP";
window.delegate = controller;
window.minSize = NSMakeSize(420, 400);
// minimized, the window shows in the Dock as the app's logo (a web view's snapshot comes out blank)
@@ -198,6 +214,24 @@ static void macShowWindow(const char *url) {
});
}
+// macNotify shows a notification: macOS asks the user once whether the app may (the answer is kept in System
+// Settings > Notifications). It returns 0 when the program cannot notify at all (not an app bundle); whether the
+// user allows it is known only later, so 1 means handed to macOS.
+static int macNotify(const char *title, const char *text) {
+ if (![NSBundle mainBundle].bundleIdentifier) return 0; // see macRunApp
+ NSString *t = [NSString stringWithUTF8String:title], *b = [NSString stringWithUTF8String:text];
+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
+ [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *err) {
+ if (!granted) return;
+ UNMutableNotificationContent *m = [UNMutableNotificationContent new];
+ m.title = t ? t : @"MPRP";
+ m.body = b ? b : @"";
+ UNNotificationRequest *r = [UNNotificationRequest requestWithIdentifier:[NSUUID UUID].UUIDString content:m trigger:nil];
+ [center addNotificationRequest:r withCompletionHandler:nil];
+ }];
+ return 1;
+}
+
static void macCloseWindow(void) {
dispatch_async(dispatch_get_main_queue(), ^{ [window close]; });
}
@@ -279,7 +313,7 @@ type menuState struct {
}
func (t *Tray) state() menuState {
- st := menuState{tip: "MPCvibedRPC"}
+ st := menuState{tip: "MPRP"}
if t.o.Tooltip != nil {
st.tip = t.o.Tooltip()
}
@@ -362,5 +396,15 @@ func (t *Tray) Close() {
})
}
-// Balloon would show a notification; the menu bar icon has none (the window shows updates).
-func (t *Tray) Balloon(title, text string) bool { return false }
+// Balloon shows a notification through the notification centre; a click on it opens the settings window. macOS asks
+// the user once whether the app may notify. It returns false when the program is not an app bundle (a bare build),
+// which cannot notify.
+func (t *Tray) Balloon(title, text string) bool {
+ if t == nil {
+ return false
+ }
+ ct, cx := C.CString(title), C.CString(text)
+ defer C.free(unsafe.Pointer(ct))
+ defer C.free(unsafe.Pointer(cx))
+ return C.macNotify(ct, cx) != 0
+}
diff --git a/internal/winsys/macapp_darwin_test.go b/internal/winsys/macapp_darwin_test.go
new file mode 100644
index 0000000..a794834
--- /dev/null
+++ b/internal/winsys/macapp_darwin_test.go
@@ -0,0 +1,17 @@
+//go:build darwin && cgo
+
+package winsys
+
+import "testing"
+
+// A program that is not an app bundle (this test binary, a bare build) has no bundle identifier: it cannot notify, and
+// asking must say so rather than stop it with the notification centre's exception.
+func TestBalloonWithoutBundle(t *testing.T) {
+ if (&Tray{}).Balloon("MPRP 9.9.9 is available", "text") {
+ t.Error("a bare program reported a notification as shown")
+ }
+ var none *Tray
+ if none.Balloon("title", "text") {
+ t.Error("no menu bar icon, yet a notification was shown")
+ }
+}
diff --git a/internal/winsys/menubaricon.go b/internal/winsys/menubaricon.go
index 03a3809..6c0ba70 100644
--- a/internal/winsys/menubaricon.go
+++ b/internal/winsys/menubaricon.go
@@ -2,60 +2,17 @@ package winsys
import (
"bytes"
- "image"
- "image/color"
"image/png"
- "math"
+
+ "github.com/CptPakundo/MPRP/internal/logo"
)
-// menuBarIcon draws the icon for the macOS menu bar at n x n pixels (18 points on a Retina screen): the program's
-// rounded square with the play triangle cut out, in black on transparent, which macOS recolours for light and dark
-// menu bars. With dot, a filled circle in the top right corner, set apart by a transparent gap, says an update waits.
-// It lives outside macapp_darwin.go so it is built and tested on every system.
+// menuBarIcon draws the icon for the macOS menu bar at n x n pixels (18 points on a Retina screen): the program's logo
+// in one colour (logo.Template), black on transparent, which macOS recolours for light and dark menu bars. With dot,
+// a filled circle in the top right corner, set apart by a transparent gap, says an update waits. It lives outside
+// macapp_darwin.go so it is built and tested on every system.
func menuBarIcon(n int, dot bool) []byte {
- const ss, radius, inset = 8, 0.2, 0.06
- const dotX, dotY, dotR, gap = 0.8, 0.2, 0.2, 0.08
- tri := [3][2]float64{{0.39, 0.29}, {0.39, 0.71}, {0.73, 0.5}}
- inRect := func(x, y float64) bool {
- x, y = (x-inset)/(1-2*inset), (y-inset)/(1-2*inset)
- if x < 0 || y < 0 || x > 1 || y > 1 {
- return false
- }
- dx := math.Max(math.Max(radius-x, x-(1-radius)), 0)
- dy := math.Max(math.Max(radius-y, y-(1-radius)), 0)
- return dx*dx+dy*dy <= radius*radius
- }
- inTri := func(x, y float64) bool {
- s := func(a, b [2]float64) float64 { return (x-b[0])*(a[1]-b[1]) - (a[0]-b[0])*(y-b[1]) }
- d1, d2, d3 := s(tri[0], tri[1]), s(tri[1], tri[2]), s(tri[2], tri[0])
- return !((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))
- }
- inCircle := func(x, y, r float64) bool { return (x-dotX)*(x-dotX)+(y-dotY)*(y-dotY) <= r*r }
- filled := func(u, v float64) bool {
- switch {
- case dot && inCircle(u, v, dotR):
- return true
- case dot && inCircle(u, v, dotR+gap):
- return false
- }
- return inRect(u, v) && !inTri(u, v)
- }
- img := image.NewNRGBA(image.Rect(0, 0, n, n))
- for y := 0; y < n; y++ {
- for x := 0; x < n; x++ {
- cover := 0
- for sy := 0; sy < ss; sy++ {
- for sx := 0; sx < ss; sx++ {
- u, v := (float64(x)+(float64(sx)+0.5)/ss)/float64(n), (float64(y)+(float64(sy)+0.5)/ss)/float64(n)
- if filled(u, v) {
- cover++
- }
- }
- }
- img.SetNRGBA(x, y, color.NRGBA{0, 0, 0, uint8(math.Round(255 * float64(cover) / (ss * ss)))})
- }
- }
var out bytes.Buffer
- _ = png.Encode(&out, img)
+ _ = png.Encode(&out, logo.Template(n, n/18, dot))
return out.Bytes()
}
diff --git a/internal/winsys/menubaricon_test.go b/internal/winsys/menubaricon_test.go
index e386363..a49ee92 100644
--- a/internal/winsys/menubaricon_test.go
+++ b/internal/winsys/menubaricon_test.go
@@ -24,13 +24,13 @@ func TestMenuBarIconDot(t *testing.T) {
_, _, _, a := img.At(x, y).RGBA()
return a >> 8
}
- if a := alpha(dotted, 29, 7); a != 255 { // the dot's middle
+ if a := alpha(dotted, 28, 8); a != 255 { // the dot's middle
t.Errorf("dot alpha %d", a)
}
- if a := alpha(dotted, 22, 13); a != 0 { // in the gap (part of the square in the plain icon)
+ if a := alpha(dotted, 24, 13); a != 0 { // in the gap (part of the square in the plain icon)
t.Errorf("gap alpha %d", a)
}
- if a := alpha(plain, 22, 13); a != 255 {
+ if a := alpha(plain, 24, 13); a != 255 {
t.Errorf("plain icon at the gap: alpha %d", a)
}
if alpha(plain, 6, 30) != alpha(dotted, 6, 30) { // far from the dot
diff --git a/internal/winsys/mpvconf.go b/internal/winsys/mpvconf.go
index f9b48cb..f9f9c76 100644
--- a/internal/winsys/mpvconf.go
+++ b/internal/winsys/mpvconf.go
@@ -6,7 +6,7 @@ import (
"path/filepath"
"strings"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
const mpvIPCKey = "input-ipc-server"
@@ -43,7 +43,7 @@ func addMpvConfLine(text, key, value string) string {
if strings.Contains(text, "\r\n") || (text == "" && IsWindows) {
eol = "\r\n"
}
- return bom + "# added by MPCvibedRPC, so it can see what mpv plays" + eol + key + "=" + value + eol + text
+ return bom + "# added by MPRP, so it can see what mpv plays" + eol + key + "=" + value + eol + text
}
// mpvConfPaths lists where mpv reads its settings, most specific first: portable_config next to a known mpv.exe,
diff --git a/internal/winsys/mpvconf_unix_test.go b/internal/winsys/mpvconf_unix_test.go
index a995831..98bb15b 100644
--- a/internal/winsys/mpvconf_unix_test.go
+++ b/internal/winsys/mpvconf_unix_test.go
@@ -7,7 +7,7 @@ import (
"path/filepath"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
// mpv's macOS and Linux layout: ~/.config/mpv (or $XDG_CONFIG_HOME/mpv), and the socket written as a full path.
diff --git a/internal/winsys/mpcsetup.go b/internal/winsys/playersetup.go
similarity index 93%
rename from internal/winsys/mpcsetup.go
rename to internal/winsys/playersetup.go
index 4a3da36..bcb67d6 100644
--- a/internal/winsys/mpcsetup.go
+++ b/internal/winsys/playersetup.go
@@ -10,11 +10,11 @@ import (
"sync"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/proc"
+ "github.com/CptPakundo/MPRP/internal/proc"
)
-// WebResult is the answer of EnableMpcWebInterface.
-type WebResult struct {
+// SetupResult is the answer of SetUpPlayers.
+type SetupResult struct {
OK bool `json:"ok"`
NeedsClose bool `json:"needsClose,omitempty"`
Message string `json:"message"`
@@ -140,31 +140,31 @@ var (
// setupLock lets one player setup run at a time (Windows and the other systems alike).
var setupLock sync.Mutex
-// EnableMpcWebInterface switches the web interface of MPC-HC and MPC-BE on (whichever is installed), sets mpv up to
+// SetUpPlayers switches the web interface of MPC-HC and MPC-BE on (whichever is installed), sets mpv up to
// accept our connection (mpvPipe; empty skips mpv) and switches VLC's web interface on (vlcPort, vlcPassword: used
// unless VLC already has its own). MPC-HC, MPC-BE and VLC rewrite their settings when they exit, so they have to be
-// closed while those change (VLC only when something changes); without closeMpc the caller is told (needsClose) and
+// closed while those change (VLC only when something changes); without mayClose the caller is told (needsClose) and
// can ask the user. mpv is never closed: it reads mpv.conf when it next starts. MPC-QT needs nothing. On macOS and
-// Linux, enableUnix does the same for the players there (iinaPipe: IINA's connection on macOS).
+// Linux, setUpUnix does the same for the players there (iinaPipe: IINA's connection on macOS).
//
// The steps run in this order: look for the running players, close them, set up MPC-HC and MPC-BE, reopen them, set
// up mpv, set up VLC (and reopen it), and word the result.
-func EnableMpcWebInterface(port int, closeMpc bool, mpvPipe string, vlcPort int, vlcPassword string, iinaPipe string) WebResult {
+func SetUpPlayers(port int, mayClose bool, mpvPipe string, vlcPort int, vlcPassword string, iinaPipe string) SetupResult {
// A double click sends two requests: a second setup would close and reopen the players again and write the same
// files at the same time.
if !setupLock.TryLock() {
- return WebResult{Message: "Player setup is already running. Wait a moment and look at the result."}
+ return SetupResult{Message: "Player setup is already running. Wait a moment and look at the result."}
}
defer setupLock.Unlock()
if !IsWindows {
- return enableUnix(port, closeMpc, mpvPipe, vlcPort, vlcPassword, iinaPipe)
+ return setUpUnix(port, mayClose, mpvPipe, vlcPort, vlcPassword, iinaPipe)
}
exes := runningPlayers()
others := runningExes(otherPlayers)
vlcAt := findVlc(others)
closeVlc := vlcAt.file != "" && !vlcReady(vlcAt.text) && len(vlcAt.exes) > 0
- if (len(exes) > 0 || closeVlc) && !closeMpc {
- return WebResult{NeedsClose: true, Message: openPlayersMessage(len(exes) > 0, closeVlc)}
+ if (len(exes) > 0 || closeVlc) && !mayClose {
+ return SetupResult{NeedsClose: true, Message: openPlayersMessage(len(exes) > 0, closeVlc)}
}
if !closeVlc {
vlcAt.exes = nil // left alone
@@ -187,7 +187,7 @@ func EnableMpcWebInterface(port int, closeMpc bool, mpvPipe string, vlcPort int,
}
message, ok := describeSetup(port, mpc, len(exes) > 0, mpv, vlc, qtFound)
- return WebResult{OK: ok, Message: message, Edited: edited, MpvPipe: mpv.Using, VlcPort: vlc.Port, VlcPassword: vlc.Password}
+ return SetupResult{OK: ok, Message: message, Edited: edited, MpvPipe: mpv.Using, VlcPort: vlc.Port, VlcPassword: vlc.Password}
}
// vlcSpot is the VLC found on this PC before the setup: its running programs, the vlcrc it reads and that file's text.
diff --git a/internal/winsys/run.go b/internal/winsys/run.go
index 246b477..72e7ff2 100644
--- a/internal/winsys/run.go
+++ b/internal/winsys/run.go
@@ -8,7 +8,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/proc"
+ "github.com/CptPakundo/MPRP/internal/proc"
)
type result struct {
diff --git a/internal/winsys/setup_unix.go b/internal/winsys/setup_unix.go
index 24f9be8..bb4f551 100644
--- a/internal/winsys/setup_unix.go
+++ b/internal/winsys/setup_unix.go
@@ -9,7 +9,7 @@ import (
"strings"
"time"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
// "Set up the player connection" on macOS and Linux. There is no MPC-HC or MPC-BE there. mpv gets input-ipc-server
@@ -20,7 +20,7 @@ import (
// iinaDomain is IINA's settings domain (its bundle identifier).
const iinaDomain = "com.colliderli.iina"
-func enableUnix(port int, closeMpc bool, mpvPipe string, vlcPort int, vlcPassword string, iinaPipe string) WebResult {
+func setUpUnix(port int, mayClose bool, mpvPipe string, vlcPort int, vlcPassword string, iinaPipe string) SetupResult {
mac := runtime.GOOS == "darwin"
home, _ := os.UserHomeDir()
@@ -37,8 +37,8 @@ func enableUnix(port int, closeMpc bool, mpvPipe string, vlcPort int, vlcPasswor
}
}
closeVlc := vlcFile != "" && !vlcReady(vlcText) && len(vlcExes) > 0
- if closeVlc && !closeMpc {
- return WebResult{NeedsClose: true, Message: "VLC is open and has to be closed for a moment (it will reopen)."}
+ if closeVlc && !mayClose {
+ return SetupResult{NeedsClose: true, Message: "VLC is open and has to be closed for a moment (it will reopen)."}
}
if closeVlc {
run("osascript", "-e", `tell application id "org.videolan.vlc" to quit`)
@@ -104,7 +104,7 @@ func enableUnix(port int, closeMpc bool, mpvPipe string, vlcPort int, vlcPasswor
parts = append(parts, "No player that needs setting up was found (mpv, IINA or VLC).")
ok = false
}
- return WebResult{OK: ok, Message: strings.Join(parts, " "), Edited: edited, MpvPipe: mpv.Using,
+ return SetupResult{OK: ok, Message: strings.Join(parts, " "), Edited: edited, MpvPipe: mpv.Using,
VlcPort: vlc.Port, VlcPassword: vlc.Password, IinaPipe: iina.Using}
}
diff --git a/internal/winsys/single_windows.go b/internal/winsys/single_windows.go
index 9102c0a..e0f9fe4 100644
--- a/internal/winsys/single_windows.go
+++ b/internal/winsys/single_windows.go
@@ -7,33 +7,53 @@ import (
"unsafe"
)
-// instanceMutex is the mutex this copy holds (0: none).
-var instanceMutex syscall.Handle
+// instanceMutexes are the mutexes this copy holds (none: nil).
+var instanceMutexes []syscall.Handle
-// AcquireSingleInstance takes a process-wide named mutex. It returns false when another copy already holds it. (The
-// data folder dir is used by the other systems, which lock a file in it.) The handle stays open: Windows releases the
-// mutex when the process ends, and that is what keeps a second copy out until then (or until ReleaseSingleInstance).
+// instanceNames are the names of the mutexes that keep a second copy out. The default install uses the program's name;
+// a copy with a data folder of its own (MPRP_HOME) gets its own, like its autostart value, so it can run
+// next to an installed copy. The name under the program's former name is held too: a copy of the former version that
+// updates itself to this one releases that mutex as it hands over, and this copy waits for it as it always did.
+func instanceNames() []string {
+ return []string{`Local\` + runName() + `-single-instance`, `Local\` + formerRunName() + `-single-instance`}
+}
+
+// AcquireSingleInstance takes the process-wide named mutexes. It returns false when another copy already holds one of
+// them. (The data folder dir is used by the other systems, which lock a file in it.) The handles stay open: Windows
+// releases the mutexes when the process ends, and that is what keeps a second copy out until then (or until
+// ReleaseSingleInstance).
func AcquireSingleInstance(dir string) bool {
- // The default install keeps the name it always had; a copy with a data folder of its own (MPCRPC_HOME) gets its
- // own, like its autostart value, so it can run next to an installed copy.
- name, _ := syscall.UTF16PtrFromString(`Local\` + runName() + `-single-instance`)
- h, _, err := kernel32.NewProc("CreateMutexW").Call(0, 0, uintptr(unsafe.Pointer(name)))
- if h == 0 {
- return true // cannot tell: do not lock ourselves out
+ if instanceMutexes != nil {
+ return true
+ }
+ var held []syscall.Handle
+ for _, n := range instanceNames() {
+ name, _ := syscall.UTF16PtrFromString(n)
+ h, _, err := kernel32.NewProc("CreateMutexW").Call(0, 0, uintptr(unsafe.Pointer(name)))
+ if h == 0 {
+ continue // cannot tell: do not lock ourselves out
+ }
+ if errno, ok := err.(syscall.Errno); ok && errno == 183 { // ERROR_ALREADY_EXISTS
+ syscall.CloseHandle(syscall.Handle(h))
+ for _, o := range held {
+ syscall.CloseHandle(o)
+ }
+ return false
+ }
+ held = append(held, syscall.Handle(h))
}
- if errno, ok := err.(syscall.Errno); ok && errno == 183 { // ERROR_ALREADY_EXISTS
- syscall.CloseHandle(syscall.Handle(h))
- return false
+ instanceMutexes = held
+ if instanceMutexes == nil {
+ instanceMutexes = []syscall.Handle{}
}
- instanceMutex = syscall.Handle(h)
return true
}
// ReleaseSingleInstance lets another copy start while this one still runs: after an update the old copy stays for a
-// moment to see that the new one comes up, and the new one waits for the mutex.
+// moment to see that the new one comes up, and the new one waits for the mutexes.
func ReleaseSingleInstance() {
- if instanceMutex != 0 {
- syscall.CloseHandle(instanceMutex)
- instanceMutex = 0
+ for _, h := range instanceMutexes {
+ syscall.CloseHandle(h)
}
+ instanceMutexes = nil
}
diff --git a/internal/winsys/taskbar_other.go b/internal/winsys/taskbar_other.go
index 6103577..251ef04 100644
--- a/internal/winsys/taskbar_other.go
+++ b/internal/winsys/taskbar_other.go
@@ -4,4 +4,7 @@ package winsys
// NameWindow does nothing here: only Windows takes the settings window's taskbar button for the browser's. (macOS
// shows the settings in a window of the program's own.)
-func NameWindow(profileDir string) bool { return false }
+func NameWindow(profileDir string, log func(level, msg string)) bool { return false }
+
+// StopWindowIcon does nothing here (see NameWindow).
+func StopWindowIcon() {}
diff --git a/internal/winsys/taskbar_windows.go b/internal/winsys/taskbar_windows.go
index 6f9e2c9..0357daf 100644
--- a/internal/winsys/taskbar_windows.go
+++ b/internal/winsys/taskbar_windows.go
@@ -1,13 +1,18 @@
package winsys
import (
+ "encoding/binary"
+ "fmt"
"os"
"runtime"
"strings"
"sync"
+ "sync/atomic"
"syscall"
"time"
"unsafe"
+
+ "github.com/CptPakundo/MPRP/internal/assets"
)
// The settings window is a browser window, so Windows takes its taskbar button for the browser's: the button's menu
@@ -41,8 +46,31 @@ const (
storeSetValue = 6
storeCommit = 7
- nameWindowFor = 15 * time.Second // how long a window that was just opened is looked for
- nameWindowEvery = 250 * time.Millisecond // and how often
+ // After a window was asked for, all windows are looked at often in its first seconds (so its button has the
+ // program's icon from the start, should an event be missed) and less often after that; a window that has not
+ // appeared after nameWindowWarn is reported (and still taken on when it does appear).
+ nameWindowFast = 3 * time.Second
+ nameWindowFastEvery = 30 * time.Millisecond
+ nameWindowEvery = 250 * time.Millisecond
+ nameWindowWarn = 30 * time.Second
+
+ // for a while after a window was taken on, all windows are looked at now and then too, in case the browser
+ // changed its icon and an event was missed
+ keepSettle = 10 * time.Second
+ keepSettleEvery = 250 * time.Millisecond
+
+ // The keeping listens to the shell hook (every program's taskbar windows) only while it may have something to do:
+ // while a window is taken on, for keepAskFor after a window was asked for, and for keepLinger after the last
+ // window taken on went (a browser that replaces its window, or restarts itself, shows the new one within that).
+ keepAskFor = 2 * time.Minute
+ keepLinger = 30 * time.Second
+
+ // a window whose icon had to be set again more than keepFixesMax times within keepFixesPer is left alone: its
+ // browser puts its own back each time (or answers for it), and correcting it would never end
+ keepFixesMax = 20
+ keepFixesPer = 10 * time.Second
+
+ keepForgetAll = 4096 // more windows remembered than this: forget them all (they are looked up again)
)
// propertyKey is Windows' PROPERTYKEY, propVariant its PROPVARIANT for a string, propertyStore an IPropertyStore.
@@ -71,32 +99,641 @@ func windowIdentity(exe, home string) (id, name, command, icon string) {
return runNameFor(home), runNameBase, command, exe + ",0"
}
-// NameWindow gives the settings window that was just opened with profileDir the program's own taskbar identity. The
-// window takes a moment to appear, so it is looked for until it is there (at most nameWindowFor); the caller runs
-// this on a goroutine of its own. It reports whether a window was named.
-func NameWindow(profileDir string) bool {
+// NameWindow is called when a settings window was just opened with profileDir: its taskbar button gets the program's
+// own identity and icon. It starts the keeping (keepWindowIcons) the first time and tells it a window is coming; the
+// keeping then gives every taskbar window of a browser process that uses profileDir the identity and icon the moment
+// it appears, whenever that is and whichever process it is in, and keeps the program's icon on it (the browser puts
+// its own back now and then), until StopWindowIcon. log gets a line when the window first has the program's icon,
+// when something fails, and when the keeping ends. It reports whether the keeping runs.
+func NameWindow(profileDir string, log func(level, msg string)) bool {
exe, err := os.Executable()
if err != nil || profileDir == "" {
return false
}
- id, name, command, icon := windowIdentity(exe, os.Getenv("MPCRPC_HOME"))
- for deadline := time.Now().Add(nameWindowFor); ; time.Sleep(nameWindowEvery) {
- if w, ok := findWindow(profileDir); ok {
- // the ID first: the other three belong to it
- named := setWindowStrings(w.Handle, []windowString{
- {propAppID, id}, {propRelaunchCommand, command}, {propRelaunchDisplayName, name}, {propRelaunchIcon, icon},
- })
- // The browser gives its window the page's icon in a small size, which the taskbar enlarges. It does so
- // when the page has loaded, which may be after the window was found: the program's icon is set now and
- // twice more.
- for _, wait := range []time.Duration{0, time.Second, 3 * time.Second} {
- time.Sleep(wait)
- setWindowIcons(w.Handle, exe)
+ if log == nil {
+ log = func(string, string) {}
+ }
+ loadWindowIcons(exe) // read now, so they are set the moment the window is there
+ k := ensureKeeper(profileDir, exe, log)
+ if k == nil {
+ return false
+ }
+ r, _, _ := pPostThreadMessage.Call(k.tid, wmWindowAsked, 0, 0)
+ return r != 0
+}
+
+// nameWindow gives one window the program's identity and icons; false when the identity was not taken.
+func nameWindow(hwnd uintptr, strs []windowString) bool {
+ applyWindowIcons(hwnd)
+ named := setWindowStrings(hwnd, strs) // the ID first: the other three belong to it
+ applyWindowIcons(hwnd) // the new ID can give the window a button of its own, drawn with its icon now
+ return named
+}
+
+// taskbarWindow says whether a window gets a taskbar button (Windows' own rule): a visible top-level window that is
+// not a tool window and has no owner, unless it asks for a button. The browser's bubbles and menus have none.
+func taskbarWindow(w topWindow) bool {
+ return w.Visible && !w.Child && (w.AppWindow || (!w.Owned && !w.Tool))
+}
+
+// processUsesProfile says whether the process pid was started with the browser profile profileDir.
+func processUsesProfile(pid uint32, profileDir string) bool {
+ h, err := syscall.OpenProcess(processQueryLimitedInformation, false, pid)
+ if err != nil {
+ return false
+ }
+ defer syscall.CloseHandle(h)
+ return usesProfile(commandLine(h), profileDir)
+}
+
+var (
+ pSetWinEventHook = user32.NewProc("SetWinEventHook")
+ pUnhookWinEvent = user32.NewProc("UnhookWinEvent")
+ pPeekMessage = user32.NewProc("PeekMessageW")
+ pPostThreadMessage = user32.NewProc("PostThreadMessageW")
+ pGetCurrentThread = kernel32.NewProc("GetCurrentThreadId")
+ pMsgWaitForObjects = user32.NewProc("MsgWaitForMultipleObjects")
+
+ pRegisterShellHook = user32.NewProc("RegisterShellHookWindow")
+ pDeregisterShellHook = user32.NewProc("DeregisterShellHookWindow")
+ pSendMessageTimeout = user32.NewProc("SendMessageTimeoutW")
+
+ // made once: callbacks are never freed (onWinEvent and the shell window's procedure find the keeping they are for
+ // in iconKeeperNow)
+ winEventCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(onWinEvent) })
+ // the message the shell hook's notifications come as
+ shellHookMessage = sync.OnceValue(func() uintptr {
+ name, _ := syscall.UTF16PtrFromString("SHELLHOOK")
+ m, _, _ := pRegisterWindowMessage.Call(uintptr(unsafe.Pointer(name)))
+ return m
+ })
+ // the class of the hidden window that gets them (nil: it could not be registered)
+ shellWindowClass = sync.OnceValue(func() *uint16 {
+ name, _ := syscall.UTF16PtrFromString(runNameBase + "-icon-keeper")
+ inst, _, _ := pGetModuleHandle.Call(0)
+ wc := wndClassEx{lpfnWndProc: syscall.NewCallback(shellWindowProc), hInstance: inst, lpszClassName: name}
+ wc.cbSize = uint32(unsafe.Sizeof(wc))
+ if r, _, _ := pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))); r == 0 {
+ return nil
+ }
+ return name
+ })
+
+ keeperMu sync.Mutex
+ ensureMu sync.Mutex // one ensureKeeper at a time
+ iconKeeperNow *iconKeeper // the keeping now (nil: none)
+ iconGen atomic.Int64 // counts StopWindowIcon: a keeping that starts after one is not taken
+)
+
+// WinEvents (SetWinEventHook) and what they are for.
+const (
+ eventObjectDestroy = 0x8001
+ eventObjectShow = 0x8002
+ eventObjectNameChange = 0x800C
+ objIDWindow = 0 // idObject of an event about the window itself
+ childIDSelf = 0 // and its idChild
+ winEventOutOfContext = 0x0000 // the events come to this process's hook thread, through its message loop
+ winEventSkipOwn = 0x0002 // and none of this process's own
+ pmNoRemove = 0x0000
+ pmRemove = 0x0001
+ wmQuit = 0x0012
+ wmWindowAsked = 0x8001 // WM_APP+1, to the keeping's thread: NameWindow was called
+
+ // shell hook notifications (RegisterShellHookWindow), in the low 15 bits of wParam
+ hshellWindowCreated = 1
+ hshellWindowDestroyed = 2
+ hshellRedraw = 6 // a taskbar button is drawn again: its window's title or icon changed
+ wmGetIcon = 0x007F
+ smtoAbortIfHung = 0x0002
+ wsPopup = 0x80000000
+
+ qsAllInput = 0x04FF
+ waitTimeout = 0x102
+ waitFailed = 0xFFFFFFFF
+ infinite = 0xFFFFFFFF
+)
+
+// keepAction is what an event means for the keeping.
+type keepAction int
+
+const (
+ keepNothing keepAction = iota
+ keepCheck // a window may be new, or may have another icon now: take it on, or check its icon
+ keepForget // a window is gone (its handle may later be given to another)
+)
+
+// shellEvent says what a shell hook notification means: a window that got a taskbar button, or whose button was
+// redrawn (as it is when the browser gives the window an icon of its own, which no WinEvent tells), is checked; a
+// destroyed one is forgotten. It is about any window of any program: the keeping checks whose it is.
+func shellEvent(code uintptr) keepAction {
+ switch code & 0x7fff {
+ case hshellWindowCreated, hshellRedraw:
+ return keepCheck
+ case hshellWindowDestroyed:
+ return keepForget
+ }
+ return keepNothing
+}
+
+// iconEvent says what a WinEvent of a browser process with a window taken on means: a window that was shown, or whose
+// title changed (after which the browser sets its own icon again), is checked; a destroyed one is forgotten. Only
+// events about a window itself count, not about its contents.
+func iconEvent(event uint32, idObject, idChild int32) keepAction {
+ if idObject != objIDWindow || idChild != childIDSelf {
+ return keepNothing
+ }
+ switch event {
+ case eventObjectShow, eventObjectNameChange:
+ return keepCheck
+ case eventObjectDestroy:
+ return keepForget
+ }
+ return keepNothing
+}
+
+// keepWait says how long the keeping may wait for an event before it looks at all windows again: often in the first
+// seconds after a window was asked for (at asked; zero: none), less often until it appears or nameWindowWarn has
+// passed, and for a while after a window was taken on (until settleEnd); otherwise until an event comes (negative).
+// overdue: the window asked for has not appeared within nameWindowWarn, and that was not reported yet (warned).
+func keepWait(now, asked, settleEnd time.Time, warned bool) (wait time.Duration, overdue bool) {
+ wait = -1
+ if !asked.IsZero() {
+ switch since := now.Sub(asked); {
+ case since >= nameWindowWarn:
+ if !warned {
+ return 0, true
}
- return named
+ case since < nameWindowFast:
+ wait = nameWindowFastEvery
+ default:
+ wait = nameWindowEvery
}
- if time.Now().After(deadline) {
- return false
+ }
+ if left := settleEnd.Sub(now); left > 0 {
+ if s := min(left, keepSettleEvery); wait < 0 || s < wait {
+ wait = s
+ }
+ }
+ return wait, false
+}
+
+// keepIdle says whether the keeping has nothing to listen for now (named windows taken on, a window asked for at
+// asked, the last window taken on gone at gone; zero: none), else how long until it may have (negative: not by
+// itself, a window is taken on).
+func keepIdle(now time.Time, named int, asked, gone time.Time) (idle bool, until time.Duration) {
+ if named > 0 {
+ return false, -1
+ }
+ var end time.Time
+ if !asked.IsZero() {
+ end = asked.Add(keepAskFor)
+ }
+ if !gone.IsZero() && gone.Add(keepLinger).After(end) {
+ end = gone.Add(keepLinger)
+ }
+ if left := end.Sub(now); left > 0 {
+ return false, left
+ }
+ return true, 0
+}
+
+// fixCount counts the times a window's icon had to be set again.
+type fixCount struct {
+ since time.Time
+ n int
+}
+
+// add counts one at now, and says whether there were more than keepFixesMax within keepFixesPer.
+func (c *fixCount) add(now time.Time) bool {
+ if now.Sub(c.since) > keepFixesPer {
+ c.since, c.n = now, 0
+ }
+ c.n++
+ return c.n > keepFixesMax
+}
+
+// iconState is what checkWindowIcons found.
+type iconState int
+
+const (
+ iconsUnknown iconState = iota // they could not be read (or the program's are not loaded)
+ iconsOurs // the window has the program's icons
+ iconsSet // it had others: the program's were set again
+)
+
+// iconKeeper gives the program's identity and icon to every taskbar window of a browser process that uses the
+// window profile, and keeps the icon on it. Its functions are Windows' (tests give fakes): visible and inspect read a
+// window, ours tells whether a process uses the profile, name gives a window the identity and icons (false: the
+// identity was refused), check sets the icons again where the window has others, iconsLoaded tells whether the
+// program's icons could be read, hook and unhook follow one process's WinEvents, listen and unlisten register and
+// deregister the shell hook, end stops the hook thread (once, through stop). armed and done may be read by others
+// (done is closed when the thread has ended); everything else belongs to the hook thread.
+type iconKeeper struct {
+ profile string
+ tid uintptr
+ self uint32
+ hidden uintptr // the hidden window that gets the shell hook's notifications
+ visible func(hwnd uintptr) bool
+ inspect func(hwnd uintptr) topWindow
+ ours func(pid uint32) bool
+ name func(hwnd uintptr) bool
+ check func(hwnd uintptr) iconState
+ iconsLoaded func() bool
+ hook func(pid uint32) []uintptr
+ unhook func(hooks []uintptr)
+ listen func() bool
+ unlisten func()
+ log func(level, msg string)
+ end func()
+ once sync.Once
+ armed atomic.Bool // the shell hook is registered
+ done chan struct{}
+
+ verdict map[uintptr]bool // taskbar windows looked up: whether their process uses the profile
+ named map[uintptr]uint32 // the windows given the identity, and their process
+ hooks map[uint32][]uintptr // the WinEvent hooks of the processes with a window taken on
+ asked time.Time // when a window was asked for that has not appeared yet (zero: none)
+ late bool // that it has not appeared within nameWindowWarn was reported
+ gone time.Time // when the last window taken on went (zero: one is there, or none was)
+ settleEnd time.Time // until when all windows are looked at now and then
+ fixes map[uintptr]*fixCount
+ given map[uintptr]bool // windows whose icon is no longer corrected (too many times)
+ confirmed bool // a window was seen with the program's icon (reported once)
+ warned map[string]bool // failures reported (once each)
+}
+
+// event handles a WinEvent.
+func (k *iconKeeper) event(event uint32, hwnd uintptr, idObject, idChild int32) {
+ k.act(iconEvent(event, idObject, idChild), hwnd)
+}
+
+// shell handles a shell hook notification.
+func (k *iconKeeper) shell(code, hwnd uintptr) { k.act(shellEvent(code), hwnd) }
+
+func (k *iconKeeper) act(a keepAction, hwnd uintptr) {
+ switch a {
+ case keepCheck:
+ if ours, seen := k.verdict[hwnd]; seen && !ours {
+ return // another program's window: the cheap way out, as most events are about those
+ }
+ if !k.visible(hwnd) {
+ return
+ }
+ k.consider(k.inspect(hwnd))
+ case keepForget:
+ k.forget(hwnd)
+ }
+}
+
+// consider takes the window w on (a taskbar window of a process that uses the profile, not named yet) or checks its
+// icon (one named before). Other programs' windows, and the browser's bubbles, menus and hidden windows, are left
+// alone; whose a window is is looked up once.
+func (k *iconKeeper) consider(w topWindow) {
+ if w.Pid == 0 || w.Pid == k.self || !taskbarWindow(w) {
+ return
+ }
+ if k.verdict == nil || len(k.verdict) > keepForgetAll {
+ k.verdict = map[uintptr]bool{}
+ }
+ ours, seen := k.verdict[w.Handle]
+ if !seen {
+ ours = k.ours(w.Pid)
+ k.verdict[w.Handle] = ours
+ }
+ if !ours {
+ return
+ }
+ if _, done := k.named[w.Handle]; done {
+ k.keepIcon(w.Handle)
+ return
+ }
+ k.adopt(w)
+}
+
+// keepIcon checks the icons of a window taken on, and stops correcting them when that happened too often.
+func (k *iconKeeper) keepIcon(hwnd uintptr) {
+ if k.given[hwnd] {
+ return
+ }
+ switch k.check(hwnd) {
+ case iconsOurs:
+ if !k.confirmed {
+ k.confirmed = true
+ k.log("INFO", "The settings window got the program's taskbar icon.")
+ }
+ case iconsSet:
+ if k.fixes == nil {
+ k.fixes = map[uintptr]*fixCount{}
+ }
+ c := k.fixes[hwnd]
+ if c == nil {
+ c = &fixCount{}
+ k.fixes[hwnd] = c
+ }
+ if c.add(time.Now()) {
+ if k.given == nil {
+ k.given = map[uintptr]bool{}
+ }
+ k.given[hwnd] = true
+ k.warn("loop", fmt.Sprintf("The settings window keeps the browser's icon: the browser put it back more than %d times in %d s.",
+ keepFixesMax, int(keepFixesPer/time.Second)))
+ }
+ }
+}
+
+// adopt gives the window w the identity and icons, and follows its process's events.
+func (k *iconKeeper) adopt(w topWindow) {
+ if k.named == nil {
+ k.named = map[uintptr]uint32{}
+ }
+ k.named[w.Handle] = w.Pid
+ if !k.iconsLoaded() {
+ k.warn("icons", "The settings window keeps the browser's icon: the program's icon could not be loaded.")
+ }
+ if !k.name(w.Handle) && k.visible(w.Handle) { // (a window that went meanwhile refuses it too)
+ k.warn("store", "The settings window's taskbar button could not be given the program's name (its property store refused it).")
+ }
+ if k.hooks == nil {
+ k.hooks = map[uint32][]uintptr{}
+ }
+ if _, ok := k.hooks[w.Pid]; !ok {
+ k.hooks[w.Pid] = k.hook(w.Pid)
+ }
+ k.asked, k.late, k.gone = time.Time{}, false, time.Time{}
+ k.settleEnd = time.Now().Add(keepSettle)
+}
+
+// forget drops a window that is gone, and its process's hooks with its last window taken on.
+func (k *iconKeeper) forget(hwnd uintptr) {
+ delete(k.verdict, hwnd)
+ pid, was := k.named[hwnd]
+ if !was {
+ return
+ }
+ delete(k.named, hwnd)
+ delete(k.fixes, hwnd)
+ delete(k.given, hwnd)
+ if len(k.named) == 0 {
+ k.gone = time.Now()
+ }
+ for _, p := range k.named {
+ if p == pid {
+ return
+ }
+ }
+ if hooks, ok := k.hooks[pid]; ok {
+ k.unhook(hooks)
+ delete(k.hooks, pid)
+ }
+}
+
+// sweep looks at every window in hwnds (all top-level windows).
+func (k *iconKeeper) sweep(hwnds []uintptr) {
+ for _, h := range hwnds {
+ k.act(keepCheck, h)
+ }
+}
+
+// windowAsked notes that a window was asked for (NameWindow), and listens for it.
+func (k *iconKeeper) windowAsked(now time.Time) {
+ k.asked, k.late = now, false
+ k.setListening(true)
+}
+
+// overdue reports the window asked for that has not appeared (it is still taken on if it does, for a while).
+func (k *iconKeeper) overdue() {
+ k.late = true
+ k.log("WARN", "The settings window was not found within 30 s; it gets the program's taskbar icon if it appears in the next minutes.")
+}
+
+// setListening registers the shell hook, or deregisters it and drops what the keeping knew (with the hook off, the
+// handles of windows that go are not heard of, and may be given to others).
+func (k *iconKeeper) setListening(on bool) {
+ switch {
+ case on && !k.armed.Load():
+ if k.listen() {
+ k.armed.Store(true)
+ } else {
+ k.warn("hook", "The settings window's icon is only set while it opens: the shell hook could not be set up.")
+ }
+ case !on && k.armed.Load():
+ k.unlisten()
+ k.armed.Store(false)
+ k.unhookAll()
+ k.verdict, k.named, k.fixes, k.given = nil, nil, nil, nil
+ k.asked, k.late, k.gone, k.settleEnd = time.Time{}, false, time.Time{}, time.Time{}
+ }
+}
+
+// warn logs a failure once.
+func (k *iconKeeper) warn(kind, msg string) {
+ if k.warned == nil {
+ k.warned = map[string]bool{}
+ }
+ if !k.warned[kind] {
+ k.warned[kind] = true
+ k.log("WARN", msg)
+ }
+}
+
+// unhookAll ends every process's hooks.
+func (k *iconKeeper) unhookAll() {
+ for pid, hooks := range k.hooks {
+ k.unhook(hooks)
+ delete(k.hooks, pid)
+ }
+}
+
+func (k *iconKeeper) stop() { k.once.Do(k.end) }
+
+// startKeeper makes k the keeping now, ending the one before; false (and nothing changed) when StopWindowIcon was
+// called since gen was read.
+func startKeeper(k *iconKeeper, gen int64) bool {
+ keeperMu.Lock()
+ if iconGen.Load() != gen {
+ keeperMu.Unlock()
+ return false
+ }
+ old := iconKeeperNow
+ iconKeeperNow = k
+ keeperMu.Unlock()
+ if old != nil {
+ old.stop()
+ }
+ return true
+}
+
+// endKeeper forgets k, if it is still the keeping now.
+func endKeeper(k *iconKeeper) {
+ keeperMu.Lock()
+ if iconKeeperNow == k {
+ iconKeeperNow = nil
+ }
+ keeperMu.Unlock()
+}
+
+// StopWindowIcon ends the keeping of the settings window's identity and icon (the program quits).
+func StopWindowIcon() {
+ keeperMu.Lock()
+ iconGen.Add(1)
+ old := iconKeeperNow
+ iconKeeperNow = nil
+ keeperMu.Unlock()
+ if old != nil {
+ old.stop()
+ }
+}
+
+// currentKeeper is the keeping now (nil: none).
+func currentKeeper() *iconKeeper {
+ keeperMu.Lock()
+ defer keeperMu.Unlock()
+ return iconKeeperNow
+}
+
+// ensureKeeper returns the keeping for profileDir, started now if none runs; nil when it could not start.
+func ensureKeeper(profileDir, exe string, log func(level, msg string)) *iconKeeper {
+ ensureMu.Lock()
+ defer ensureMu.Unlock()
+ if k := currentKeeper(); k != nil && k.profile == profileDir {
+ return k
+ }
+ ready := make(chan *iconKeeper, 1)
+ go keepWindowIcons(profileDir, exe, log, iconGen.Load(), ready)
+ return <-ready
+}
+
+// onWinEvent is the WinEvent callback (WINEVENTPROC); it runs on the hook thread.
+func onWinEvent(_, event, hwnd, idObject, idChild, _, _ uintptr) uintptr {
+ if k := currentKeeper(); k != nil {
+ k.event(uint32(event), hwnd, int32(idObject), int32(idChild))
+ }
+ return 0
+}
+
+// shellWindowProc is the hidden window's procedure: it passes the shell hook's notifications on.
+func shellWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintptr {
+ if m := shellHookMessage(); m != 0 && uintptr(message) == m {
+ if k := currentKeeper(); k != nil {
+ k.shell(wParam, lParam)
+ }
+ return 0
+ }
+ r, _, _ := pDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam)
+ return r
+}
+
+// hookProcess follows the WinEvents of the process pid (out of context: nothing goes into the browser).
+func hookProcess(pid uint32) []uintptr {
+ var hooks []uintptr
+ for _, r := range [][2]uintptr{{eventObjectDestroy, eventObjectShow}, {eventObjectNameChange, eventObjectNameChange}} {
+ if hk, _, _ := pSetWinEventHook.Call(r[0], r[1], 0, winEventCallback(), uintptr(pid), 0, winEventOutOfContext|winEventSkipOwn); hk != 0 {
+ hooks = append(hooks, hk)
+ }
+ }
+ return hooks
+}
+
+func unhookProcess(hooks []uintptr) {
+ for _, hk := range hooks {
+ pUnhookWinEvent.Call(hk)
+ }
+}
+
+// keepWindowIcons is the keeping's thread, for the program's life from the first settings window on. It listens to
+// the shell hook (a hidden window of its own: every program's taskbar windows as they appear, are redrawn and go) and
+// to the WinEvents of the browser processes it took a window of, both through a message loop on this goroutine's own
+// thread, and looks at all windows now and then while a window is awaited or was just taken on (keepWait). It sends
+// itself to ready once it runs (nil: it does not), and ends with StopWindowIcon.
+func keepWindowIcons(profileDir, exe string, log func(level, msg string), gen int64, ready chan<- *iconKeeper) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ var m msg
+ pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmNoRemove) // makes the thread's message queue
+ tid, _, _ := pGetCurrentThread.Call()
+ id, name, command, icon := windowIdentity(exe, os.Getenv("MPRP_HOME"))
+ strs := []windowString{{propAppID, id}, {propRelaunchCommand, command}, {propRelaunchDisplayName, name}, {propRelaunchIcon, icon}}
+ k := &iconKeeper{profile: profileDir, tid: tid, self: uint32(os.Getpid()), log: log,
+ visible: func(h uintptr) bool { v, _, _ := pIsWindowVisible.Call(h); return v != 0 },
+ inspect: describeWindow,
+ ours: func(pid uint32) bool { return processUsesProfile(pid, profileDir) },
+ name: func(h uintptr) bool {
+ loadWindowIcons(exe) // icons that could not be had before are tried again
+ return nameWindow(h, strs)
+ },
+ check: checkWindowIcons,
+ iconsLoaded: haveWindowIcons,
+ hook: hookProcess,
+ unhook: unhookProcess,
+ end: func() { pPostThreadMessage.Call(tid, wmQuit, 0, 0) },
+ done: make(chan struct{})}
+ defer close(k.done)
+ if cls := shellWindowClass(); cls != nil && shellHookMessage() != 0 {
+ inst, _, _ := pGetModuleHandle.Call(0)
+ k.hidden, _, _ = pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(cls)), 0, wsPopup, 0, 0, 0, 0, 0, 0, inst, 0)
+ }
+ k.listen = func() bool {
+ r, _, _ := pRegisterShellHook.Call(k.hidden)
+ return k.hidden != 0 && r != 0
+ }
+ k.unlisten = func() { pDeregisterShellHook.Call(k.hidden) }
+ if k.hidden != 0 {
+ defer pDestroyWindow.Call(k.hidden)
+ }
+ if !startKeeper(k, gen) {
+ ready <- nil
+ return
+ }
+ defer endKeeper(k)
+ defer k.setListening(false)
+ ready <- k
+ for {
+ now := time.Now()
+ if k.armed.Load() {
+ if idle, _ := keepIdle(now, len(k.named), k.asked, k.gone); idle {
+ k.setListening(false) // no settings window, none coming: the program rests
+ }
+ }
+ wait, overdue := keepWait(now, k.asked, k.settleEnd, k.late)
+ if overdue {
+ k.overdue()
+ continue
+ }
+ if k.armed.Load() {
+ if _, until := keepIdle(now, len(k.named), k.asked, k.gone); until >= 0 && (wait < 0 || until < wait) {
+ wait = until
+ }
+ }
+ ms := uintptr(infinite)
+ if wait >= 0 {
+ ms = uintptr(wait / time.Millisecond)
+ }
+ r, _, _ := pMsgWaitForObjects.Call(0, 0, 0, ms, qsAllInput)
+ switch r {
+ case waitFailed:
+ log("INFO", "The settings window's icon is no longer looked after: waiting for events failed.")
+ return
+ case waitTimeout:
+ if k.armed.Load() {
+ k.sweep(topWindowHandles())
+ }
+ continue
+ }
+ for {
+ if got, _, _ := pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmRemove); got == 0 {
+ break
+ }
+ switch {
+ case m.message == wmQuit: // StopWindowIcon
+ log("INFO", "The settings window's icon is no longer looked after: the program quits.")
+ return
+ case m.hwnd == 0 && m.message == wmWindowAsked:
+ k.windowAsked(time.Now())
+ k.sweep(topWindowHandles())
+ default:
+ pTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
+ pDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
+ }
}
}
}
@@ -141,10 +778,11 @@ func setWindowStrings(hwnd uintptr, values []windowString) bool {
}
var (
- pPrivateExtractIcons = user32.NewProc("PrivateExtractIconsW")
+ pPrivateExtractIcons = user32.NewProc("PrivateExtractIconsW")
+ pCreateIconFromResourceEx = user32.NewProc("CreateIconFromResourceEx")
- // the icons the window was last given: they must outlive the call (the window only keeps their handles), and the
- // ones before them are freed when new ones are set
+ // the program's icons for the window, read once (loadWindowIcons): a window only keeps their handles, so they are
+ // kept for the program's life
windowIconMu sync.Mutex
windowIcons [2]uintptr
)
@@ -154,27 +792,104 @@ const (
smCxIcon = 11 // the width of a large icon on this screen; smCxSmIcon (tray_windows.go) is the small one's
)
-// setWindowIcons gives the window the program file's own icon in the two sizes Windows asks a window for, each read
-// at exactly that size (the taskbar button and Alt+Tab use the large one, the title bar the small one). An icon
-// handle is valid in every process of the session, so the browser's window can use one this program holds.
-func setWindowIcons(hwnd uintptr, exe string) {
- path, err := syscall.UTF16PtrFromString(exe)
- if err != nil {
- return
+// icoImage finds in an .ico file the image for an icon of size px: the one of exactly that size, else the smallest
+// larger one, else the largest (nil: none, or not an .ico file).
+func icoImage(ico []byte, size int) []byte {
+ if len(ico) < 6 || binary.LittleEndian.Uint16(ico[0:]) != 0 || binary.LittleEndian.Uint16(ico[2:]) != 1 {
+ return nil
}
+ n := int(binary.LittleEndian.Uint16(ico[4:]))
+ var best []byte
+ bestW := 0
+ for i := 0; i < n; i++ {
+ e := 6 + 16*i
+ if e+16 > len(ico) {
+ return nil
+ }
+ w := int(ico[e])
+ if w == 0 {
+ w = 256
+ }
+ length, off := int(binary.LittleEndian.Uint32(ico[e+8:])), int(binary.LittleEndian.Uint32(ico[e+12:]))
+ if length <= 0 || off < 0 || off+length > len(ico) {
+ continue
+ }
+ better := best == nil ||
+ (w >= size && (bestW < size || w < bestW)) || // a fitting one, smaller than the fitting one before
+ (w < size && bestW < size && w > bestW) // none fits yet: the largest
+ if better {
+ best, bestW = ico[off:off+length], w
+ }
+ }
+ return best
+}
+
+// loadWindowIcons makes the program's icon in the two sizes Windows asks a window for, each at exactly that size
+// (the taskbar button and Alt+Tab use the large one, the title bar the small one), from the icon built into the
+// program (so a program file that cannot be read yet, while a virus scanner looks at it, does not matter), else from
+// the program file. A size that could be made is kept; one that could not is tried again next time. An icon handle is
+// valid in every process of the session, so the browser's window can use one this program holds.
+func loadWindowIcons(exe string) {
windowIconMu.Lock()
defer windowIconMu.Unlock()
- for i, metric := range []uintptr{smCxSmIcon, smCxIcon} { // i is also WM_SETICON's ICON_SMALL (0) and ICON_BIG (1)
+ for i, metric := range []uintptr{smCxSmIcon, smCxIcon} {
+ if windowIcons[i] != 0 {
+ continue
+ }
size, _, _ := pGetSystemMetrics.Call(metric)
var icon uintptr
- if n, _, _ := pPrivateExtractIcons.Call(uintptr(unsafe.Pointer(path)), 0, size, size, uintptr(unsafe.Pointer(&icon)), 0, 1, 0); int32(n) < 1 || icon == 0 {
- continue // a program file without an icon (a plain development build): the browser's stays
+ if img := icoImage(assets.Icon, int(size)); img != nil {
+ b := append([]byte(nil), img...)
+ icon, _, _ = pCreateIconFromResourceEx.Call(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 1, 0x00030000, size, size, 0)
}
- pPostMessage.Call(hwnd, wmSetIcon, uintptr(i), icon)
- if old := windowIcons[i]; old != 0 {
- // freed a moment later: the window may still be drawing with it
- time.AfterFunc(5*time.Second, func() { pDestroyIcon.Call(old) })
+ if icon == 0 && exe != "" {
+ if path, err := syscall.UTF16PtrFromString(exe); err == nil {
+ if n, _, _ := pPrivateExtractIcons.Call(uintptr(unsafe.Pointer(path)), 0, size, size, uintptr(unsafe.Pointer(&icon)), 0, 1, 0); int32(n) < 1 {
+ icon = 0
+ }
+ }
}
windowIcons[i] = icon
}
}
+
+// haveWindowIcons says whether both of the program's icons could be made.
+func haveWindowIcons() bool {
+ windowIconMu.Lock()
+ defer windowIconMu.Unlock()
+ return windowIcons[0] != 0 && windowIcons[1] != 0
+}
+
+// checkWindowIcons gives the window the icons loadWindowIcons made again where it has others, and says what it found.
+// (Setting them when it has them already would make the taskbar button redraw, which the shell hook reports: it would
+// never end.)
+func checkWindowIcons(hwnd uintptr) iconState {
+ windowIconMu.Lock()
+ want := windowIcons
+ windowIconMu.Unlock()
+ state := iconsOurs
+ for i, icon := range want {
+ var has uintptr
+ r, _, _ := pSendMessageTimeout.Call(hwnd, wmGetIcon, uintptr(i), 0, smtoAbortIfHung, 200, uintptr(unsafe.Pointer(&has)))
+ if icon == 0 || r == 0 {
+ state = iconsUnknown
+ continue
+ }
+ if has != icon {
+ applyWindowIcons(hwnd)
+ return iconsSet
+ }
+ }
+ return state
+}
+
+// applyWindowIcons gives the window the icons loadWindowIcons made.
+func applyWindowIcons(hwnd uintptr) {
+ windowIconMu.Lock()
+ defer windowIconMu.Unlock()
+ for i, icon := range windowIcons { // i is also WM_SETICON's ICON_SMALL (0) and ICON_BIG (1)
+ if icon != 0 {
+ pPostMessage.Call(hwnd, wmSetIcon, uintptr(i), icon)
+ }
+ }
+}
diff --git a/internal/winsys/taskbar_windows_test.go b/internal/winsys/taskbar_windows_test.go
index b44dc7c..79399e0 100644
--- a/internal/winsys/taskbar_windows_test.go
+++ b/internal/winsys/taskbar_windows_test.go
@@ -1,11 +1,92 @@
package winsys
-import "testing"
+import (
+ "bytes"
+ "encoding/binary"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+ "unsafe"
+
+ "github.com/CptPakundo/MPRP/internal/assets"
+)
+
+// The real keeping's thread, with a profile no browser uses (so it finds and names nothing, and touches nothing): it
+// starts, registers its shell hook, and while it looks at every window often (its first seconds after a window was
+// asked for, each look taking the window list) other threads take the window list too, which reads every window's
+// details, the keeper's hidden window among them. Asking a window of this process for its title waits for the
+// thread that owns it; when that thread is the keeper waiting for the same list, both waited for good (fixed by
+// leaving this process's own windows' titles alone). Then the hidden window's procedure answers on the keeper's
+// thread, and StopWindowIcon ends the thread and its window.
+func TestKeeperThreadRunsAndEnds(t *testing.T) {
+ StopWindowIcon()
+ defer StopWindowIcon()
+ profile := filepath.Join(t.TempDir(), "window")
+ var logMu sync.Mutex
+ var logs []string
+ log := func(level, msg string) {
+ logMu.Lock()
+ defer logMu.Unlock()
+ logs = append(logs, level+" "+msg)
+ }
+ if !NameWindow(profile, log) {
+ t.Fatal("the keeping did not start")
+ }
+ k := currentKeeper()
+ if k == nil || k.done == nil || k.hidden == 0 {
+ t.Fatalf("no keeping, or no hidden window: %+v", k)
+ }
+
+ until := time.Now().Add(1500 * time.Millisecond)
+ var wg sync.WaitGroup
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for time.Now().Before(until) {
+ topWindows()
+ findWindow(profile)
+ }
+ }()
+ }
+ listed := make(chan struct{})
+ go func() { wg.Wait(); close(listed) }()
+ select {
+ case <-listed:
+ case <-time.After(20 * time.Second):
+ t.Fatal("the window lists hung while the keeper looked at the windows (a deadlock)")
+ }
+
+ var res uintptr
+ if r, _, _ := pSendMessageTimeout.Call(k.hidden, shellHookMessage(), hshellRedraw, 0, smtoAbortIfHung, 2000, uintptr(unsafe.Pointer(&res))); r == 0 {
+ t.Error("the hidden window's procedure did not answer")
+ }
+ if !k.armed.Load() {
+ logMu.Lock()
+ t.Logf("the shell hook could not be registered here (no shell?): %q", logs)
+ logMu.Unlock()
+ }
+
+ StopWindowIcon()
+ select {
+ case <-k.done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the keeper's thread did not end after StopWindowIcon")
+ }
+ if ok, _, _ := pIsWindow.Call(k.hidden); ok != 0 {
+ t.Error("the hidden window outlived the keeper")
+ }
+ if currentKeeper() != nil {
+ t.Error("a keeping is still current")
+ }
+}
func TestWindowIdentity(t *testing.T) {
- const exe = `C:\Programs\Sample\MPCvibedRPC.exe`
+ const exe = `C:\Programs\Sample\MPRP.exe`
id, name, command, icon := windowIdentity(exe, "")
- if id != "MPCvibedRPC" || name != "MPCvibedRPC" || command != `"`+exe+`"` || icon != exe+",0" {
+ if id != "MPRP" || name != "MPRP" || command != `"`+exe+`"` || icon != exe+",0" {
t.Errorf("the installed copy: id %q, name %q, command %q, icon %q", id, name, command, icon)
}
// a copy with a data folder of its own: another button group, and a pinned button starts it with that folder
@@ -13,17 +94,462 @@ func TestWindowIdentity(t *testing.T) {
if id2 == id || id2 != runNameFor(`D:\Portable\data`) {
t.Errorf("a copy with its own folder has the ID %q (the installed one: %q)", id2, id)
}
- if name2 != "MPCvibedRPC" || command2 != `"`+exe+`" --home "D:\Portable\data"` {
+ if name2 != "MPRP" || command2 != `"`+exe+`" --home "D:\Portable\data"` {
t.Errorf("a copy with its own folder: name %q, command %q", name2, command2)
}
}
-// A window that is not there is not named, and nothing is waited for without a profile.
+// Nothing is kept without a profile, and no properties are set on no window.
func TestNameWindowWithoutAWindow(t *testing.T) {
- if NameWindow("") {
+ if NameWindow("", nil) {
t.Error("a window was named without a profile")
}
if setWindowStrings(0, []windowString{{propAppID, "Sample"}}) {
t.Error("properties were set on no window")
}
}
+
+// Only events about a window itself count: shown or retitled, it is checked; destroyed, it is forgotten.
+func TestIconEvent(t *testing.T) {
+ for _, c := range []struct {
+ event uint32
+ obj, child int32
+ want keepAction
+ why string
+ }{
+ {eventObjectShow, objIDWindow, childIDSelf, keepCheck, "shown"},
+ {eventObjectNameChange, objIDWindow, childIDSelf, keepCheck, "retitled"},
+ {eventObjectDestroy, objIDWindow, childIDSelf, keepForget, "destroyed"},
+ {eventObjectNameChange, -4, childIDSelf, keepNothing, "its contents (OBJID_CLIENT)"},
+ {eventObjectShow, objIDWindow, 3, keepNothing, "a child element"},
+ {eventObjectDestroy, objIDWindow, 3, keepNothing, "a child element goes"},
+ {0x800B, objIDWindow, childIDSelf, keepNothing, "moved (not asked for)"},
+ } {
+ if got := iconEvent(c.event, c.obj, c.child); got != c.want {
+ t.Errorf("%s: %v, want %v", c.why, got, c.want)
+ }
+ }
+}
+
+// A window that got a taskbar button, or whose button was redrawn (the browser set an icon of its own: no WinEvent
+// tells that), is checked; a destroyed one is forgotten.
+func TestShellEvent(t *testing.T) {
+ for _, c := range []struct {
+ code uintptr
+ want keepAction
+ why string
+ }{
+ {hshellRedraw, keepCheck, "redrawn"},
+ {hshellRedraw | 0x8000, keepCheck, "flashing (HSHELL_FLASH)"},
+ {hshellWindowCreated, keepCheck, "created"},
+ {hshellWindowDestroyed, keepForget, "destroyed"},
+ {4, keepNothing, "activated (not asked for)"},
+ } {
+ if got := shellEvent(c.code); got != c.want {
+ t.Errorf("%s: %v, want %v", c.why, got, c.want)
+ }
+ }
+}
+
+// Only windows with a taskbar button are named: not the browser's bubbles, menus, hidden helpers or child windows.
+func TestTaskbarWindow(t *testing.T) {
+ for _, c := range []struct {
+ w topWindow
+ want bool
+ why string
+ }{
+ {topWindow{Visible: true}, true, "a plain window"},
+ {topWindow{}, false, "hidden"},
+ {topWindow{Visible: true, Owned: true}, false, "owned (a bubble)"},
+ {topWindow{Visible: true, Tool: true}, false, "a tool window (a menu)"},
+ {topWindow{Visible: true, Owned: true, AppWindow: true}, true, "owned, but asks for a button"},
+ {topWindow{Visible: true, Child: true}, false, "a child window"},
+ } {
+ if got := taskbarWindow(c.w); got != c.want {
+ t.Errorf("%s: %v, want %v", c.why, got, c.want)
+ }
+ }
+}
+
+// All windows are looked at often in the first seconds after a window was asked for, less often until it appears,
+// and for a while after one was taken on; a window that does not appear is reported after 30 s, once, and then only
+// listened for; otherwise the keeping only waits for events.
+func TestKeepWait(t *testing.T) {
+ now := time.Now()
+ var zero time.Time
+ for _, c := range []struct {
+ asked, settleEnd time.Time
+ late bool
+ wait time.Duration
+ overdue bool
+ why string
+ }{
+ {zero, zero, false, -1, false, "nothing awaited"},
+ {now.Add(-time.Second), zero, false, nameWindowFastEvery, false, "just asked for"},
+ {now.Add(-5 * time.Second), zero, false, nameWindowEvery, false, "asked for a while ago"},
+ {now.Add(-nameWindowWarn), zero, false, 0, true, "not there after 30 s"},
+ {now.Add(-nameWindowWarn), zero, true, -1, false, "not there after 30 s, reported: only listened for"},
+ {zero, now.Add(5 * time.Second), false, keepSettleEvery, false, "just taken on"},
+ {zero, now.Add(100 * time.Millisecond), false, 100 * time.Millisecond, false, "the settling ends sooner"},
+ {zero, now.Add(-time.Second), false, -1, false, "settled"},
+ {now.Add(-time.Second), now.Add(5 * time.Second), false, nameWindowFastEvery, false, "the shorter of both"},
+ } {
+ w, o := keepWait(now, c.asked, c.settleEnd, c.late)
+ if w != c.wait || o != c.overdue {
+ t.Errorf("%s: wait %v overdue %v, want %v %v", c.why, w, o, c.wait, c.overdue)
+ }
+ }
+}
+
+// The keeping listens while a window is taken on, for 2 minutes after one was asked for, and for 30 s after the last
+// one went; otherwise it rests.
+func TestKeepIdle(t *testing.T) {
+ now := time.Now()
+ var zero time.Time
+ for _, c := range []struct {
+ named int
+ asked, gone time.Time
+ idle bool
+ until time.Duration
+ why string
+ }{
+ {0, zero, zero, true, 0, "nothing to listen for"},
+ {1, zero, zero, false, -1, "a window is taken on"},
+ {1, now.Add(-time.Hour), now.Add(-time.Hour), false, -1, "a window is taken on, whatever else"},
+ {0, now.Add(-time.Minute), zero, false, keepAskFor - time.Minute, "a window was asked for a minute ago"},
+ {0, now.Add(-keepAskFor), zero, true, 0, "a window asked for did not come"},
+ {0, zero, now.Add(-10 * time.Second), false, keepLinger - 10*time.Second, "the window went 10 s ago"},
+ {0, zero, now.Add(-keepLinger), true, 0, "the window went 30 s ago"},
+ {0, now.Add(-time.Minute), now.Add(-keepLinger), false, keepAskFor - time.Minute, "the later of both"},
+ } {
+ idle, until := keepIdle(now, c.named, c.asked, c.gone)
+ if idle != c.idle || until != c.until {
+ t.Errorf("%s: idle %v until %v, want %v %v", c.why, idle, until, c.idle, c.until)
+ }
+ }
+}
+
+// fakeKeeper is a keeping whose windows are described by wins; the processes in profile use the window profile.
+type fakeKeeper struct {
+ wins map[uintptr]topWindow
+ profile map[uint32]bool
+ looked map[uint32]int // how often each process was looked up
+ named, checked map[uintptr]int
+ hooked, unhooked map[uint32]int
+ hasIcon map[uintptr]bool
+ noIcons, refuse bool
+ listening bool
+ listens int
+ deaf bool // the shell hook cannot be registered
+ logs []string
+ ended int
+}
+
+func newFakeKeeper() (*fakeKeeper, *iconKeeper) {
+ f := &fakeKeeper{wins: map[uintptr]topWindow{}, profile: map[uint32]bool{10: true, 11: true}, looked: map[uint32]int{},
+ named: map[uintptr]int{}, checked: map[uintptr]int{}, hooked: map[uint32]int{}, unhooked: map[uint32]int{},
+ hasIcon: map[uintptr]bool{}}
+ k := &iconKeeper{self: 1,
+ visible: func(h uintptr) bool { return f.wins[h].Visible },
+ inspect: func(h uintptr) topWindow { return f.wins[h] },
+ ours: func(pid uint32) bool { f.looked[pid]++; return f.profile[pid] },
+ name: func(h uintptr) bool { f.named[h]++; return !f.refuse },
+ check: func(h uintptr) iconState {
+ f.checked[h]++
+ if f.hasIcon[h] {
+ return iconsOurs
+ }
+ return iconsSet
+ },
+ listen: func() bool {
+ f.listens++
+ f.listening = !f.deaf
+ return !f.deaf
+ },
+ unlisten: func() { f.listening = false },
+ hook: func(pid uint32) []uintptr {
+ f.hooked[pid]++
+ return []uintptr{uintptr(pid)}
+ },
+ unhook: func(hooks []uintptr) { f.unhooked[uint32(hooks[0])]++ },
+ iconsLoaded: func() bool { return !f.noIcons },
+ log: func(level, msg string) { f.logs = append(f.logs, level+" "+msg) },
+ end: func() { f.ended++ }}
+ return f, k
+}
+
+func (f *fakeKeeper) add(h uintptr, w topWindow) {
+ w.Handle = h
+ f.wins[h] = w
+}
+
+// A taskbar window of a process that uses the profile is named once, whenever it appears and whichever process it
+// is in (the browser replaced its process, or the window came late); then its icon is kept. Another program's window,
+// the browser's bubble and its hidden windows are left alone, and whose a window is is looked up only once.
+func TestIconKeeperAdoptsTheProfilesWindows(t *testing.T) {
+ f, k := newFakeKeeper()
+ f.add(0x10, topWindow{Pid: 10, Visible: true, Titled: true})
+ f.add(0x30, topWindow{Pid: 99, Visible: true, Titled: true})
+ f.add(0x40, topWindow{Pid: 10, Visible: true, Owned: true})
+ f.add(0x50, topWindow{Pid: 10})
+
+ k.shell(hshellWindowCreated, 0x10)
+ k.event(eventObjectShow, 0x10, objIDWindow, childIDSelf)
+ k.shell(hshellRedraw, 0x10)
+ if f.named[0x10] != 1 || f.checked[0x10] != 2 || f.hooked[10] != 1 {
+ t.Errorf("the window: named %d (want 1), checked %d (want 2), its process hooked %d (want 1)", f.named[0x10], f.checked[0x10], f.hooked[10])
+ }
+ if k.settleEnd.IsZero() {
+ t.Error("taking on a window did not start a while of looking")
+ }
+ for i := 0; i < 3; i++ {
+ k.shell(hshellRedraw, 0x30)
+ }
+ k.shell(hshellWindowCreated, 0x40)
+ k.sweep([]uintptr{0x30, 0x40, 0x50})
+ if f.named[0x30]+f.checked[0x30]+f.named[0x40]+f.checked[0x40]+f.named[0x50]+f.checked[0x50] != 0 {
+ t.Errorf("another program's window, a bubble or a hidden window was touched: %v %v", f.named, f.checked)
+ }
+ if f.looked[99] != 1 || f.looked[10] != 1 {
+ t.Errorf("processes looked up %v, want each once", f.looked)
+ }
+ // the browser's process ends and a new one shows the window: taken on as well
+ k.shell(hshellWindowDestroyed, 0x10)
+ delete(f.wins, 0x10)
+ if f.unhooked[10] != 1 {
+ t.Error("the process's hooks stayed after its last window went")
+ }
+ f.add(0x20, topWindow{Pid: 11, Visible: true})
+ k.sweep([]uintptr{0x30, 0x20})
+ if f.named[0x20] != 1 || f.hooked[11] != 1 {
+ t.Errorf("the window of the new process: named %d, hooked %d", f.named[0x20], f.hooked[11])
+ }
+ // a handle given to another program's window is looked up again
+ k.shell(hshellWindowDestroyed, 0x20)
+ f.add(0x20, topWindow{Pid: 99, Visible: true})
+ k.shell(hshellWindowCreated, 0x20)
+ if f.named[0x20] != 1 || f.looked[99] != 2 {
+ t.Errorf("a reused handle: named %d (want 1), process 99 looked up %d (want 2)", f.named[0x20], f.looked[99])
+ }
+ // the program's own windows are never touched
+ f.add(0x60, topWindow{Pid: 1, Visible: true})
+ k.shell(hshellWindowCreated, 0x60)
+ if f.named[0x60] != 0 || f.looked[1] != 0 {
+ t.Error("the program's own window was looked at")
+ }
+ if f.ended != 0 {
+ t.Error("the keeping ended with a window")
+ }
+}
+
+// What the log gets: the window's icon confirmed once, each failure once, a window that does not appear.
+func TestIconKeeperLog(t *testing.T) {
+ f, k := newFakeKeeper()
+ // a window that goes while it is named refuses its name too: that is no failure
+ f.add(0x05, topWindow{Pid: 10, Visible: true})
+ k.name = func(h uintptr) bool { f.wins[h] = topWindow{}; return false }
+ k.shell(hshellWindowCreated, 0x05)
+ k.name = func(h uintptr) bool { f.named[h]++; return !f.refuse }
+ f.add(0x10, topWindow{Pid: 10, Visible: true})
+ f.add(0x20, topWindow{Pid: 10, Visible: true})
+ k.windowAsked(time.Now())
+ f.noIcons, f.refuse = true, true
+ k.shell(hshellWindowCreated, 0x10)
+ k.shell(hshellWindowCreated, 0x20)
+ if !k.asked.IsZero() {
+ t.Error("a window taken on still counts as awaited")
+ }
+ k.shell(hshellRedraw, 0x10) // no icon yet: nothing to report
+ f.hasIcon[0x10], f.hasIcon[0x20] = true, true
+ k.shell(hshellRedraw, 0x10)
+ k.shell(hshellRedraw, 0x20)
+ k.windowAsked(time.Now())
+ k.overdue()
+ got := strings.Join(f.logs, "\n")
+ want := strings.Join([]string{
+ "WARN The settings window keeps the browser's icon: the program's icon could not be loaded.",
+ "WARN The settings window's taskbar button could not be given the program's name (its property store refused it).",
+ "INFO The settings window got the program's taskbar icon.",
+ "WARN The settings window was not found within 30 s; it gets the program's taskbar icon if it appears in the next minutes.",
+ }, "\n")
+ if got != want {
+ t.Errorf("log:\n%s\nwant:\n%s", got, want)
+ }
+ if _, overdue := keepWait(time.Now().Add(nameWindowWarn), k.asked, time.Time{}, k.late); overdue || k.asked.IsZero() {
+ t.Error("an overdue window is reported again, or no longer listened for")
+ }
+}
+
+// The shell hook is registered when a window is asked for and stays while a window is taken on; once none is left
+// and none is coming it is deregistered, and with it what the keeping knew (its WinEvent hooks, whose windows were
+// whose); a new ask registers it again. A hook that cannot be registered is reported once.
+func TestIconKeeperListensOnlyWhenNeeded(t *testing.T) {
+ f, k := newFakeKeeper()
+ f.add(0x10, topWindow{Pid: 10, Visible: true})
+ f.add(0x30, topWindow{Pid: 99, Visible: true})
+ k.windowAsked(time.Now())
+ if !f.listening || !k.armed.Load() {
+ t.Fatal("not listening after a window was asked for")
+ }
+ k.shell(hshellWindowCreated, 0x10)
+ k.shell(hshellWindowCreated, 0x30)
+ if idle, _ := keepIdle(time.Now(), len(k.named), k.asked, k.gone); idle {
+ t.Error("idle with a window taken on")
+ }
+ k.shell(hshellWindowDestroyed, 0x10)
+ if k.gone.IsZero() {
+ t.Fatal("the last window's going was not noted")
+ }
+ if idle, until := keepIdle(time.Now(), len(k.named), k.asked, k.gone); idle || until <= 0 || until > keepLinger {
+ t.Errorf("right after the last window went: idle %v, until %v (want a while of listening)", idle, until)
+ }
+ if idle, _ := keepIdle(time.Now().Add(keepLinger), len(k.named), k.asked, k.gone); !idle {
+ t.Error("still listening 30 s after the last window went")
+ }
+ k.setListening(false) // as the loop does then
+ if f.listening || k.armed.Load() || f.unhooked[10] != 1 || len(k.verdict) != 0 {
+ t.Errorf("after resting: listening %v, unhooked %v, windows remembered %v", f.listening, f.unhooked, k.verdict)
+ }
+ k.windowAsked(time.Now())
+ if !f.listening || f.listens != 2 {
+ t.Errorf("a new ask did not listen again (listening %v, %d registrations)", f.listening, f.listens)
+ }
+ k.shell(hshellWindowCreated, 0x30)
+ if f.looked[99] != 2 {
+ t.Error("whose a window is was not looked up again after resting")
+ }
+
+ f2, k2 := newFakeKeeper()
+ f2.deaf = true
+ k2.windowAsked(time.Now())
+ k2.windowAsked(time.Now())
+ if k2.armed.Load() || len(f2.logs) != 1 || !strings.Contains(f2.logs[0], "shell hook could not be set up") {
+ t.Errorf("a hook that cannot be registered: armed %v, log %q", k2.armed.Load(), f2.logs)
+ }
+}
+
+// A window whose browser puts its own icon back every time (or answers for it) is corrected at most 20 times within
+// 10 s, then left alone and reported once; another window is still corrected, and the count starts anew after 10 s.
+func TestIconKeeperStopsCorrectingAWindowThatFightsBack(t *testing.T) {
+ f, k := newFakeKeeper()
+ f.add(0x10, topWindow{Pid: 10, Visible: true})
+ f.add(0x20, topWindow{Pid: 10, Visible: true})
+ k.shell(hshellWindowCreated, 0x10)
+ k.shell(hshellWindowCreated, 0x20)
+ for i := 0; i < 100; i++ {
+ k.shell(hshellRedraw, 0x10) // every correction redraws the button: the next notification
+ }
+ if f.checked[0x10] != keepFixesMax+1 {
+ t.Errorf("corrected %d times, want %d", f.checked[0x10], keepFixesMax+1)
+ }
+ if len(f.logs) != 1 || !strings.Contains(f.logs[0], "put it back more than 20 times in 10 s") {
+ t.Errorf("log %q, want one line", f.logs)
+ }
+ k.shell(hshellRedraw, 0x20)
+ if f.checked[0x20] != 1 {
+ t.Error("another window is no longer corrected")
+ }
+ c := fixCount{}
+ start := time.Now()
+ for i := 0; i < keepFixesMax; i++ {
+ if c.add(start) {
+ t.Fatal("too many before the limit")
+ }
+ }
+ if !c.add(start.Add(time.Second)) {
+ t.Error("the 21st correction within 10 s is not too many")
+ }
+ if c.add(start.Add(keepFixesPer + 2*time.Second)) {
+ t.Error("the count did not start anew after 10 s")
+ }
+ // a window that goes and whose handle comes back is corrected again
+ k.shell(hshellWindowDestroyed, 0x10)
+ k.shell(hshellWindowCreated, 0x10)
+ k.shell(hshellRedraw, 0x10)
+ if f.checked[0x10] != keepFixesMax+2 {
+ t.Errorf("a new window under the same handle: checked %d, want %d", f.checked[0x10], keepFixesMax+2)
+ }
+}
+
+// One keeping at a time; StopWindowIcon ends it, and a keeping that starts after it is not taken. The hook's
+// callback and the shell window's procedure reach the current one, with idObject as Windows passes it (a LONG in a
+// pointer-sized argument).
+func TestIconKeeperLifecycle(t *testing.T) {
+ StopWindowIcon()
+ gen := iconGen.Load()
+ f1, k1 := newFakeKeeper()
+ f1.add(0x10, topWindow{Pid: 10, Visible: true})
+ f2, k2 := newFakeKeeper()
+ f2.add(0x10, topWindow{Pid: 10, Visible: true})
+ if !startKeeper(k1, gen) {
+ t.Fatal("the first keeping did not start")
+ }
+ onWinEvent(0, eventObjectShow, 0x10, 0, 0, 0, 0)
+ onWinEvent(0, eventObjectNameChange, 0x10, uintptr(0xFFFFFFFC), 0, 0, 0) // OBJID_CLIENT: not the window
+ if f1.named[0x10] != 1 || f1.checked[0x10] != 0 {
+ t.Errorf("first keeping: named %d checked %d", f1.named[0x10], f1.checked[0x10])
+ }
+ if !startKeeper(k2, gen) || f1.ended != 1 {
+ t.Error("a new keeping did not end the one before")
+ }
+ m := uint32(shellHookMessage())
+ if m == 0 {
+ t.Fatal("no SHELLHOOK message")
+ }
+ shellWindowProc(0, m, hshellRedraw, 0x10)
+ if f1.named[0x10] != 1 || f2.named[0x10] != 1 {
+ t.Errorf("the shell hook's redraw went to %v %v", f1.named, f2.named)
+ }
+ k2.stop()
+ k2.stop()
+ if f2.ended != 1 {
+ t.Errorf("the keeping ended %d times, want once", f2.ended)
+ }
+ endKeeper(k2)
+ f3, k3 := newFakeKeeper()
+ if !startKeeper(k3, gen) {
+ t.Fatal("a third keeping did not start")
+ }
+ StopWindowIcon()
+ if f3.ended != 1 {
+ t.Error("StopWindowIcon did not end the keeping")
+ }
+ if _, k4 := newFakeKeeper(); startKeeper(k4, gen) {
+ t.Error("a keeping started after StopWindowIcon")
+ }
+ f3.add(0x30, topWindow{Pid: 10, Visible: true})
+ onWinEvent(0, eventObjectShow, 0x30, 0, 0, 0, 0)
+ if f3.named[0x30] != 0 {
+ t.Error("an event came through after StopWindowIcon")
+ }
+}
+
+// The window's icons come from the icon built into the program, at the size asked for (or the next larger one).
+func TestIcoImage(t *testing.T) {
+ for _, c := range []struct{ size, want int }{{16, 16}, {32, 32}, {64, 64}, {36, 40}, {20, 24}, {96, 64}} {
+ img := icoImage(assets.Icon, c.size)
+ if img == nil {
+ t.Fatalf("%d px: no image", c.size)
+ }
+ if w := imageWidth(img); w != c.want {
+ t.Errorf("%d px: the %d px image, want %d", c.size, w, c.want)
+ }
+ }
+ for _, bad := range [][]byte{nil, []byte("not an icon"), {0, 0, 1, 0, 1, 0}} {
+ if icoImage(bad, 32) != nil {
+ t.Errorf("an image from %q", bad)
+ }
+ }
+ loadWindowIcons("") // from the built-in icon alone
+ if !haveWindowIcons() {
+ t.Error("the program's icons could not be made from the built-in icon")
+ }
+}
+
+// imageWidth is the width of an .ico image: a PNG's from its header, a bitmap's from its BITMAPINFOHEADER.
+func imageWidth(img []byte) int {
+ if bytes.HasPrefix(img, []byte("\x89PNG")) {
+ return int(binary.BigEndian.Uint32(img[16:]))
+ }
+ return int(binary.LittleEndian.Uint32(img[4:]))
+}
diff --git a/internal/winsys/tray_windows.go b/internal/winsys/tray_windows.go
index d6d57fa..b83c335 100644
--- a/internal/winsys/tray_windows.go
+++ b/internal/winsys/tray_windows.go
@@ -80,7 +80,7 @@ const (
cmdHide = 4
cmdStream = 5
timerID = 1
- className = "MPCvibedRPC.Tray"
+ className = "MPRP.Tray"
)
type wndClassEx struct {
@@ -181,7 +181,7 @@ func (t *Tray) loop() {
t.o.Log("WARN", "Tray icon could not start (RegisterClass: "+err.Error()+"). Open the app again to reach the settings.")
return
}
- hwnd, _, err := pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(cls)), uintptr(unsafe.Pointer(utf16Ptr("MPCvibedRPC"))), 0, 0, 0, 0, 0, 0, 0, hinst, 0)
+ hwnd, _, err := pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(cls)), uintptr(unsafe.Pointer(utf16Ptr("MPRP"))), 0, 0, 0, 0, 0, 0, 0, hinst, 0)
if hwnd == 0 {
t.o.Log("WARN", "Tray icon could not start (CreateWindow: "+err.Error()+"). Open the app again to reach the settings.")
return
@@ -243,7 +243,7 @@ func (t *Tray) tooltip() string {
if t.o.Tooltip != nil {
return t.o.Tooltip()
}
- return "MPCvibedRPC"
+ return "MPRP"
}
func (t *Tray) notify(action uintptr) bool {
@@ -300,7 +300,7 @@ func (t *Tray) showMenu() {
toggle = "Stop showing on Discord"
}
// the first line says what the program is doing (the icon's tooltip, without the program's name)
- status := strings.TrimPrefix(t.tooltip(), "MPCvibedRPC - ")
+ status := strings.TrimPrefix(t.tooltip(), "MPRP - ")
pAppendMenu.Call(menu, mfString|mfDisabled|mfGrayed, 0, uintptr(unsafe.Pointer(utf16Ptr(status))))
pAppendMenu.Call(menu, mfSeparator, 0, 0)
pAppendMenu.Call(menu, mfString, cmdOpen, uintptr(unsafe.Pointer(utf16Ptr("Open settings"))))
diff --git a/internal/winsys/unix.go b/internal/winsys/unix.go
index ed57255..15db07a 100644
--- a/internal/winsys/unix.go
+++ b/internal/winsys/unix.go
@@ -9,7 +9,7 @@ import (
"strings"
)
-// The macOS and Linux versions of what run.go, mpcsetup.go and window.go do on Windows: the running players, the
+// The macOS and Linux versions of what run.go, playersetup.go and window.go do on Windows: the running players, the
// system description, the browser and the player setup. They live in an ordinary file (not one for a single system) so
// that their logic is tested everywhere; only the helper programs they start are missing on Windows.
diff --git a/internal/winsys/unix_test.go b/internal/winsys/unix_test.go
index b046623..4bde6b1 100644
--- a/internal/winsys/unix_test.go
+++ b/internal/winsys/unix_test.go
@@ -7,66 +7,66 @@ import (
"strings"
"testing"
- "github.com/CptPakundo/MPCvibedRPC/internal/pipe"
+ "github.com/CptPakundo/MPRP/internal/pipe"
)
func TestLoginItemPaths(t *testing.T) {
- t.Setenv("MPCRPC_HOME", "")
+ t.Setenv("MPRP_HOME", "")
home := filepath.Join("home", "someone")
- if got, want := loginItemPath("darwin", home, ""), filepath.Join(home, "Library", "LaunchAgents", "io.github.cptpakundo.mpcvibedrpc.plist"); got != want {
+ if got, want := loginItemPath("darwin", home, ""), filepath.Join(home, "Library", "LaunchAgents", "io.github.cptpakundo.mprp.plist"); got != want {
t.Errorf("macOS: %s, want %s", got, want)
}
- if got, want := loginItemPath("linux", home, ""), filepath.Join(home, ".config", "autostart", "mpcvibedrpc.desktop"); got != want {
+ if got, want := loginItemPath("linux", home, ""), filepath.Join(home, ".config", "autostart", "mprp.desktop"); got != want {
t.Errorf("Linux: %s, want %s", got, want)
}
- if got, want := loginItemPath("linux", home, filepath.Join("cfg")), filepath.Join("cfg", "autostart", "mpcvibedrpc.desktop"); got != want {
+ if got, want := loginItemPath("linux", home, filepath.Join("cfg")), filepath.Join("cfg", "autostart", "mprp.desktop"); got != want {
t.Errorf("Linux with XDG_CONFIG_HOME: %s, want %s", got, want)
}
if loginItemPath("linux", "", "") != "" || loginItemPath("darwin", "", "x") != "" {
t.Error("no home folder, no login item")
}
// a copy with a data folder of its own gets a login item of its own
- t.Setenv("MPCRPC_HOME", filepath.Join("tmp", "test-copy"))
+ t.Setenv("MPRP_HOME", filepath.Join("tmp", "test-copy"))
p := loginItemPath("linux", home, "")
- if !strings.Contains(p, "mpcvibedrpc-") || p == filepath.Join(home, ".config", "autostart", "mpcvibedrpc.desktop") {
+ if !strings.Contains(p, "mprp-") || p == filepath.Join(home, ".config", "autostart", "mprp.desktop") {
t.Errorf("isolated copy: %s", p)
}
}
func TestLoginItemContent(t *testing.T) {
- t.Setenv("MPCRPC_HOME", "")
- plist := loginItem("darwin", "/Applications/MPCvibedRPC.app/Contents/MacOS/MPCvibedRPC", "")
- for _, want := range []string{"io.github.cptpakundo.mpcvibedrpc",
- "/Applications/MPCvibedRPC.app/Contents/MacOS/MPCvibedRPC", "--background", "RunAtLoad\n\t"} {
+ t.Setenv("MPRP_HOME", "")
+ plist := loginItem("darwin", "/Applications/MPRP.app/Contents/MacOS/MPRP", "")
+ for _, want := range []string{"io.github.cptpakundo.mprp",
+ "/Applications/MPRP.app/Contents/MacOS/MPRP", "--background", "RunAtLoad\n\t"} {
if !strings.Contains(plist, want) {
t.Errorf("plist lacks %q:\n%s", want, plist)
}
}
- if strings.Contains(plist, "MPCRPC_HOME") {
+ if strings.Contains(plist, "MPRP_HOME") {
t.Error("no data folder of its own, no environment")
}
if v, err := parsePlist(strings.NewReader(plist)); err != nil || v.(map[string]any)["RunAtLoad"] != true {
t.Errorf("the plist must be readable: %v %v", v, err)
}
// odd characters are escaped
- plist = loginItem("darwin", "/Apps/A & B /MPCvibedRPC", "/data/My \"copy\"")
- if !strings.Contains(plist, "A & B <x>") || !strings.Contains(plist, "MPCRPC_HOME") {
+ plist = loginItem("darwin", "/Apps/A & B /MPRP", "/data/My \"copy\"")
+ if !strings.Contains(plist, "A & B <x>") || !strings.Contains(plist, "MPRP_HOME") {
t.Errorf("escaping:\n%s", plist)
}
if v, err := parsePlist(strings.NewReader(plist)); err != nil {
t.Errorf("escaped plist unreadable: %v", err)
- } else if args := v.(map[string]any)["ProgramArguments"].([]any); args[0] != "/Apps/A & B /MPCvibedRPC" {
+ } else if args := v.(map[string]any)["ProgramArguments"].([]any); args[0] != "/Apps/A & B /MPRP" {
t.Errorf("program: %v", args)
}
- desktop := loginItem("linux", "/opt/MPCvibedRPC/MPCvibedRPC", "")
- for _, want := range []string{"[Desktop Entry]\n", "Type=Application\n", `Exec="/opt/MPCvibedRPC/MPCvibedRPC" --background` + "\n", "Name=MPCvibedRPC\n"} {
+ desktop := loginItem("linux", "/opt/MPRP/MPRP", "")
+ for _, want := range []string{"[Desktop Entry]\n", "Type=Application\n", `Exec="/opt/MPRP/MPRP" --background` + "\n", "Name=MPRP\n"} {
if !strings.Contains(desktop, want) {
t.Errorf("desktop entry lacks %q:\n%s", want, desktop)
}
}
- desktop = loginItem("linux", "/opt/a b/MPCvibedRPC", "/data/x")
- if !strings.Contains(desktop, `Exec=env "MPCRPC_HOME=/data/x" "/opt/a b/MPCvibedRPC" --background`) {
+ desktop = loginItem("linux", "/opt/a b/MPRP", "/data/x")
+ if !strings.Contains(desktop, `Exec=env "MPRP_HOME=/data/x" "/opt/a b/MPRP" --background`) {
t.Errorf("with a data folder:\n%s", desktop)
}
}
@@ -235,10 +235,10 @@ func TestMpvConfPathsUnix(t *testing.T) {
}
func TestTranslocatedAppGetsNoLoginItem(t *testing.T) {
- if !translocated("/private/var/folders/ab/xyz/T/AppTranslocation/0A1B/d/MPCvibedRPC.app/Contents/MacOS/MPCvibedRPC") {
+ if !translocated("/private/var/folders/ab/xyz/T/AppTranslocation/0A1B/d/MPRP.app/Contents/MacOS/MPRP") {
t.Error("a translocated app must be recognised")
}
- if translocated("/Applications/MPCvibedRPC.app/Contents/MacOS/MPCvibedRPC") {
+ if translocated("/Applications/MPRP.app/Contents/MacOS/MPRP") {
t.Error("an app in Applications is not translocated")
}
}
diff --git a/internal/winsys/window.go b/internal/winsys/window.go
index 7affd20..120fb4e 100644
--- a/internal/winsys/window.go
+++ b/internal/winsys/window.go
@@ -7,7 +7,7 @@ import (
"path/filepath"
"runtime"
- "github.com/CptPakundo/MPCvibedRPC/internal/proc"
+ "github.com/CptPakundo/MPRP/internal/proc"
)
// findBrowser returns Edge/Chrome/Brave/Vivaldi if installed.
@@ -50,17 +50,17 @@ func start(c *exec.Cmd) bool {
// OpenWindow shows the page in an app-style window (no tabs or address bar) when Edge/Chrome is there, else in the
// default browser. It returns "app", "browser" or "" (nothing could be started). With a profileDir the window
// gets a browser profile of its own, so the user's regular profile is left alone and no background browser outlives
-// the window; CloseWindowBrowser(profileDir) ends it. MPCRPC_BROWSER names the browser to use instead, or "none".
+// the window; CloseWindowBrowser(profileDir) ends it. MPRP_BROWSER names the browser to use instead, or "none".
func OpenWindow(url, profileDir string) string {
b := findBrowser()
- switch v := os.Getenv("MPCRPC_BROWSER"); v {
+ switch v := os.Getenv("MPRP_BROWSER"); v {
case "":
case "none":
return "" // no window (a computer without a screen, a test)
default:
b = v // a browser of the user's choice; it has to understand --app
}
- if macApp && os.Getenv("MPCRPC_BROWSER") == "" && openNativeWindow(url) {
+ if macApp && os.Getenv("MPRP_BROWSER") == "" && openNativeWindow(url) {
return "app" // the macOS app shows the page in a window of its own
}
if b != "" {
diff --git a/tools/ci/allowed-skips.sh b/tools/ci/allowed-skips.sh
index f4e8158..dd28bf7 100755
--- a/tools/ci/allowed-skips.sh
+++ b/tools/ci/allowed-skips.sh
@@ -2,10 +2,10 @@
# Prints the tests that may skip on this runner's system, for test-noskip.sh (ci.yml and release.yml share it).
# The live tests are opt-in everywhere; on Windows the Unix-socket fakes and the end-to-end run are Linux/macOS-only
# (the smoke test covers them there); the update rollback run is Linux-only (the Windows smoke test has its own, and
-# the macOS program does not install updates itself). A new test that skips on some system belongs here.
+# the macOS program does not install updates itself); the data-folder copy for a held file is Windows-only (only Windows refuses that rename); the registry tests are opt-in. A new test that skips on some system belongs here.
live='TestLivePlayer|TestLiveJellyfin|TestLivePotPlayer|TestLiveCatalogs'
case "${RUNNER_OS:-$(uname -s)}" in
- Windows|MINGW*|MSYS*) echo "$live|TestEndToEnd|TestEndToEndUpdateRollback|TestLoginAndActivity|TestErrorReply|TestHandshakeTimeout|TestServerCloseFailsPending|TestCloseFrameSaysWhy|TestAutostartRegistryRoundTrip" ;;
- macOS|Darwin*) echo "$live|TestEndToEndUpdateRollback" ;;
- *) echo "$live" ;;
+ Windows|MINGW*|MSYS*) echo "$live|TestEndToEnd|TestEndToEndUpdateRollback|TestLoginAndActivity|TestErrorReply|TestHandshakeTimeout|TestServerCloseFailsPending|TestCloseFrameSaysWhy|TestAutostartRegistryRoundTrip|TestAutostartMigrationRegistry" ;;
+ macOS|Darwin*) echo "$live|TestEndToEndUpdateRollback|TestMoveFormerDataCopiesWhenAFileIsHeld" ;;
+ *) echo "$live|TestMoveFormerDataCopiesWhenAFileIsHeld" ;;
esac
diff --git a/tools/ci/dev-download.sh b/tools/ci/dev-download.sh
index 93fe2ae..38efae7 100755
--- a/tools/ci/dev-download.sh
+++ b/tools/ci/dev-download.sh
@@ -6,7 +6,7 @@
# dev-download.sh record BY TAG/FILE[=N] ... records downloads made another way (the program's own updater)
# BY says who downloaded ("release check v0.9.39 draft", "an automated agent"). Needs gh signed in with write access.
set -euo pipefail
-repo="${GITHUB_REPOSITORY:-CptPakundo/MPCvibedRPC}"
+repo="${GITHUB_REPOSITORY:-CptPakundo/MPRP}"
record() {
local by="$1"; shift
diff --git a/tools/ci/fake-http.ps1 b/tools/ci/fake-http.ps1
index 1a8f30d..8f09d88 100644
--- a/tools/ci/fake-http.ps1
+++ b/tools/ci/fake-http.ps1
@@ -16,13 +16,13 @@ while ($l.IsListening) {
$html = '
Sample.Movie.2001.1080p.mkv
C:\Movies\Sample.Movie.2001.1080p.mkv
' + $state + '
' + (1000 + [int]$clock.ElapsedMilliseconds) + '
7500000
1
'
$bytes = [Text.Encoding]::UTF8.GetBytes($html); $res.ContentType = 'text/html'
} elseif ($p -like '*/releases/latest') {
- $json = '{"tag_name":"v' + $Tag + '","body":"test release","html_url":"http://x","assets":[{"name":"MPCvibedRPC.exe","browser_download_url":"http://127.0.0.1:' + $Port + '/dl"},{"name":"MPCvibedRPC.exe.sha256","browser_download_url":"http://127.0.0.1:' + $Port + '/sha"}]}'
+ $json = '{"tag_name":"v' + $Tag + '","body":"test release","html_url":"http://x","assets":[{"name":"MPRP.exe","browser_download_url":"http://127.0.0.1:' + $Port + '/dl"},{"name":"MPRP.exe.sha256","browser_download_url":"http://127.0.0.1:' + $Port + '/sha"}]}'
$bytes = [Text.Encoding]::UTF8.GetBytes($json); $res.ContentType = 'application/json'
} elseif ($p -eq '/dl') {
$bytes = [IO.File]::ReadAllBytes($NewExe); $res.ContentType = 'application/octet-stream'
} elseif ($p -eq '/sha') { # the program only installs a release with a checksum file
$sum = (Get-FileHash -Algorithm SHA256 $NewExe).Hash.ToLower()
- $bytes = [Text.Encoding]::UTF8.GetBytes("$sum MPCvibedRPC.exe`n"); $res.ContentType = 'text/plain'
+ $bytes = [Text.Encoding]::UTF8.GetBytes("$sum MPRP.exe`n"); $res.ContentType = 'text/plain'
} else {
$res.StatusCode = 404; $bytes = [Text.Encoding]::UTF8.GetBytes('not found')
}
diff --git a/tools/ci/former-names.txt b/tools/ci/former-names.txt
new file mode 100644
index 0000000..c68e218
--- /dev/null
+++ b/tools/ci/former-names.txt
@@ -0,0 +1,20 @@
+# The program's former name, where releases still need it. The one list: release.yml and verify-release.ps1 read it.
+#
+# file
+# Copies installed before the rename look for their update under the former file name, so every release also
+# publishes a byte-identical copy of each program file under that name, with its own .sha256 and build record.
+# The program itself looks only for the current names.
+# env
+# The environment variables the former version reads: the release check runs the release before this one, which
+# may still be one of the former name.
+#
+# The maintainer decides when the former names are dropped (when no copy that needs them is in use any more). Then
+# delete the file lines (or this whole file and its uses in release.yml and verify-release.ps1).
+file MPRP.exe MPCvibedRPC.exe
+file MPRP-linux-amd64 MPCvibedRPC-linux-amd64
+file MPRP-linux-arm64 MPCvibedRPC-linux-arm64
+file MPRP-macos.zip MPCvibedRPC-macos.zip
+env MPRP_HOME MPCRPC_HOME
+env MPRP_BROWSER MPCRPC_BROWSER
+env MPRP_FOREGROUND MPCRPC_FOREGROUND
+env MPRP_UPDATE_API MPCRPC_UPDATE_API
diff --git a/tools/ci/live-flathub.sh b/tools/ci/live-flathub.sh
index 129e6a7..5e1a7b1 100755
--- a/tools/ci/live-flathub.sh
+++ b/tools/ci/live-flathub.sh
@@ -15,8 +15,8 @@ trap cleanup EXIT
live() {
local name="$1"; shift
echo "== $name ($(flatpak info "$app" | sed -n 's/^ *Version: //p'))"
- bash "$(dirname "$0")/must-pass.sh" TestLivePlayer env MPCRPC_LIVE_PLAYER="$name" MPCRPC_LIVE_TITLE="Sample Show" \
- MPCRPC_LIVE_MPV_PIPE=/nonexistent/none MPCRPC_LIVE_EVENTS=mpris ${1+"$@"} go test -count=1 -timeout 5m -run TestLivePlayer -v ./internal/engine
+ bash "$(dirname "$0")/must-pass.sh" TestLivePlayer env MPRP_LIVE_PLAYER="$name" MPRP_LIVE_TITLE="Sample Show" \
+ MPRP_LIVE_MPV_PIPE=/nonexistent/none MPRP_LIVE_EVENTS=mpris ${1+"$@"} go test -count=1 -timeout 5m -run TestLivePlayer -v ./internal/engine
}
stop_last() { flatpak kill "$app" 2> /dev/null || true; app=""; sleep 2; }
@@ -40,7 +40,7 @@ app=io.mpv.Mpv
xvfb-run -a flatpak run --filesystem="$videos:ro" --filesystem="$sockdir" "$app" --no-config --vo=null --ao=null \
--loop-file=inf --input-ipc-server="$sockdir/mpvsocket" "$video" > /dev/null 2>&1 &
wait_socket "$sockdir/mpvsocket"
-live mpv MPCRPC_LIVE_MPV_PIPE="$sockdir/mpvsocket" MPCRPC_LIVE_EVENTS=pipe
+live mpv MPRP_LIVE_MPV_PIPE="$sockdir/mpvsocket" MPRP_LIVE_EVENTS=pipe
stop_last
app=org.videolan.VLC
diff --git a/tools/ci/live-jellyfin.sh b/tools/ci/live-jellyfin.sh
index 5191e6c..49c82c1 100755
--- a/tools/ci/live-jellyfin.sh
+++ b/tools/ci/live-jellyfin.sh
@@ -105,9 +105,9 @@ call POST /Sessions/Playing "{\"ItemId\":\"$item\",\"MediaSourceId\":\"$item\",\
feed=$!
sleep 4
-export MPCRPC_LIVE_JELLYFIN_ADDRESS="$S" MPCRPC_LIVE_JELLYFIN_USER="$user" MPCRPC_LIVE_JELLYFIN_PASSWORD="$pass"
-export MPCRPC_LIVE_JELLYFIN_PRODUCT="$product" MPCRPC_LIVE_TITLE="Example Show"
+export MPRP_LIVE_JELLYFIN_ADDRESS="$S" MPRP_LIVE_JELLYFIN_USER="$user" MPRP_LIVE_JELLYFIN_PASSWORD="$pass"
+export MPRP_LIVE_JELLYFIN_PRODUCT="$product" MPRP_LIVE_TITLE="Example Show"
bash "$(dirname "$0")/must-pass.sh" TestLiveJellyfin go test -count=1 -timeout 3m -run TestLiveJellyfin -v ./internal/jellyfin
-MPCRPC_LIVE_PLAYER="$product" bash "$(dirname "$0")/must-pass.sh" TestLivePlayer go test -count=1 -timeout 3m -run TestLivePlayer -v ./internal/engine
+MPRP_LIVE_PLAYER="$product" bash "$(dirname "$0")/must-pass.sh" TestLivePlayer go test -count=1 -timeout 3m -run TestLivePlayer -v ./internal/engine
done_file
diff --git a/tools/ci/live-players.sh b/tools/ci/live-players.sh
index b61f89f..ba99991 100755
--- a/tools/ci/live-players.sh
+++ b/tools/ci/live-players.sh
@@ -18,7 +18,7 @@ trap cleanup EXIT
live() {
local name="$1"; shift
echo "== $name"
- bash "$(dirname "$0")/must-pass.sh" TestLivePlayer env MPCRPC_LIVE_PLAYER="$name" MPCRPC_LIVE_TITLE="Sample Show" ${1+"$@"} go test -count=1 -timeout 5m -run TestLivePlayer -v ./internal/engine
+ bash "$(dirname "$0")/must-pass.sh" TestLivePlayer env MPRP_LIVE_PLAYER="$name" MPRP_LIVE_TITLE="Sample Show" ${1+"$@"} go test -count=1 -timeout 5m -run TestLivePlayer -v ./internal/engine
}
stop_last() { kill "$pid" 2> /dev/null || true; wait "$pid" 2> /dev/null || true; pid=""; sleep 1; }
@@ -26,44 +26,44 @@ stop_last() { kill "$pid" 2> /dev/null || true; wait "$pid" 2> /dev/null || true
mpv --no-config --vo=null --ao=null --loop-file=inf --input-ipc-server="$tmp/mpvsocket" "$video" > /dev/null 2>&1 &
pid=$!
wait_socket "$tmp/mpvsocket"
-live mpv MPCRPC_LIVE_EVENTS=pipe # also: a pause shows at once, from mpv's event
+live mpv MPRP_LIVE_EVENTS=pipe # also: a pause shows at once, from mpv's event
stop_last
if [ "$os" = Linux ]; then
- none="MPCRPC_LIVE_MPV_PIPE=/nonexistent/none" # so that mpv can only be found through MPRIS below
+ none="MPRP_LIVE_MPV_PIPE=/nonexistent/none" # so that mpv can only be found through MPRIS below
cvlc --intf dummy --extraintf dbus --no-video --aout dummy --loop "$video" > /dev/null 2>&1 &
pid=$!
wait_bus org.mpris.MediaPlayer2.vlc
- live VLC "$none" MPCRPC_LIVE_EVENTS=mpris
+ live VLC "$none" MPRP_LIVE_EVENTS=mpris
stop_last
mpv --vo=null --ao=null --loop-file=inf "$video" > /dev/null 2>&1 & # the mpv-mpris script is loaded from /etc/mpv/scripts
pid=$!
wait_bus org.mpris.MediaPlayer2.mpv
- live mpv "$none" MPCRPC_LIVE_EVENTS=mpris
+ live mpv "$none" MPRP_LIVE_EVENTS=mpris
stop_last
xvfb-run -a celluloid --mpv-options="--ao=null --loop-file=inf" "$video" > /dev/null 2>&1 &
pid=$!
wait_bus "org.mpris.MediaPlayer2.*[Cc]elluloid" 240 # Celluloid's first start on a fresh runner once took over 20 s
- live Celluloid "$none" MPCRPC_LIVE_EVENTS=mpris
+ live Celluloid "$none" MPRP_LIVE_EVENTS=mpris
stop_last
pkill -x celluloid || true # xvfb-run does not pass the signal on
else
echo "== IINA: the real program sets it up"
- go build -o "$work/MPCvibedRPC" ./cmd/mpcvibedrpc
- export MPCRPC_HOME="$work/home" MPCRPC_BROWSER=none MPCRPC_FOREGROUND=1
- mkdir -p "$MPCRPC_HOME"
- printf '%s' '{"app":{"openWindow":false,"startPresence":false,"checkUpdates":false,"welcomeSeen":true},"port":1}' > "$MPCRPC_HOME/config.json"
+ go build -o "$work/MPRP" ./cmd/mprp
+ export MPRP_HOME="$work/home" MPRP_BROWSER=none MPRP_FOREGROUND=1
+ mkdir -p "$MPRP_HOME"
+ printf '%s' '{"app":{"openWindow":false,"startPresence":false,"checkUpdates":false,"welcomeSeen":true},"port":1}' > "$MPRP_HOME/config.json"
app="" port="" token=""
# every wait below has a limit: a CI machine has nobody to answer a dialog
start_app() {
- "$work/MPCvibedRPC" &
+ "$work/MPRP" &
app=$!
- for _ in $(seq 1 60); do [ -s "$MPCRPC_HOME/ipc.json" ] && break; sleep 0.25; done
- [ -s "$MPCRPC_HOME/ipc.json" ] || { echo "the program did not start"; exit 1; }
- port="$(jq -r .port "$MPCRPC_HOME/ipc.json")"; token="$(jq -r .token "$MPCRPC_HOME/ipc.json")"
+ for _ in $(seq 1 60); do [ -s "$MPRP_HOME/ipc.json" ] && break; sleep 0.25; done
+ [ -s "$MPRP_HOME/ipc.json" ] || { echo "the program did not start"; exit 1; }
+ port="$(jq -r .port "$MPRP_HOME/ipc.json")"; token="$(jq -r .token "$MPRP_HOME/ipc.json")"
}
api() { curl -sf -m 60 -H "X-Token: $token" -H 'Content-Type: application/json' -X POST --data "$2" "http://127.0.0.1:$port/api/$1"; }
stop_app() {
@@ -73,18 +73,18 @@ else
}
echo "-- first setup"
start_app
- api mpc-web '{"closeMpc":false}' | tee "$work/setup.json"
+ api player-setup '{"closePlayers":false}' | tee "$work/setup.json"
echo
stop_app
defaults read com.colliderli.iina enableAdvancedSettings | grep -qx 1 || { echo "IINA's advanced settings are off"; exit 1; }
defaults read com.colliderli.iina userOptions | grep -q "input-ipc-server" || { echo "IINA has no input-ipc-server"; exit 1; }
echo "-- second setup keeps what is there"
start_app
- api mpc-web '{"closeMpc":false}' > "$work/setup2.json" || true
+ api player-setup '{"closePlayers":false}' > "$work/setup2.json" || true
cat "$work/setup2.json"; echo
stop_app
grep -q "IINA was already set up" "$work/setup2.json" || { echo "the second setup should find IINA set up"; exit 1; }
- unset MPCRPC_HOME MPCRPC_BROWSER MPCRPC_FOREGROUND
+ unset MPRP_HOME MPRP_BROWSER MPRP_FOREGROUND
echo "-- opening IINA"
# by its path, not its name: a freshly installed app is not always registered with LaunchServices yet ("Unable to
@@ -92,7 +92,7 @@ else
open -a /Applications/IINA.app "$video" &
pid=$!
wait_socket "$tmp/iina-mpvsocket" || { pgrep -lf IINA || echo "IINA is not running"; ls -la "$tmp"; exit 1; }
- live IINA MPCRPC_LIVE_EVENTS=pipe
+ live IINA MPRP_LIVE_EVENTS=pipe
pkill -x IINA || true # not AppleScript: macOS would ask whether this may control IINA, and nobody can answer
fi
echo "live player tests passed"
diff --git a/tools/ci/live-plex.sh b/tools/ci/live-plex.sh
index 51397b9..9a1fa17 100755
--- a/tools/ci/live-plex.sh
+++ b/tools/ci/live-plex.sh
@@ -48,7 +48,7 @@ echo "sample episode: $rk"
) &
feed=$!
-MPCRPC_LIVE_PLAYER=Plex MPCRPC_LIVE_TITLE="Sample Show - S01E02" MPCRPC_LIVE_PLEX_ADDRESS="$P" \
+MPRP_LIVE_PLAYER=Plex MPRP_LIVE_TITLE="Sample Show - S01E02" MPRP_LIVE_PLEX_ADDRESS="$P" \
bash "$(dirname "$0")/must-pass.sh" TestLivePlayer go test -count=1 -timeout 3m -run TestLivePlayer -v ./internal/engine
done_file
diff --git a/tools/ci/live-windows.sh b/tools/ci/live-windows.sh
index be303ce..604c5b2 100755
--- a/tools/ci/live-windows.sh
+++ b/tools/ci/live-windows.sh
@@ -7,11 +7,30 @@ here="$(cd "$(dirname "$0")" && pwd)"
work="$RUNNER_TEMP/live-windows"
mkdir -p "$work"
+# choco_install CHECK PACKAGE... [OPTION...]: choco install, tried up to three times, 30 seconds apart (a download
+# from Chocolatey's mirrors fails now and then, for example with a TLS error for Kodi). CHECK is a shell test that must
+# hold afterwards: choco has answered success with the program missing, so its exit code alone is not trusted.
+choco_install() {
+ local check="$1" try; shift
+ for try in 1 2 3; do
+ if choco install -y --no-progress "$@" >> "$work/choco.log" 2>&1 && eval "$check"; then return 0; fi
+ echo "choco install $* did not leave what it should ($check), try $try of 3"
+ [ "$try" = 3 ] || sleep 30
+ done
+ grep -iE "install|fail|error|warn|not " "$work/choco.log" | grep -viE "proceeds|community|chocolatey.org/compare|awesome" | tail -60
+ return 1
+}
+
+# ffmpeg: Chocolatey puts its shim in its bin folder, which this shell may not have on PATH yet
+export PATH="$PATH:/c/ProgramData/chocolatey/bin"
+pot_exe() { ls /c/Program\ Files/DAUM/PotPlayer/PotPlayerMini64.exe /c/Program\ Files*/DAUM/PotPlayer/PotPlayerMini*.exe 2>/dev/null | head -1; }
+
echo "::group::install"
-choco install -y --no-progress kodi ffmpeg > "$work/choco.log" || { cat "$work/choco.log"; exit 1; }
+: > "$work/choco.log"
+choco_install 'command -v ffmpeg >/dev/null && ls /c/Program\ Files*/Kodi/kodi.exe >/dev/null 2>&1' kodi ffmpeg
# PotPlayer replaces the installer at its fixed download address, so the package's recorded checksum goes stale; on
# this throwaway runner it is installed without that check.
-choco install -y --no-progress --ignore-checksums potplayer >> "$work/choco.log" || { cat "$work/choco.log"; exit 1; }
+choco_install '[ -n "$(pot_exe)" ]' potplayer --ignore-checksums
tail -5 "$work/choco.log"
echo "::endgroup::"
@@ -21,17 +40,17 @@ win_video="$(cygpath -w "$video")"
live() { # live NAME [VAR=value ...]: the live engine test, which must really run and pass
local name="$1"; shift
- env MPCRPC_LIVE_PLAYER="$name" MPCRPC_LIVE_TITLE="Sample Movie" "$@" \
+ env MPRP_LIVE_PLAYER="$name" MPRP_LIVE_TITLE="Sample Movie" "$@" \
"$here/must-pass.sh" TestLivePlayer go test -count=1 -v -run TestLivePlayer ./internal/engine
}
echo "::group::PotPlayer"
-pot="$(ls /c/Program\ Files/DAUM/PotPlayer/PotPlayerMini64.exe /c/Program\ Files*/DAUM/PotPlayer/PotPlayerMini*.exe 2>/dev/null | head -1 || true)"
+pot="$(pot_exe || true)"
[ -n "$pot" ] || { echo "PotPlayer was not installed where expected"; ls "/c/Program Files" "/c/Program Files (x86)"; exit 1; }
"$pot" "$win_video" &
sleep 10
live PotPlayer
-MPCRPC_LIVE_POTPLAYER=1 "$here/must-pass.sh" TestLivePotPlayer go test -count=1 -v -run TestLivePotPlayer ./internal/potplayer
+MPRP_LIVE_POTPLAYER=1 "$here/must-pass.sh" TestLivePotPlayer go test -count=1 -v -run TestLivePotPlayer ./internal/potplayer
taskkill //F //IM "$(basename "$pot")" > /dev/null || true
echo "::endgroup::"
@@ -60,7 +79,7 @@ file_json="$(printf '%s' "$win_video" | sed 's/\\/\\\\/g')"
rpc "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"Player.Open\",\"params\":{\"item\":{\"file\":\"$file_json\"}}}"
echo
sleep 8
-live Kodi MPCRPC_LIVE_KODI_PASSWORD=ci-secret MPCRPC_LIVE_EVENTS=kodi # also: a pause shows at once, from Kodi's notification
+live Kodi MPRP_LIVE_KODI_PASSWORD=ci-secret MPRP_LIVE_EVENTS=kodi # also: a pause shows at once, from Kodi's notification
taskkill //F //IM kodi.exe > /dev/null || true
echo "::endgroup::"
diff --git a/tools/ci/package-macos.sh b/tools/ci/package-macos.sh
index 56f047f..bfca5d1 100755
--- a/tools/ci/package-macos.sh
+++ b/tools/ci/package-macos.sh
@@ -1,10 +1,10 @@
#!/usr/bin/env bash
-# Builds MPCvibedRPC.app, one program for Apple silicon and Intel Macs, and zips it as OUTDIR/MPCvibedRPC-macos.zip.
+# Builds MPRP.app, one program for Apple silicon and Intel Macs, and zips it as OUTDIR/MPRP-macos.zip.
# Runs on macOS (it needs lipo, codesign and ditto). usage: package-macos.sh VERSION OUTDIR
set -euo pipefail
version="$1"; out="$2"
work="$(mktemp -d)"
-app="$work/MPCvibedRPC.app"
+app="$work/MPRP.app"
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" "$out"
out="$(cd "$out" && pwd)" # the zip is written from inside $work
@@ -12,12 +12,12 @@ out="$(cd "$out" && pwd)" # the zip is written from inside $work
for arch in arm64 amd64; do
carch="$arch"; [ "$arch" = amd64 ] && carch=x86_64
CGO_ENABLED=1 GOOS=darwin GOARCH="$arch" CC="clang -arch $carch" MACOSX_DEPLOYMENT_TARGET=13.0 \
- go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$version" -o "$work/MPCvibedRPC-$arch" ./cmd/mpcvibedrpc
+ go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$version" -o "$work/MPRP-$arch" ./cmd/mprp
# the Cocoa part must be in both: a build without it would quietly fall back to the browser and no menu bar icon
- otool -L "$work/MPCvibedRPC-$arch" | grep -q WebKit.framework || { echo "the $arch build lacks the macOS app code"; exit 1; }
+ otool -L "$work/MPRP-$arch" | grep -q WebKit.framework || { echo "the $arch build lacks the macOS app code"; exit 1; }
done
-lipo -create -output "$app/Contents/MacOS/MPCvibedRPC" "$work/MPCvibedRPC-arm64" "$work/MPCvibedRPC-amd64"
-go run ./tools/mkico -icns "$app/Contents/Resources/MPCvibedRPC.icns"
+lipo -create -output "$app/Contents/MacOS/MPRP" "$work/MPRP-arm64" "$work/MPRP-amd64"
+go run ./tools/mkico -icns "$app/Contents/Resources/MPRP.icns"
# LSUIElement: no Dock icon or menu bar of its own (the program has no windows besides the settings page).
cat > "$app/Contents/Info.plist" < "$app/Contents/Info.plist" <CFBundleDevelopmentRegion
enCFBundleDisplayName
- MPCvibedRPC
+ MPRPCFBundleExecutable
- MPCvibedRPC
+ MPRPCFBundleIconFile
- MPCvibedRPC
+ MPRPCFBundleIdentifier
- io.github.cptpakundo.mpcvibedrpc
+ io.github.cptpakundo.mprpCFBundleInfoDictionaryVersion6.0CFBundleName
- MPCvibedRPC
+ MPRPCFBundlePackageTypeAPPLCFBundleShortVersionString
@@ -50,7 +50,7 @@ cat > "$app/Contents/Info.plist" <LSUIElement
NSLocalNetworkUsageDescription
- MPCvibedRPC reads what plays on the Plex, Jellyfin, Emby or Kodi server you set up on your network, to show it on Discord.
+ MPRP reads what plays on the Plex, Jellyfin, Emby or Kodi server you set up on your network, to show it on Discord.NSHumanReadableCopyrightMIT License. Made with AI (vibe coded).
@@ -62,7 +62,7 @@ plutil -lint "$app/Contents/Info.plist"
plutil -extract NSLocalNetworkUsageDescription raw "$app/Contents/Info.plist" > /dev/null
[ "$(plutil -extract LSMinimumSystemVersion raw "$app/Contents/Info.plist")" = 13.0 ] || { echo "LSMinimumSystemVersion is not 13.0"; exit 1; }
for arch in arm64 amd64; do
- minos="$(otool -l "$work/MPCvibedRPC-$arch" | awk '/LC_BUILD_VERSION/ { b = 1 } b && $1 == "minos" { print $2; exit }')"
+ minos="$(otool -l "$work/MPRP-$arch" | awk '/LC_BUILD_VERSION/ { b = 1 } b && $1 == "minos" { print $2; exit }')"
echo "$arch build: minimum macOS $minos"
[ -n "$minos" ] && [ "${minos%%.*}" -le 13 ] || { echo "the $arch build needs macOS $minos, above the app's 13.0"; exit 1; }
done
@@ -71,8 +71,8 @@ done
# macOS asks the user to confirm the first start (see the README).
codesign --force --sign - --timestamp=none "$app"
codesign --verify --strict --verbose=2 "$app"
-lipo -archs "$app/Contents/MacOS/MPCvibedRPC"
+lipo -archs "$app/Contents/MacOS/MPRP"
-rm -f "$out/MPCvibedRPC-macos.zip"
-(cd "$work" && ditto -c -k --keepParent MPCvibedRPC.app "$out/MPCvibedRPC-macos.zip")
-ls -l "$out/MPCvibedRPC-macos.zip"
+rm -f "$out/MPRP-macos.zip"
+(cd "$work" && ditto -c -k --keepParent MPRP.app "$out/MPRP-macos.zip")
+ls -l "$out/MPRP-macos.zip"
diff --git a/tools/ci/reproduce.sh b/tools/ci/reproduce.sh
index 418855e..5c0352a 100755
--- a/tools/ci/reproduce.sh
+++ b/tools/ci/reproduce.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Rebuilds the release files the way the release builds them, so a release can be checked byte for byte.
-# reproduce.sh builds MPCvibedRPC.exe, MPCvibedRPC-linux-amd64 and -arm64 into out-dir
+# reproduce.sh builds MPRP.exe, MPRP-linux-amd64 and -arm64 into out-dir
# reproduce.sh compare fails unless both files are the same
# reproduce.sh hash fails unless the file has that SHA-256
# reproduce.sh sums prints exe=, linux_amd64= and linux_arm64= with the SHA-256 of the files built there
@@ -35,9 +35,9 @@ case "${1:-}" in
fi
;;
sums)
- echo "exe=$(sha "$2/MPCvibedRPC.exe")"
- echo "linux_amd64=$(sha "$2/MPCvibedRPC-linux-amd64")"
- echo "linux_arm64=$(sha "$2/MPCvibedRPC-linux-arm64")"
+ echo "exe=$(sha "$2/MPRP.exe")"
+ echo "linux_amd64=$(sha "$2/MPRP-linux-amd64")"
+ echo "linux_arm64=$(sha "$2/MPRP-linux-arm64")"
;;
same)
echo "$2: release $3, rebuilt $4"
@@ -50,12 +50,12 @@ case "${1:-}" in
v="$1"; out="$2"
mkdir -p "$out"
export CGO_ENABLED=0
- syso=cmd/mpcvibedrpc/rsrc_windows_amd64.syso
+ syso=cmd/mprp/rsrc_windows_amd64.syso
go run ./tools/mkrsrc -version "$v" -out "$syso"
- GOOS=windows GOARCH=amd64 go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$v" -o "$out/MPCvibedRPC.exe" ./cmd/mpcvibedrpc
+ GOOS=windows GOARCH=amd64 go build -trimpath -buildvcs=false -ldflags "-H=windowsgui -s -w -X main.version=$v" -o "$out/MPRP.exe" ./cmd/mprp
rm -f "$syso"
for arch in amd64 arm64; do
- GOOS=linux GOARCH=$arch go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$v" -o "$out/MPCvibedRPC-linux-$arch" ./cmd/mpcvibedrpc
+ GOOS=linux GOARCH=$arch go build -trimpath -buildvcs=false -ldflags "-s -w -X main.version=$v" -o "$out/MPRP-linux-$arch" ./cmd/mprp
done
ls -l "$out"
;;
diff --git a/tools/ci/smoke-unix.sh b/tools/ci/smoke-unix.sh
index a40aab2..640a274 100755
--- a/tools/ci/smoke-unix.sh
+++ b/tools/ci/smoke-unix.sh
@@ -7,21 +7,21 @@ set -euo pipefail
exe="$1"; version="$2"; app="${3:-}"
os="$(uname -s)"
work="$(mktemp -d)"
-export MPCRPC_HOME="$work/home" MPCRPC_BROWSER=none MPCRPC_FOREGROUND=1
+export MPRP_HOME="$work/home" MPRP_BROWSER=none MPRP_FOREGROUND=1
export XDG_CONFIG_HOME="$work/config" # mpv.conf and the Linux autostart entry are written here, not in the real home
-mkdir -p "$MPCRPC_HOME" "$XDG_CONFIG_HOME/mpv" # an mpv folder: mpv counts as present for the setup
+mkdir -p "$MPRP_HOME" "$XDG_CONFIG_HOME/mpv" # an mpv folder: mpv counts as present for the setup
quiet='{"app":{"openWindow":false,"startPresence":false,"checkUpdates":false,"welcomeSeen":true},"port":1}'
-printf '%s' "$quiet" > "$MPCRPC_HOME/config.json"
+printf '%s' "$quiet" > "$MPRP_HOME/config.json"
-fail() { echo "::error title=smoke-unix::$*"; [ -f "$MPCRPC_HOME/mpcvibedrpc.log" ] && tail -n 40 "$MPCRPC_HOME/mpcvibedrpc.log"; exit 1; }
+fail() { echo "::error title=smoke-unix::$*"; [ -f "$MPRP_HOME/mprp.log" ] && tail -n 40 "$MPRP_HOME/mprp.log"; exit 1; }
wait_for() { # wait_for "what" command...
local what="$1"; shift
for _ in $(seq 1 60); do "$@" && return 0; sleep 0.25; done
fail "timed out waiting for $what"
}
-have_ipc() { [ -s "$MPCRPC_HOME/ipc.json" ] && curl -sf "http://127.0.0.1:$(jq -r .port "$MPCRPC_HOME/ipc.json")/api/ping" > /dev/null; }
+have_ipc() { [ -s "$MPRP_HOME/ipc.json" ] && curl -sf "http://127.0.0.1:$(jq -r .port "$MPRP_HOME/ipc.json")/api/ping" > /dev/null; }
port=""; token=""
-read_ipc() { port="$(jq -r .port "$MPCRPC_HOME/ipc.json")"; token="$(jq -r .token "$MPCRPC_HOME/ipc.json")"; }
+read_ipc() { port="$(jq -r .port "$MPRP_HOME/ipc.json")"; token="$(jq -r .token "$MPRP_HOME/ipc.json")"; }
get() { curl -sf -m 60 -H "X-Token: $token" "http://127.0.0.1:$port/api/$1"; }
post() { curl -sf -m 60 -H "X-Token: $token" -H 'Content-Type: application/json' -X POST --data "${2:-"{}"}" "http://127.0.0.1:$port/api/$1"; }
gone() { ! kill -0 "$1" 2> /dev/null; }
@@ -47,13 +47,13 @@ fi
echo "state ok ($want_os)"
echo "== run at login"
-if [ "$want_os" = darwin ]; then item_dir="$HOME/Library/LaunchAgents"; item_glob="io.github.cptpakundo.mpcvibedrpc-*.plist"
-else item_dir="$XDG_CONFIG_HOME/autostart"; item_glob="mpcvibedrpc-*.desktop"; fi
+if [ "$want_os" = darwin ]; then item_dir="$HOME/Library/LaunchAgents"; item_glob="io.github.cptpakundo.mprp-*.plist"
+else item_dir="$XDG_CONFIG_HOME/autostart"; item_glob="mprp-*.desktop"; fi
[ "$(post save '{"app":{"autoStart":true}}' | jq -r .autoStart)" = true ] || fail "autoStart did not switch on"
item="$(find "$item_dir" -name "$item_glob" 2> /dev/null | head -n 1)"
[ -n "$item" ] || fail "no login item in $item_dir"
grep -qF -- "--background" "$item" || fail "the login item does not start in the background"
-grep -qF -- "$MPCRPC_HOME" "$item" || fail "the login item does not keep the data folder"
+grep -qF -- "$MPRP_HOME" "$item" || fail "the login item does not keep the data folder"
if [ "$want_os" = darwin ]; then plutil -lint "$item"
elif command -v desktop-file-validate > /dev/null; then desktop-file-validate "$item"
else echo "::warning title=smoke test::desktop-file-validate is not installed here, so the login item was not validated"; fi
@@ -63,19 +63,19 @@ cat "$item"
echo "login item ok"
echo "== player setup"
-r="$(post mpc-web '{"closeMpc":false}')"
+r="$(post player-setup '{"closePlayers":false}')"
echo "$r"
if [ "$want_os" = darwin ] && [ ! -d /Applications/IINA.app ]; then
! grep -q IINA <<< "$r" || fail "IINA is not installed here, yet the setup touched it: $r"
! defaults read com.colliderli.iina userOptions > /dev/null 2>&1 || fail "settings were written for an IINA that is not installed"
fi
grep -qE "^input-ipc-server=/.+/mpvsocket$" "$XDG_CONFIG_HOME/mpv/mpv.conf" || fail "mpv.conf has no absolute input-ipc-server: $(cat "$XDG_CONFIG_HOME/mpv/mpv.conf")"
-r="$(post mpc-web '{"closeMpc":false}')"
+r="$(post player-setup '{"closePlayers":false}')"
jq -e '.message | contains("already set up")' <<< "$r" > /dev/null || fail "a second setup should find mpv set up: $r"
echo "== diagnostics"
diag="$(get diagnostics | jq -r .text)"
-grep -q "MPCvibedRPC diagnostics" <<< "$diag" || fail "diagnostics"
+grep -q "MPRP diagnostics" <<< "$diag" || fail "diagnostics"
! grep -qF "$work" <<< "$diag" || fail "diagnostics leak a path"
grep -m1 -i "system" <<< "$diag" || true
@@ -90,20 +90,20 @@ echo "== presence on and off (nothing plays: Discord stays on standby)"
echo "== quit"
post quit > /dev/null
wait_for "the program to quit" gone "$pid"
-[ ! -e "$MPCRPC_HOME/ipc.json" ] || fail "ipc.json left behind"
+[ ! -e "$MPRP_HOME/ipc.json" ] || fail "ipc.json left behind"
if [ -n "$app" ]; then
echo "== macOS: open the app like the Finder does"
- unset MPCRPC_FOREGROUND MPCRPC_BROWSER # the app's own window this time
+ unset MPRP_FOREGROUND MPRP_BROWSER # the app's own window this time
swift tools/ci/windows.swift > /dev/null # compiled once, so the checks below are quick
windows() { swift tools/ci/windows.swift | awk -F'\t' -v p="$1" -v l="$2" '$1 == p && $2 == l' | wc -l | tr -d ' '; }
icons() { swift tools/ci/windows.swift | awk -F' ' '$2 == 25' | wc -l | tr -d ' '; } # menu bar icons, whoever draws them (macOS 26: Control Center)
shot="${SCREENSHOT:-$work/screen.png}"
icons_before="$(icons)"
- open --env "MPCRPC_HOME=$MPCRPC_HOME" "$app"
+ open --env "MPRP_HOME=$MPRP_HOME" "$app"
wait_for "the app to answer" have_ipc
read_ipc
- server="$(jq -r .pid "$MPCRPC_HOME/ipc.json")"
+ server="$(jq -r .pid "$MPRP_HOME/ipc.json")"
sleep 5
kill -0 "$server" || fail "the program did not keep running after the launcher left"
ps -o args= -p "$server" | grep -q -- "--serve" || fail "the running copy should be the --serve one"
@@ -118,17 +118,17 @@ if [ -n "$app" ]; then
echo "== macOS: the settings window"
open "$app" # opening the app again: macOS tells the running app, which shows its window
sleep 5
- [ "$(jq -r .pid "$MPCRPC_HOME/ipc.json")" = "$server" ] || fail "opening the app again started another copy"
- n="$(pgrep -f "MPCvibedRPC.app/Contents/MacOS/MPCvibedRPC" | wc -l | tr -d ' ')"
+ [ "$(jq -r .pid "$MPRP_HOME/ipc.json")" = "$server" ] || fail "opening the app again started another copy"
+ n="$(pgrep -f "MPRP.app/Contents/MacOS/MPRP" | wc -l | tr -d ' ')"
[ "$n" = 1 ] || fail "$n copies are running"
[ "$(windows "$server" 0)" = 1 ] || { swift tools/ci/windows.swift; fail "the app should show exactly one window of its own"; }
- ! pgrep -f -- "--user-data-dir=$MPCRPC_HOME/window" > /dev/null || fail "a browser was started for the window"
+ ! pgrep -f -- "--user-data-dir=$MPRP_HOME/window" > /dev/null || fail "a browser was started for the window"
post open > /dev/null # once more: the same window comes forward, no second one
sleep 2
[ "$(windows "$server" 0)" = 1 ] || fail "a second window was opened"
if screencapture -x "$shot" 2> /dev/null; then echo "screenshot: $shot"; fi
echo "window ok"
- grep -c "starting" "$MPCRPC_HOME/mpcvibedrpc.log" || true
+ grep -c "starting" "$MPRP_HOME/mprp.log" || true
post quit > /dev/null
wait_for "the app to quit" gone "$server"
fi
diff --git a/tools/ci/smoke.ps1 b/tools/ci/smoke.ps1
index 017b025..d768805 100644
--- a/tools/ci/smoke.ps1
+++ b/tools/ci/smoke.ps1
@@ -12,13 +12,13 @@ if ($env:GITHUB_ACTIONS -ne 'true') { Write-Host 'smoke.ps1 only runs on a GitHu
$work = Join-Path $env:RUNNER_TEMP ('smoke-' + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Path $work | Out-Null
$home_ = Join-Path $work 'home'; New-Item -ItemType Directory -Path $home_ | Out-Null
-$app = Join-Path $work 'MPCvibedRPC.exe'
+$app = Join-Path $work 'MPRP.exe'
Copy-Item $Exe $app
-$env:MPCRPC_HOME = $home_
+$env:MPRP_HOME = $home_
# A copy with its own data folder gets its own run-at-login value (see winsys/autostart.go), so this test can never touch an installed program's.
-$runName = 'MPCvibedRPC-' + ([BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($home_.TrimEnd('\','/').ToLower()))).Replace('-','').Substring(0,8).ToLower())
+$runName = 'MPRP-' + ([BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($home_.TrimEnd('\','/').ToLower()))).Replace('-','').Substring(0,8).ToLower())
$port = 13591
-$env:MPCRPC_UPDATE_API = "http://127.0.0.1:$port"
+$env:MPRP_UPDATE_API = "http://127.0.0.1:$port"
$stateFile = Join-Path $work 'state.txt'; Set-Content $stateFile '2'
$discordLog = Join-Path $work 'discord.log'
$failures = New-Object System.Collections.ArrayList
@@ -39,7 +39,7 @@ function Api([string]$method, [string]$name, $body = $null) {
if ($method -eq 'Post') { $args_.Body = if ($null -eq $body) { '{}' } else { $body | ConvertTo-Json -Depth 6 }; $args_.ContentType = 'application/json' }
Invoke-RestMethod @args_
}
-function Dump { Write-Host '--- app log ---'; Get-Content (Join-Path $home_ 'mpcvibedrpc.log') -ErrorAction SilentlyContinue | Write-Host; Write-Host '--- fake discord log ---'; Get-Content $discordLog -ErrorAction SilentlyContinue | Write-Host }
+function Dump { Write-Host '--- app log ---'; Get-Content (Join-Path $home_ 'mprp.log') -ErrorAction SilentlyContinue | Write-Host; Write-Host '--- fake discord log ---'; Get-Content $discordLog -ErrorAction SilentlyContinue | Write-Host }
Add-Type -Namespace W -Name U -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] public static extern System.IntPtr FindWindow(string c, string t);
@@ -47,7 +47,7 @@ Add-Type -Namespace W -Name U -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("shcore.dll")] public static extern int GetProcessDpiAwareness(System.IntPtr p, out int a);
'@
function StartFakeDiscord { Start-Process pwsh -PassThru -WindowStyle Hidden -ArgumentList '-NoProfile', '-File', (Join-Path $PSScriptRoot 'fake-discord.ps1'), '-Log', $discordLog }
-function AppLog { Get-Content (Join-Path $home_ 'mpcvibedrpc.log') -Raw -ErrorAction SilentlyContinue }
+function AppLog { Get-Content (Join-Path $home_ 'mprp.log') -Raw -ErrorAction SilentlyContinue }
try {
# fakes
@@ -63,7 +63,7 @@ try {
# the program carries its version details and icon
$vi = (Get-Item $app).VersionInfo
- Check ($vi.ProductVersion -eq $Version -and $vi.ProductName -eq 'MPCvibedRPC' -and $vi.FileDescription -like 'MPCvibedRPC*') "exe carries version details ($($vi.ProductVersion))"
+ Check ($vi.ProductVersion -eq $Version -and $vi.ProductName -eq 'MPRP' -and $vi.FileDescription -like 'MPRP*') "exe carries version details ($($vi.ProductVersion))"
Add-Type -AssemblyName System.Drawing
$ico = [System.Drawing.Icon]::ExtractAssociatedIcon($app)
$bmp = $ico.ToBitmap(); $px = @(); foreach ($pt in @(@(8, 8), @(16, 16), @(24, 24), @(8, 24))) { $px += $bmp.GetPixel($pt[0], $pt[1]).ToArgb() }
@@ -76,7 +76,7 @@ try {
Check (WaitFor { $null -ne (Ipc) } 20 'ipc.json') 'program started and published ipc.json'
$i = Ipc
$ping = Invoke-RestMethod "http://127.0.0.1:$($i.port)/api/ping"
- Check ($ping.app -eq 'MPCvibedRPC' -and $ping.version -eq $Version) 'ping answers with the version'
+ Check ($ping.app -eq 'MPRP' -and $ping.version -eq $Version) 'ping answers with the version'
$aware = -1; [void][W.U]::GetProcessDpiAwareness($p.Handle, [ref]$aware)
Check ($aware -eq 2) "the program is per-monitor DPI-aware (awareness $aware)"
$state = Api 'Get' 'state'
@@ -87,14 +87,14 @@ try {
# presence reaches "Discord" through the real named pipe
Check (WaitFor { (Get-Content $discordLog -Raw) -match 'Sample Movie' } 30 'activity in fake discord') 'presence frame with the title arrives over the named pipe'
$s = Api 'Get' 'status'
- Check ($s.running -and $s.discord -eq 'connected' -and $s.mpc) 'status: connected, MPC-HC seen'
+ Check ($s.running -and $s.discord -eq 'connected' -and $s.playerAnswers) 'status: connected, MPC-HC seen'
Check ((Get-Content $discordLog -Raw) -match '"type":3') 'activity uses the Watching type'
Check ((AppLog) -notmatch 'resting') 'presence does not rest while Discord runs'
# Discord closes: presence rests (no window is open); Discord starts again: presence comes back by itself
$fakeDiscord.Kill(); [void]$fakeDiscord.WaitForExit(10000)
Check (WaitFor { (AppLog) -match 'Discord is not running: resting' } 20 'rest') 'presence rests once Discord is gone'
- Check (-not (Api 'Get' 'status').mpc) 'a resting program asks no player'
+ Check (-not (Api 'Get' 'status').playerAnswers) 'a resting program asks no player'
$shownBefore = ([regex]::Matches((Get-Content $discordLog -Raw), 'Sample Movie')).Count
$fakeDiscord = StartFakeDiscord
[void]$procs.Add($fakeDiscord)
@@ -108,7 +108,7 @@ try {
Set-Content $stateFile '2'
# tray: its hidden window exists and understands the menu commands (1 open, 2 toggle, 3 quit)
- $hwnd = [W.U]::FindWindow('MPCvibedRPC.Tray', [NullString]::Value)
+ $hwnd = [W.U]::FindWindow('MPRP.Tray', [NullString]::Value)
Check ($hwnd -ne [IntPtr]::Zero) 'tray window exists'
[void][W.U]::PostMessage($hwnd, 0x0111, [UIntPtr]2, [IntPtr]::Zero)
Check (WaitFor { -not (Api 'Get' 'status').running } 10 'toggle off') 'tray menu "Stop showing on Discord" works'
@@ -116,15 +116,15 @@ try {
Check (WaitFor { (Api 'Get' 'status').running } 10 'toggle on') 'tray menu "Show on Discord" works'
# run at login
- $plainBefore = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v MPCvibedRPC 2>&1) -join "`n"
+ $plainBefore = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v MPRP 2>&1) -join "`n"
Api 'Post' 'save' @{ app = @{ autoStart = $true } } | Out-Null
$reg = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v $runName 2>&1) -join "`n"
- Check ($reg -match 'MPCvibedRPC\.exe" --background --home "') 'autostart writes the Run entry (under the name for this data folder, passing that folder on)'
+ Check ($reg -match 'MPRP\.exe" --background --home "') 'autostart writes the Run entry (under the name for this data folder, passing that folder on)'
Check ((Api 'Get' 'state').autoStart -eq $true) 'state reports autostart on'
Api 'Post' 'save' @{ app = @{ autoStart = $false } } | Out-Null
$reg = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v $runName 2>&1) -join "`n"
- Check ($reg -notmatch 'MPCvibedRPC\.exe') 'autostart removes the Run entry'
- $plain = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v MPCvibedRPC 2>&1) -join "`n"
+ Check ($reg -notmatch 'MPRP\.exe') 'autostart removes the Run entry'
+ $plain = (reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v MPRP 2>&1) -join "`n"
# compared without regard to whitespace: PowerShell orders the lines of a failed lookup differently from run to run
Check (($plain -replace '\s+',' ').Trim() -eq ($plainBefore -replace '\s+',' ').Trim()) ("the plain (installed program) Run value was never touched (before=[$($plainBefore -replace '\s+',' ')] after=[$($plain -replace '\s+',' ')])")
@@ -132,27 +132,27 @@ try {
# VLC is not installed either: an empty VLC settings folder stands in for it (only when there is none; removed after).
$vlcDir = Join-Path $env:APPDATA 'vlc'; $vlcMade = $false
if (-not (Test-Path $vlcDir)) { New-Item -ItemType Directory -Path $vlcDir | Out-Null; $vlcMade = $true }
- $mw = Api 'Post' 'mpc-web' @{ closeMpc = $false }
+ $mw = Api 'Post' 'player-setup' @{ closePlayers = $false }
if ($vlcMade) {
$rc = Get-Content (Join-Path $vlcDir 'vlcrc') -Raw -ErrorAction SilentlyContinue
- Check ($rc -match '(?m)^extraintf=http\r?$') 'mpc-web switched VLC''s web interface on (vlcrc)'
- Check ($rc -match '(?m)^http-host=127\.0\.0\.1\r?$') 'mpc-web made VLC''s web interface answer this PC only'
+ Check ($rc -match '(?m)^extraintf=http\r?$') 'player-setup switched VLC''s web interface on (vlcrc)'
+ Check ($rc -match '(?m)^http-host=127\.0\.0\.1\r?$') 'player-setup made VLC''s web interface answer this PC only'
$vlcPw = [regex]::Match([string]$rc, '(?m)^http-password=([0-9a-f]+)\r?$').Groups[1].Value
- Check ($vlcPw.Length -eq 24) 'mpc-web gave VLC a password'
+ Check ($vlcPw.Length -eq 24) 'player-setup gave VLC a password'
$vals = (Api 'Get' 'state').values
Check ($vals.vlcPassword -eq $vlcPw -and $vals.vlcPort -eq 8080) 'the settings took VLC''s password and port over'
- Check ($mw.settingsChanged -eq $true -and $mw.message -match 'VLC web interface switched on') 'mpc-web says so'
+ Check ($mw.settingsChanged -eq $true -and $mw.message -match 'VLC web interface switched on') 'player-setup says so'
Check (-not ($mw.PSObject.Properties.Name -contains 'vlcPassword')) 'the password is not in the answer'
Remove-Item -Recurse -Force $vlcDir
}
- Check ($mw.ok -eq $true) 'mpc-web reports success'
+ Check ($mw.ok -eq $true) 'player-setup reports success'
$reg = (reg query 'HKCU\Software\MPC-HC\MPC-HC\Settings' /v EnableWebServer 2>&1) -join "`n"
- Check ($reg -match '0x1') 'mpc-web set EnableWebServer=1'
+ Check ($reg -match '0x1') 'player-setup set EnableWebServer=1'
$reg = (reg query 'HKCU\Software\MPC-HC\MPC-HC\Settings' /v WebServerPort 2>&1) -join "`n"
- Check ($reg -match ('0x' + ('{0:x}' -f $port))) 'mpc-web set WebServerPort'
+ Check ($reg -match ('0x' + ('{0:x}' -f $port))) 'player-setup set WebServerPort'
$reg = (reg query 'HKCU\Software\MPC-HC\MPC-HC\Settings' /v WebServerLocalhostOnly 2>&1) -join "`n"
- Check ($reg -match '0x1') 'mpc-web made the web interface answer this PC only'
- Check ($mw.message -match 'this PC only') 'mpc-web says so'
+ Check ($reg -match '0x1') 'player-setup made the web interface answer this PC only'
+ Check ($mw.message -match 'this PC only') 'player-setup says so'
# a second launch hands over to the running copy and exits
$second = Start-Process $app -PassThru
@@ -169,10 +169,10 @@ try {
Check (WaitFor { ([regex]::Matches((Get-Content $discordLog -Raw), '(?> "$GITHUB_ENV"
echo "NEXT=$next" >> "$GITHUB_ENV"
diff --git a/tools/downloads/main.go b/tools/downloads/main.go
index b288b11..170fcc1 100644
--- a/tools/downloads/main.go
+++ b/tools/downloads/main.go
@@ -33,7 +33,7 @@ type asset struct {
Count int `json:"download_count"`
}
-// baseline is the count of every release file when counting started ("v0.9.38/MPCvibedRPC.exe": 3).
+// baseline is the count of every release file when counting started ("v0.9.38/MPRP.exe": 3).
type baseline struct {
At string `json:"at"`
Counts map[string]int `json:"counts"`
@@ -55,9 +55,21 @@ type summary struct {
ByRelease map[string]int `json:"byRelease"`
}
+// programPrefixes start the names of the program files: the current name, and the former one (the files of every
+// release before the rename, and the copies under that name that later releases carry for installs from before it).
+var programPrefixes = []string{"MPRP", "MPCvibedRPC"}
+
// isProgram: the files people download to run the program.
func isProgram(name string) bool {
- return strings.HasPrefix(name, "MPCvibedRPC") && !strings.HasSuffix(name, ".sha256")
+ if strings.HasSuffix(name, ".sha256") {
+ return false
+ }
+ for _, p := range programPrefixes {
+ if strings.HasPrefix(name, p) {
+ return true
+ }
+ }
+ return false
}
func readJSON(path string, v any) error {
diff --git a/tools/downloads/main_test.go b/tools/downloads/main_test.go
index 062d729..97ba239 100644
--- a/tools/downloads/main_test.go
+++ b/tools/downloads/main_test.go
@@ -19,23 +19,23 @@ func rel(tag string, counts ...any) release {
// and notices never count, drafts are left out, and a recorded download GitHub has not counted yet never goes below 0.
func TestCount(t *testing.T) {
rels := []release{
- rel("v0.9.1", "MPCvibedRPC.exe", 9, "MPCvibedRPC.exe.sha256", 5, "LICENSE", 4),
- rel("v0.9.2", "MPCvibedRPC.exe", 7, "MPCvibedRPC-macos.zip", 3, "MPCvibedRPC-linux-amd64", 2, "MPCvibedRPC.exe.sha256", 6),
- {Tag: "v0.9.3", Draft: true, Assets: []asset{{Name: "MPCvibedRPC.exe", Count: 2}}},
+ rel("v0.9.1", "MPRP.exe", 9, "MPRP.exe.sha256", 5, "LICENSE", 4),
+ rel("v0.9.2", "MPRP.exe", 7, "MPRP-macos.zip", 3, "MPRP-linux-amd64", 2, "MPRP.exe.sha256", 6),
+ {Tag: "v0.9.3", Draft: true, Assets: []asset{{Name: "MPRP.exe", Count: 2}}},
}
- base := baseline{At: "2026-01-01T00:00:00Z", Counts: map[string]int{"v0.9.1/MPCvibedRPC.exe": 4, "v0.9.1/LICENSE": 4}}
+ base := baseline{At: "2026-01-01T00:00:00Z", Counts: map[string]int{"v0.9.1/MPRP.exe": 4, "v0.9.1/LICENSE": 4}}
dev := map[string]int{
- "v0.9.1/MPCvibedRPC.exe": 3, // 9 - 4 - 3 = 2 people
- "v0.9.2/MPCvibedRPC.exe": 4, // a release after the baseline: 7 - 4 = 3 people
- "v0.9.2/MPCvibedRPC-macos.zip": 3,
- "v0.9.2/MPCvibedRPC-linux-amd64": 5, // GitHub has counted 2 of 5 so far
- "v0.9.2/MPCvibedRPC.exe.sha256": 6,
+ "v0.9.1/MPRP.exe": 3, // 9 - 4 - 3 = 2 people
+ "v0.9.2/MPRP.exe": 4, // a release after the baseline: 7 - 4 = 3 people
+ "v0.9.2/MPRP-macos.zip": 3,
+ "v0.9.2/MPRP-linux-amd64": 5, // GitHub has counted 2 of 5 so far
+ "v0.9.2/MPRP.exe.sha256": 6,
}
s := count(rels, base, dev)
if s.People != 5 || s.Development != 12 || s.NotCountedYet != 3 {
t.Fatalf("people %d, development %d, not counted yet %d; want 5, 12, 3", s.People, s.Development, s.NotCountedYet)
}
- if s.ByFile["MPCvibedRPC.exe"] != 5 || s.ByRelease["v0.9.1"] != 2 || s.ByRelease["v0.9.2"] != 3 || len(s.ByFile) != 1 {
+ if s.ByFile["MPRP.exe"] != 5 || s.ByRelease["v0.9.1"] != 2 || s.ByRelease["v0.9.2"] != 3 || len(s.ByFile) != 1 {
t.Errorf("by file %v, by release %v", s.ByFile, s.ByRelease)
}
if b := badge(s); b["message"] != "5" || b["schemaVersion"] != 1 {
@@ -47,8 +47,8 @@ func TestCount(t *testing.T) {
// page), and every ledger file added up.
func TestFiles(t *testing.T) {
dir := t.TempDir()
- pages := `[{"tag_name":"v0.9.1","assets":[{"name":"MPCvibedRPC.exe","download_count":4}]}]
-[{"tag_name":"v0.9.2","assets":[{"name":"MPCvibedRPC.exe","download_count":6}]}]`
+ pages := `[{"tag_name":"v0.9.1","assets":[{"name":"MPRP.exe","download_count":4}]}]
+[{"tag_name":"v0.9.2","assets":[{"name":"MPRP.exe","download_count":6}]}]`
relFile := filepath.Join(dir, "releases.json")
os.WriteFile(relFile, []byte(pages), 0o644)
rels, err := readReleases(relFile)
@@ -56,19 +56,37 @@ func TestFiles(t *testing.T) {
t.Fatalf("releases %v, %v", rels, err)
}
b := newBaseline(rels[:1], time.Unix(0, 0))
- if b.Counts["v0.9.1/MPCvibedRPC.exe"] != 4 {
+ if b.Counts["v0.9.1/MPRP.exe"] != 4 {
t.Fatalf("baseline %v", b)
}
os.MkdirAll(filepath.Join(dir, "ledger"), 0o755)
- os.WriteFile(filepath.Join(dir, "ledger", "a.json"), []byte(`{"by":"release check","at":"2026-01-02T10:00:00Z","files":{"v0.9.2/MPCvibedRPC.exe":2}}`), 0o644)
- os.WriteFile(filepath.Join(dir, "ledger", "b.json"), []byte(`{"by":"agent","at":"2026-01-03T10:00:00Z","files":{"v0.9.2/MPCvibedRPC.exe":1}}`), 0o644)
+ os.WriteFile(filepath.Join(dir, "ledger", "a.json"), []byte(`{"by":"release check","at":"2026-01-02T10:00:00Z","files":{"v0.9.2/MPRP.exe":2}}`), 0o644)
+ os.WriteFile(filepath.Join(dir, "ledger", "b.json"), []byte(`{"by":"agent","at":"2026-01-03T10:00:00Z","files":{"v0.9.2/MPRP.exe":1}}`), 0o644)
// before the baseline: already in its counts
- os.WriteFile(filepath.Join(dir, "ledger", "c.json"), []byte(`{"by":"agent","at":"2026-01-01T10:00:00Z","files":{"v0.9.2/MPCvibedRPC.exe":5}}`), 0o644)
+ os.WriteFile(filepath.Join(dir, "ledger", "c.json"), []byte(`{"by":"agent","at":"2026-01-01T10:00:00Z","files":{"v0.9.2/MPRP.exe":5}}`), 0o644)
dev, err := ledger(filepath.Join(dir, "ledger"), "2026-01-02T00:00:00Z")
- if err != nil || dev["v0.9.2/MPCvibedRPC.exe"] != 3 {
+ if err != nil || dev["v0.9.2/MPRP.exe"] != 3 {
t.Fatalf("ledger %v, %v", dev, err)
}
if s := count(rels, b, dev); s.People != 3 || s.Development != 3 {
t.Errorf("people %d, development %d; want 3, 3", s.People, s.Development)
}
}
+
+// The files of the releases before the rename, and the copies under the former name that later releases carry, count
+// as the program like the current files; their checksums never do.
+func TestFormerNamesCount(t *testing.T) {
+ for name, want := range map[string]bool{
+ "MPRP.exe": true, "MPRP-linux-arm64": true, "MPRP-macos.zip": true,
+ "MPCvibedRPC.exe": true, "MPCvibedRPC-linux-amd64": true, "MPCvibedRPC-macos.zip": true,
+ "MPRP.exe.sha256": false, "MPCvibedRPC.exe.sha256": false, "LICENSE": false, "THIRD-PARTY-NOTICES.md": false,
+ } {
+ if got := isProgram(name); got != want {
+ t.Errorf("isProgram(%q) = %v, want %v", name, got, want)
+ }
+ }
+ s := count([]release{rel("v1.0.0", "MPRP.exe", 3, "MPCvibedRPC.exe", 2, "MPCvibedRPC.exe.sha256", 9)}, baseline{}, nil)
+ if s.People != 5 || s.ByFile["MPRP.exe"] != 3 || s.ByFile["MPCvibedRPC.exe"] != 2 {
+ t.Errorf("people %d, by file %v", s.People, s.ByFile)
+ }
+}
diff --git a/tools/mkico/icns.go b/tools/mkico/icns.go
index 1b1b64e..30c1742 100644
--- a/tools/mkico/icns.go
+++ b/tools/mkico/icns.go
@@ -3,9 +3,9 @@ package main
import (
"bytes"
"encoding/binary"
- "image"
- "image/color"
"image/png"
+
+ "github.com/CptPakundo/MPRP/internal/logo"
)
// icnsTypes are the PNG entries of a macOS .icns file, by pixel size.
@@ -19,15 +19,8 @@ var icnsTypes = []struct {
// pngOf draws the icon at one size.
func pngOf(n int) []byte {
- img := image.NewNRGBA(image.Rect(0, 0, n, n))
- for y := 0; y < n; y++ {
- for x := 0; x < n; x++ {
- r, g, b, a := pixel(n, x, y)
- img.SetNRGBA(x, y, color.NRGBA{r, g, b, a})
- }
- }
var out bytes.Buffer
- _ = png.Encode(&out, img)
+ _ = png.Encode(&out, logo.Image(n, false))
return out.Bytes()
}
diff --git a/tools/mkico/main.go b/tools/mkico/main.go
index 6859d76..d2b2517 100644
--- a/tools/mkico/main.go
+++ b/tools/mkico/main.go
@@ -1,8 +1,9 @@
-// mkico writes internal/assets/icon.ico: a blurple rounded square with a white play triangle, drawn at every
-// size Windows asks for from 100% to 250% scaling (16, 24, 32, 40, 48, 64 pixels, 32-bit BMP frames).
+// mkico writes internal/assets/icon.ico: the program's logo (internal/logo, a play triangle over a progress bar on an
+// indigo tile), drawn at every size Windows asks for from 100% to 250% scaling (16, 24, 32, 40, 48, 64 pixels, 32-bit
+// BMP frames).
//
// go run ./tools/mkico -out internal/assets/icon.ico
-// go run ./tools/mkico -icns MPCvibedRPC.icns (the macOS app icon, made when the app is packaged)
+// go run ./tools/mkico -icns MPRP.icns (the macOS app icon, made when the app is packaged)
// go run ./tools/mkico -png docs/images/icon.png (a 256-pixel logo for the README)
// go run ./tools/mkico -dot -out internal/assets/icon-update.ico (the tray icon while an update is waiting)
package main
@@ -12,8 +13,9 @@ import (
"encoding/binary"
"flag"
"fmt"
- "math"
"os"
+
+ "github.com/CptPakundo/MPRP/internal/logo"
)
var sizes = []int{16, 24, 32, 40, 48, 64}
@@ -37,64 +39,6 @@ func main() {
}
}
-// Shape in unit coordinates (0..1).
-const radius = 0.15
-
-var tri = [3][2]float64{{0.375, 0.2708}, {0.375, 0.7292}, {0.75, 0.5}}
-
-func inRoundRect(x, y float64) bool {
- dx := math.Max(math.Max(radius-x, x-(1-radius)), 0)
- dy := math.Max(math.Max(radius-y, y-(1-radius)), 0)
- return dx*dx+dy*dy <= radius*radius
-}
-
-func inTriangle(x, y float64) bool {
- sign := func(a, b [2]float64) float64 { return (x-b[0])*(a[1]-b[1]) - (a[0]-b[0])*(y-b[1]) }
- d1, d2, d3 := sign(tri[0], tri[1]), sign(tri[1], tri[2]), sign(tri[2], tri[0])
- neg := d1 < 0 || d2 < 0 || d3 < 0
- pos := d1 > 0 || d2 > 0 || d3 > 0
- return !(neg && pos)
-}
-
-// The update dot: a red circle in the top right corner, cut out of the icon by a transparent ring so it stands apart
-// at 16 pixels too.
-const dotX, dotY, dotR, dotRing = 0.79, 0.21, 0.21, 0.07
-
-func inDot(x, y, r float64) bool { return (x-dotX)*(x-dotX)+(y-dotY)*(y-dotY) <= r*r }
-
-// pixel is the colour of one pixel of the n x n icon (y counted from the top), supersampled 8x8: blurple, white
-// inside the triangle, transparent outside the rounded square.
-func pixel(n, x, y int) (r, g, b, a byte) { return pixelDot(n, x, y, false) }
-
-// pixelDot is pixel, with the update dot when dot is set.
-func pixelDot(n, x, y int, dot bool) (r, g, b, a byte) {
- const ss = 8
- var cover, white, red float64
- for sy := 0; sy < ss; sy++ {
- for sx := 0; sx < ss; sx++ {
- u, v := (float64(x)+(float64(sx)+0.5)/ss)/float64(n), (float64(y)+(float64(sy)+0.5)/ss)/float64(n)
- if dot && inDot(u, v, dotR) {
- cover++
- red++
- } else if dot && inDot(u, v, dotR+dotRing) {
- continue // the gap around the dot
- } else if inRoundRect(u, v) {
- cover++
- if inTriangle(u, v) {
- white++
- }
- }
- }
- }
- if cover == 0 {
- return 0, 0, 0, 0
- }
- w, rd := white/cover, red/cover
- // blurple, mixed with white (the triangle) and Discord's red (the dot) by how much of the pixel each covers
- ch := func(blue, full, dotc float64) byte { return byte(math.Round(blue + (full-blue)*w + (dotc-blue)*rd)) }
- return ch(88, 255, 237), ch(101, 255, 66), ch(242, 255, 69), byte(math.Round(255 * cover / (ss * ss)))
-}
-
// frame returns the BMP-in-ICO payload (header, bottom-up BGRA pixels, empty AND mask) for one size.
func frame(n int, dot bool) []byte {
b := new(bytes.Buffer)
@@ -106,10 +50,11 @@ func frame(n int, dot bool) []byte {
X, Y int32
Used, Imp uint32
}{40, int32(n), int32(2 * n), 1, 32, 0, uint32(4 * n * n), 0, 0, 0, 0})
+ img := logo.Image(n, dot)
for y := n - 1; y >= 0; y-- {
for x := 0; x < n; x++ {
- r, g, bl, a := pixelDot(n, x, y, dot)
- b.Write([]byte{bl, g, r, a})
+ c := img.NRGBAAt(x, y)
+ b.Write([]byte{c.B, c.G, c.R, c.A})
}
}
b.Write(make([]byte, ((n+31)/32*4)*n)) // AND mask, unused with an alpha channel
diff --git a/tools/mkico/main_test.go b/tools/mkico/main_test.go
index 03c3296..bc76a50 100644
--- a/tools/mkico/main_test.go
+++ b/tools/mkico/main_test.go
@@ -54,3 +54,14 @@ func TestCommittedUpdateIconMatchesGenerator(t *testing.T) {
t.Fatal("the update icon has no dot")
}
}
+
+// The README's logo is generated too.
+func TestCommittedLogoPNGMatchesGenerator(t *testing.T) {
+ have, err := os.ReadFile("../../docs/images/icon.png")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(have, pngOf(256)) {
+ t.Fatal("docs/images/icon.png is out of date: run go run ./tools/mkico -png docs/images/icon.png")
+ }
+}
diff --git a/tools/mkrsrc/main.go b/tools/mkrsrc/main.go
index 5364163..e54510f 100644
--- a/tools/mkrsrc/main.go
+++ b/tools/mkrsrc/main.go
@@ -1,8 +1,8 @@
// mkrsrc writes a Windows resource object (.syso) holding the program's icon, version information and application manifest (per-monitor DPI awareness), so the
-// finished MPCvibedRPC.exe has an icon in Explorer and proper details in Task Manager. The Go linker picks the
+// finished MPRP.exe has an icon in Explorer and proper details in Task Manager. The Go linker picks the
// .syso up automatically when it sits next to the main package. Standard library only.
//
-// go run ./tools/mkrsrc -icon internal/assets/icon.ico -version X.Y.Z -out cmd/mpcvibedrpc/rsrc_windows_amd64.syso
+// go run ./tools/mkrsrc -icon internal/assets/icon.ico -version X.Y.Z -out cmd/mprp/rsrc_windows_amd64.syso
package main
import (
@@ -286,12 +286,12 @@ func versionInfo(version string) ([]byte, error) {
for _, kv := range [][2]string{
{"CompanyName", ""},
{"Comments", "Made with AI (vibe coded). MIT License, no warranty."},
- {"FileDescription", "MPCvibedRPC - Discord Rich Presence for MPC-HC, MPC-BE, MPC-QT, mpv, VLC, PotPlayer, IINA, Kodi, Plex, Stremio, Jellyfin and Emby"},
+ {"FileDescription", "MPRP - Media Player Rich Presence: Discord status for MPC-HC, MPC-BE, MPC-QT, mpv, VLC, PotPlayer, IINA, Kodi, Plex, Stremio, Jellyfin and Emby"},
{"FileVersion", version},
- {"InternalName", "MPCvibedRPC"},
+ {"InternalName", "MPRP"},
{"LegalCopyright", "MIT License"},
- {"OriginalFilename", "MPCvibedRPC.exe"},
- {"ProductName", "MPCvibedRPC"},
+ {"OriginalFilename", "MPRP.exe"},
+ {"ProductName", "MPRP"},
{"ProductVersion", version},
} {
strs = append(strs, str(kv[0], kv[1]))
diff --git a/tools/relnotes/main.go b/tools/relnotes/main.go
index c7f51ce..d9bd2c4 100644
--- a/tools/relnotes/main.go
+++ b/tools/relnotes/main.go
@@ -70,7 +70,7 @@ func build(version, changelogPath, advisoryPath string) (string, error) {
// render lays the text out: heading, the changelog's lines as a list, the hand-written block, the footer.
func render(e entry, extra string) string {
var b strings.Builder
- fmt.Fprintf(&b, "## MPCvibedRPC %s\n\n", e.Version)
+ fmt.Fprintf(&b, "## MPRP %s\n\n", e.Version)
b.WriteString("### What's new\n")
for _, it := range e.Items {
b.WriteString("- " + strings.TrimSpace(it) + "\n")
@@ -87,13 +87,13 @@ Nothing to do: the update installs itself (Windows and Linux, unless you switche
sign-ins are kept.
### Get it
-- **Windows:** download **` + "`MPCvibedRPC.exe`" + `** and run it, or install it from the Updates section of the version you
+- **Windows:** download **` + "`MPRP.exe`" + `** and run it, or install it from the Updates section of the version you
have. Your settings are kept.
-- **macOS 13 or later:** download **` + "`MPCvibedRPC-macos.zip`" + `** and move the app to Applications (the first time,
+- **macOS 13 or later:** download **` + "`MPRP-macos.zip`" + `** and move the app to Applications (the first time,
System Settings > Privacy & Security > **Open Anyway**).
-- **Linux:** download **` + "`MPCvibedRPC-linux-amd64`" + `** (or ` + "`-arm64`" + `), ` + "`chmod +x`" + ` it and run it.
+- **Linux:** download **` + "`MPRP-linux-amd64`" + `** (or ` + "`-arm64`" + `), ` + "`chmod +x`" + ` it and run it.
Every system needs the Discord desktop app with User Settings > Activity Privacy > "Share my activity" on (Activity
Privacy is in the Games & Apps section, called Activity Settings in older Discord versions). To check a download, see
-[SECURITY.md](https://github.com/CptPakundo/MPCvibedRPC/blob/master/SECURITY.md).
+[SECURITY.md](https://github.com/CptPakundo/MPRP/blob/master/SECURITY.md).
`
diff --git a/tools/relnotes/main_test.go b/tools/relnotes/main_test.go
index 3f82c19..f050e23 100644
--- a/tools/relnotes/main_test.go
+++ b/tools/relnotes/main_test.go
@@ -22,7 +22,7 @@ func TestBuild(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, want := range []string{"## MPCvibedRPC 9.9.9\n", "- 🧹 Sample line one.\n- 🔒 Sample line two.\n", "### Get it", "MPCvibedRPC.exe"} {
+ for _, want := range []string{"## MPRP 9.9.9\n", "- 🧹 Sample line one.\n- 🔒 Sample line two.\n", "### Get it", "MPRP.exe"} {
if !strings.Contains(text, want) {
t.Errorf("missing %q in:\n%s", want, text)
}
@@ -59,7 +59,7 @@ func TestRealChangelogRenders(t *testing.T) {
v := string(raw[i+len(`"version": "`):])
v = v[:strings.Index(v, `"`)]
text, err := build(v, path, filepath.Join(t.TempDir(), "none.md"))
- if err != nil || !strings.HasPrefix(text, "## MPCvibedRPC "+v+"\n") {
+ if err != nil || !strings.HasPrefix(text, "## MPRP "+v+"\n") {
t.Fatalf("%v\n%s", err, text)
}
}
diff --git a/tools/screenshots/demo.js b/tools/screenshots/demo.js
index c6982d1..9b8cc54 100644
--- a/tools/screenshots/demo.js
+++ b/tools/screenshots/demo.js
@@ -1,17 +1,17 @@
-// Shows a made-up "Sample Show" playing in the settings window, for the README screenshots (docs/images). Paste it
-// into the page of a throwaway copy (see "Screenshots" in docs/maintaining.md); nothing is sent to Discord or a player. It only
+// Shows a made-up "Sample Show" playing in the settings window, for the README screenshots (docs/images). take.js
+// runs it in the page of a throwaway copy (see "Screenshots" in docs/maintaining.md); nothing is sent to Discord or a player. It only
// changes what the page is told: the status line, the preview of the Discord card and Your stats.
(() => {
const real = window.__realFetch || window.fetch;
window.__realFetch = real;
const start = Date.now() - 744000; // 12:24 into a 48-minute episode
const status = {
- running: true, discord: 'connected', mpc: true, player: 'MPC-HC', nowPlaying: 'Sample Show - S01E02 - Episode title',
+ running: true, discord: 'connected', mpc: true, playerAnswers: true, player: 'MPC-HC', nowPlaying: 'Sample Show - S01E02 - Episode title',
paused: false, pauseCleared: false, hidden: false, lastError: null, since: start,
preview: {
watching: true, name: 'Sample Show', details: 'S01E02 · Episode title', state: 'Drama, Mystery · ★ 8.1',
largeText: 'Season 1, Episode 2', start, end: start + 2880000, button: 'View on IMDb', button2: 'View on TVmaze',
- smallImage: 'https://raw.githubusercontent.com/CptPakundo/MPCvibedRPC/master/docs/players/mpc-hc.png', smallText: 'Media Player Classic',
+ smallImage: 'https://raw.githubusercontent.com/CptPakundo/MPRP/master/docs/players/mpc-hc.png', smallText: 'Media Player Classic',
},
};
const stats = { since: '2026-10-01', videos: 14, matched: 11, watchedMs: 19260000, players: { 'MPC-HC': 9, Plex: 4, VLC: 1 } };
diff --git a/tools/screenshots/take.js b/tools/screenshots/take.js
new file mode 100644
index 0000000..475b3bb
--- /dev/null
+++ b/tools/screenshots/take.js
@@ -0,0 +1,250 @@
+// Takes the README screenshots (docs/images/window-main.jpg, window-privacy.jpg, window-plex.jpg) from a throwaway copy
+// of the program, in a headless Edge or Chrome with a profile of its own. Node.js 22 or later, nothing to install.
+//
+// node tools/screenshots/take.js [--out docs/images] [--quality 70]
+//
+// The copy gets a temporary data folder (MPRP_HOME) and opens no window (MPRP_BROWSER=none); showing on Discord,
+// update checks and autostart are off, and its players point nowhere (port 1, no mpv pipe, no VLC or Kodi password),
+// so it contacts nothing. window-main shows made-up playback from demo.js. The copy is quit and both temporary
+// folders are deleted at the end. The browser is found in the usual places; MPRP_SHOT_BROWSER names another one.
+'use strict';
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawn, execFileSync } = require('child_process');
+
+// The program's own window: Edge's --window-size=660,800 (internal/winsys/window.go) leaves a 660 x 760 page. The
+// pictures are 800 pixels wide.
+const PAGE = { width: 660, height: 760 };
+const WIDTH = 800;
+
+function usage(msg) {
+ if (msg) console.error(msg);
+ console.error('usage: node tools/screenshots/take.js [--out ] [--quality <1-100>]');
+ process.exit(2);
+}
+
+function parseArgs(argv) {
+ const o = { out: path.join(__dirname, '..', '..', 'docs', 'images'), quality: 70 };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--out') o.out = argv[++i];
+ else if (a === '--quality') o.quality = Number(argv[++i]);
+ else if (a.startsWith('-')) usage('unknown option ' + a);
+ else if (!o.program) o.program = path.resolve(a);
+ else usage('one program only');
+ }
+ if (!o.program || !fs.existsSync(o.program)) usage('name the program you built');
+ if (!(o.quality >= 1 && o.quality <= 100)) usage('--quality is 1 to 100');
+ if (!o.out) usage('--out needs a folder');
+ return o;
+}
+
+function findBrowser() {
+ if (process.env.MPRP_SHOT_BROWSER) return process.env.MPRP_SHOT_BROWSER;
+ const list = [];
+ if (process.platform === 'win32') {
+ for (const base of [process.env['ProgramFiles(x86)'], process.env.ProgramFiles, process.env.LOCALAPPDATA]) {
+ if (!base) continue;
+ list.push(path.join(base, 'Microsoft', 'Edge', 'Application', 'msedge.exe'));
+ list.push(path.join(base, 'Google', 'Chrome', 'Application', 'chrome.exe'));
+ }
+ } else if (process.platform === 'darwin') {
+ list.push('/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge');
+ list.push('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome');
+ list.push('/Applications/Chromium.app/Contents/MacOS/Chromium');
+ } else {
+ for (const dir of (process.env.PATH || '').split(':')) {
+ for (const name of ['microsoft-edge', 'google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']) {
+ list.push(path.join(dir, name));
+ }
+ }
+ }
+ const found = list.find((p) => fs.existsSync(p));
+ if (!found) throw new Error('no Edge or Chrome found: set MPRP_SHOT_BROWSER to one');
+ return found;
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function waitFor(what, fn, ms = 20000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await fn().catch(() => null);
+ if (v) return v;
+ if (Date.now() > end) throw new Error('timed out waiting for ' + what);
+ await sleep(200);
+ }
+}
+
+// rmrf deletes a folder, retrying while a process that just quit still holds files in it.
+async function rmrf(dir) {
+ for (let i = 0; i < 25; i++) {
+ try { fs.rmSync(dir, { recursive: true, force: true }); return; } catch (_) { await sleep(400); }
+ }
+ console.error('could not delete ' + dir + ': delete it by hand');
+}
+
+// startCopy starts the throwaway copy and returns how to reach its API.
+async function startCopy(program, home) {
+ const config = {
+ port: 1, mpvPipe: '', vlcPassword: '', kodiPassword: '',
+ app: { autoStart: false, startPresence: false, checkUpdates: false, autoUpdate: false, welcomeSeen: true, openWindow: false },
+ };
+ fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config, null, 2));
+ const env = { ...process.env, MPRP_HOME: home, MPRP_BROWSER: 'none' };
+ const child = spawn(program, [], { env, stdio: 'ignore' });
+ const ipc = await waitFor('the copy to start', async () => JSON.parse(fs.readFileSync(path.join(home, 'ipc.json'), 'utf8')));
+ const base = 'http://127.0.0.1:' + ipc.port;
+ const api = async (name, body) => {
+ const res = await fetch(base + '/api/' + name, {
+ method: body === undefined ? 'GET' : 'POST',
+ headers: { 'X-Token': ipc.token, 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ if (!res.ok) throw new Error(name + ': HTTP ' + res.status);
+ return res.json();
+ };
+ return { child, base, token: ipc.token, api };
+}
+
+// cdp is a minimal Chrome DevTools Protocol client over the browser's WebSocket.
+function cdp(url) {
+ const ws = new WebSocket(url);
+ let id = 0;
+ const waiting = new Map();
+ const listeners = [];
+ ws.onmessage = (ev) => {
+ const m = JSON.parse(ev.data);
+ if (m.id && waiting.has(m.id)) {
+ const { ok, fail } = waiting.get(m.id);
+ waiting.delete(m.id);
+ if (m.error) fail(new Error(m.error.message)); else ok(m.result);
+ } else if (m.method) {
+ listeners.forEach((l) => l(m));
+ }
+ };
+ const open = new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = () => fail(new Error('cannot reach the browser')); });
+ return {
+ open,
+ send(method, params = {}) {
+ return new Promise((ok, fail) => { const n = ++id; waiting.set(n, { ok, fail }); ws.send(JSON.stringify({ id: n, method, params })); });
+ },
+ on(method, fn) { listeners.push((m) => { if (m.method === method) fn(m.params); }); },
+ once(method) { return new Promise((ok) => { const l = (m) => { if (m.method === method) { listeners.splice(listeners.indexOf(l), 1); ok(m.params); } }; listeners.push(l); }); },
+ close() { ws.close(); },
+ };
+}
+
+async function main() {
+ const o = parseArgs(process.argv.slice(2));
+ const browser = findBrowser();
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'mprp-shots-home-'));
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'mprp-shots-browser-'));
+ let copy, edge, page;
+ try {
+ copy = await startCopy(o.program, home);
+ const state = await copy.api('state');
+ await copy.api('save', { app: { seenVersion: state.version } }); // keeps the What's new box closed
+
+ edge = spawn(browser, [
+ '--headless=new', '--user-data-dir=' + profile, '--remote-debugging-port=0', '--no-first-run',
+ '--no-default-browser-check', '--disable-extensions', 'about:blank',
+ ], { stdio: 'ignore' });
+ const devPort = await waitFor('the browser to start', async () => fs.readFileSync(path.join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0].trim());
+ const target = await waitFor('the browser page', async () => {
+ const list = await (await fetch('http://127.0.0.1:' + devPort + '/json/list')).json();
+ return list.find((t) => t.type === 'page');
+ });
+ page = cdp(target.webSocketDebuggerUrl);
+ await page.open;
+ await page.send('Page.enable');
+ await page.send('Emulation.setDeviceMetricsOverride', { width: PAGE.width, height: PAGE.height, deviceScaleFactor: WIDTH / PAGE.width, mobile: false });
+ await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
+ // The player logos come from this checkout's docs/players, not from GitHub: the pictures show the logos as they
+ // are here, and nothing is fetched.
+ const logos = path.join(__dirname, '..', '..', 'docs', 'players');
+ page.on('Fetch.requestPaused', (p) => {
+ const file = path.join(logos, path.basename(new URL(p.request.url).pathname));
+ if (!fs.existsSync(file)) return page.send('Fetch.failRequest', { requestId: p.requestId, errorReason: 'FileNotFound' }).catch(() => {});
+ page.send('Fetch.fulfillRequest', {
+ requestId: p.requestId, responseCode: 200, responseHeaders: [{ name: 'Content-Type', value: 'image/png' }],
+ body: fs.readFileSync(file).toString('base64'),
+ }).catch(() => {});
+ });
+ await page.send('Fetch.enable', { patterns: [{ urlPattern: '*/docs/players/*.png' }] });
+
+ const js = async (expr) => {
+ const r = await page.send('Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true });
+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.text + ' in ' + expr.slice(0, 60));
+ return r.result.value;
+ };
+ const load = async () => {
+ const done = page.once('Page.loadEventFired');
+ await page.send('Page.navigate', { url: copy.base + '/?t=' + copy.token });
+ await done;
+ await waitFor('the settings page', () => js("!!document.querySelector('#tab-privacy')"));
+ };
+ const settle = async () => {
+ await js('document.fonts.ready.then(() => true)');
+ await waitFor('the pictures', () => js('[...document.images].every((i) => i.complete)'));
+ const broken = await js("[...document.images].filter((i) => i.offsetParent && !i.naturalWidth).map((i) => i.src)");
+ if (broken.length) throw new Error('pictures that did not load: ' + broken.join(', '));
+ await sleep(800);
+ };
+ const shoot = async (name) => {
+ const shot = await page.send('Page.captureScreenshot', { format: 'jpeg', quality: o.quality });
+ const file = path.join(o.out, name);
+ fs.writeFileSync(file, Buffer.from(shot.data, 'base64'));
+ console.log(file + ' (' + fs.statSync(file).size + ' bytes)');
+ };
+ // scroll brings an element to the top of the panel that scrolls it, or (bottom) scrolls that panel to its
+ // end.
+ const scroll = (selector, bottom) => js(`(() => {
+ const t = ${selector};
+ let s = t.parentElement;
+ while (s && !(s.scrollHeight > s.clientHeight && /(auto|scroll)/.test(getComputedStyle(s).overflowY))) s = s.parentElement;
+ if (!s) throw new Error('nothing scrolls');
+ s.scrollTop = ${bottom ? 's.scrollHeight' : 's.scrollTop + t.getBoundingClientRect().top - s.getBoundingClientRect().top'};
+ return true;
+ })()`);
+
+ // window-main: the General tab with demo.js's made-up playback.
+ await load();
+ await js(fs.readFileSync(path.join(__dirname, 'demo.js'), 'utf8') + ';true');
+ await waitFor('the sample playback', () => js("document.body.innerText.includes('Sample Show')"));
+ await settle();
+ await shoot('window-main.jpg');
+
+ // window-privacy: a fresh page (not showing on Discord), Privacy tab at "Services that may see your titles".
+ await load();
+ await js("document.querySelector('#tab-privacy').click(), true");
+ await scroll("document.querySelector('#fl-disabledSources')", false);
+ await settle();
+ await shoot('window-privacy.jpg');
+
+ // window-plex: the Players tab scrolled to its end (Plex, Stremio, Jellyfin / Emby).
+ await js("document.querySelector('#tab-players').click(), true");
+ await scroll("document.querySelector('#p-players')", true);
+ await settle();
+ await shoot('window-plex.jpg');
+ } finally {
+ if (page) { await page.send('Browser.close').catch(() => {}); page.close(); }
+ if (edge && edge.exitCode === null) await Promise.race([new Promise((r) => edge.once('exit', r)), sleep(5000)]);
+ if (edge && edge.exitCode === null) edge.kill();
+ if (copy) {
+ await copy.api('quit', {}).catch(() => {});
+ await Promise.race([new Promise((r) => copy.child.once('exit', r)), sleep(5000)]);
+ if (copy.child.exitCode === null) {
+ try {
+ if (process.platform === 'win32') execFileSync('taskkill', ['/PID', String(copy.child.pid), '/F'], { stdio: 'ignore' });
+ else process.kill(copy.child.pid);
+ } catch (_) {}
+ }
+ }
+ await rmrf(profile);
+ await rmrf(home);
+ }
+}
+
+main().catch((e) => { console.error(e.message || e); process.exit(1); });